Skip to content

Commit a68b4c4

Browse files
sahrizviclaude
andcommitted
fix(workspace): unlink never deletes on a "not linked" answer; confirm a link as the captured credential (review)
- `workspace unlink` touches nothing when the service says the project is not linked: `Manage.unlink` deletes server-side, and the answer can be a cached miss that predates a new link. Reverts the local cleanup added in the previous commit; the skill sync already takes skills out of service on a confirmed unbind - `link` confirming an existing link derives the account from the captured credential, and a refused or failed record exits 1 instead of reporting the link as confirmed - Tests assert the list and bind run as the captured credential too Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018fJ3X7pcGT4R9yzjsJnqsV
1 parent ed1298a commit a68b4c4

3 files changed

Lines changed: 58 additions & 27 deletions

File tree

‎packages/opencode/src/cli/cmd/link.ts‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -989,8 +989,9 @@ export interface LinkHeadlessDeps {
989989
actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>,
990990
): Promise<ProjectBindingLookup | null>
991991
captureCredentials(): ReturnType<typeof WorkspaceApi.captureCredentials>
992-
/** Record on this machine that the user approved a link the service already has; no server call. */
993-
approve(identifier: ProjectIdentifier, existing: ProjectBindingLookup): Promise<void>
992+
/** Record on this machine that the user approved a link the service already has; no server call. Runs as
993+
* `actAs`, the credential the link was looked up with; false when nothing was recorded. */
994+
approve(identifier: ProjectIdentifier, existing: ProjectBindingLookup, actAs: ActAs): Promise<boolean>
994995
listDatamates(actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>): Promise<DatamateRef[]>
995996
bindOrRebind(
996997
identifier: ProjectIdentifier,
@@ -1051,7 +1052,23 @@ export async function linkHeadless(
10511052
// An explicit `link` for the workspace the service already has: record the user's approval here (a fresh clone
10521053
// only knows the link as discovered, which `workspace sync` refuses), without a redundant server rebind.
10531054
const alreadyLinked = async (lookup: ProjectBindingLookup): Promise<void> => {
1054-
await deps.approve(identifier, lookup)
1055+
let recorded: boolean
1056+
try {
1057+
recorded = await deps.approve(identifier, lookup, actAs)
1058+
} catch (err) {
1059+
deps.printError(
1060+
`The link was not confirmed on this machine: ${stripControlChars(err instanceof Error ? err.message : String(err))}`,
1061+
)
1062+
process.exitCode = 1
1063+
return
1064+
}
1065+
if (!recorded) {
1066+
deps.printError(
1067+
"Your Altimate account changed while linking, so the link was not confirmed on this machine. Re-run the command.",
1068+
)
1069+
process.exitCode = 1
1070+
return
1071+
}
10551072
deps.print(`Already linked to "${stripControlChars(lookup.datamate.name)}" — link confirmed on this machine.`)
10561073
}
10571074

@@ -1131,10 +1148,10 @@ function linkHeadlessDeps(directory: string): LinkHeadlessDeps {
11311148
isConfigured: () => AltimateApi.isConfigured(),
11321149
getBindingForProject: (identifier, actAs) => WorkspaceApi.getBindingForProject(identifier, actAs),
11331150
captureCredentials: () => WorkspaceApi.captureCredentials(),
1134-
approve: async (identifier, existing) => {
1135-
// Pinned to the account that confirmed the link: the record is refused if the account changed meanwhile.
1136-
const account = await accountDigest()
1137-
if (account === null) throw new Error("Could not read your Altimate credentials")
1151+
approve: async (identifier, existing, actAs) => {
1152+
// Pinned to the credential the link was looked up with: refused if the configured account is another one now.
1153+
const account = credentialDigest(actAs.url, actAs.instance, actAs.apiKey)
1154+
if ((await accountDigest()) !== account) return false
11381155
const seed = await recordApprovedBinding(
11391156
identifier.projectPath ?? directory,
11401157
{
@@ -1146,7 +1163,9 @@ function linkHeadlessDeps(directory: string): LinkHeadlessDeps {
11461163
},
11471164
{ awaitBackfill: true, account },
11481165
)
1166+
if (seed === null || seed.status === "account-changed") return false
11491167
UI.println(seedMessage(seed))
1168+
return true
11501169
},
11511170
listDatamates: (actAs) => WorkspaceApi.listDatamates(actAs),
11521171
bindOrRebind: (identifier, datamateId, existing, actAs) => bindOrRebind(identifier, datamateId, existing, true, directory, actAs),

‎packages/opencode/src/cli/cmd/workspace.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -173,14 +173,14 @@ async function linkOf(
173173
deps: WorkspaceDeps,
174174
json: boolean,
175175
directory: string,
176-
): Promise<{ binding: CachedBinding; stale: boolean } | { code: number; unbound?: true }> {
176+
): Promise<{ binding: CachedBinding; stale: boolean } | { code: number }> {
177177
const outcome = await deps.resolve(directory)
178178
if (outcome.status === "bound") return { binding: outcome.binding, stale: outcome.stale === true }
179179
if (outcome.status === "unbound") {
180180
// A "not linked" answered from the short-lived miss cache says so: a link made elsewhere in the last few
181181
// minutes would not show yet.
182182
const lines = outcome.stale ? [...NOT_LINKED_LINES, "(As of a check in the last few minutes.)"] : NOT_LINKED_LINES
183-
return { code: report(deps, json, EXIT.NOT_LINKED, { linked: false, stale: outcome.stale === true }, lines), unbound: true }
183+
return { code: report(deps, json, EXIT.NOT_LINKED, { linked: false, stale: outcome.stale === true }, lines) }
184184
}
185185
return {
186186
code: failure(deps, json, EXIT.FAILED, "Could not reach the workspace service to check whether this project is linked. Try again."),
@@ -251,12 +251,10 @@ export async function runUnlink(directory: string, json: boolean, yes: boolean,
251251
if (!(await deps.isConfigured())) return failure(deps, json, EXIT.USAGE, NOT_SIGNED_IN)
252252
try {
253253
const link = await linkOf(deps, json, directory)
254-
if ("code" in link) {
255-
// Already detached on the service (from another machine, or the web): the local side can still hold its
256-
// skills and memory overlay, which keep loading until they are cleared here.
257-
if (link.unbound) await deps.unlink(directory).catch(() => undefined)
258-
return link.code
259-
}
254+
// Nothing is touched when the service says "not linked": `Manage.unlink` deletes server-side, and the
255+
// answer may be a cached miss that predates a new link. A confirmed unbind already takes the workspace
256+
// skills out of service on the next skill sync (every turn, or `workspace refresh`).
257+
if ("code" in link) return link.code
260258
const name = stripControlChars(link.binding.datamateName)
261259
if (!yes) {
262260
if (!deps.isTTY() || json) return failure(deps, json, EXIT.USAGE, `Unlinking from "${name}" needs confirmation: pass --yes.`)

‎packages/opencode/test/cli/workspace-command.test.ts‎

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,8 @@ describe("workspace subcommands", () => {
183183
]) {
184184
const f = fakeDeps({ resolve: async () => ({ status: "unbound" }) })
185185
expect(await run(f.deps)).toBe(EXIT.NOT_LINKED)
186-
// Nothing is sent or changed on the service; unlink alone clears local state (tested below).
187-
expect(f.calls.filter((c) => c !== "unlink")).toEqual([])
186+
// Nothing is sent or changed: unlink included, since its delete could hit a link made after a cached miss.
187+
expect(f.calls).toEqual([])
188188
expect(f.json[0]).toMatchObject({ ok: false, linked: false })
189189
}
190190
})
@@ -254,12 +254,6 @@ describe("workspace subcommands", () => {
254254
expect(f.calls).toEqual([])
255255
})
256256

257-
test("unlink of a project the service already detached still clears local workspace state", async () => {
258-
const f = fakeDeps({ resolve: async () => ({ status: "unbound" }) })
259-
expect(await runUnlink("/p", false, true, f.deps)).toBe(EXIT.NOT_LINKED)
260-
expect(f.calls).toEqual(["unlink"])
261-
})
262-
263257
test("a 'not linked' answered from the recent-miss cache says so", async () => {
264258
const f = fakeDeps({ resolve: async () => ({ status: "unbound", stale: true }) })
265259
expect(await runStatus("/p", false, f.deps)).toBe(EXIT.NOT_LINKED)
@@ -298,9 +292,9 @@ describe("link --workspace / --create without prompting", () => {
298292
isConfigured: async () => true,
299293
getBindingForProject: async (_i, a) => (lookups.push(a === actAs ? "pinned" : "other"), null),
300294
captureCredentials: async () => actAs,
301-
approve: async (_i, e) => void calls.push(`approve:${e.datamate.id}`),
302-
listDatamates: async () => [growth, { id: 9, name: "Finance" }] as any,
303-
bindOrRebind: async (_i, id) => void calls.push(`bind:${id}`),
295+
approve: async (_i, e, a) => (calls.push(`approve:${e.datamate.id}`), lookups.push(`approve:${a === actAs ? "pinned" : "other"}`), true),
296+
listDatamates: async (a) => (lookups.push(`list:${a === actAs ? "pinned" : "other"}`), [growth, { id: 9, name: "Finance" }] as any),
297+
bindOrRebind: async (_i, id, _e, a) => void (calls.push(`bind:${id}`), lookups.push(`bind:${a === actAs ? "pinned" : "other"}`)),
304298
create: async (_i, name) => void calls.push(`create:${name}`),
305299
print: (l) => void out.push(l),
306300
printError: (l) => void err.push(l),
@@ -388,7 +382,27 @@ describe("link --workspace / --create without prompting", () => {
388382
test("the pre-check runs as the same captured credential as the list and the bind", async () => {
389383
const f = linkDeps()
390384
await linkHeadless({ directory: dir, workspace: "9", yes: false }, f.deps)
391-
expect(f.lookups).toEqual(["pinned"])
385+
expect(f.lookups).toEqual(["pinned", "list:pinned", "bind:pinned"])
386+
})
387+
388+
test("confirming an existing link runs as the captured credential", async () => {
389+
const f = linkDeps({ getBindingForProject: async () => ({ datamate: { id: 9, name: "Finance" }, binding: {} }) as any })
390+
await linkHeadless({ directory: dir, workspace: "9", yes: false }, f.deps)
391+
expect(f.lookups).toContain("approve:pinned")
392+
})
393+
394+
test("a link that could not be confirmed on this machine is a failure, not 'confirmed'", async () => {
395+
for (const approve of [async () => false, async () => Promise.reject(new Error("keychain locked"))]) {
396+
const f = linkDeps({
397+
getBindingForProject: async () => ({ datamate: { id: 9, name: "Finance" }, binding: {} }) as any,
398+
approve,
399+
})
400+
process.exitCode = 0
401+
await linkHeadless({ directory: dir, workspace: "9", yes: false }, f.deps)
402+
expect(process.exitCode).toBe(1)
403+
expect(f.out.join("\n")).not.toContain("link confirmed")
404+
expect(f.err.join("\n")).toContain("not confirmed on this machine")
405+
}
392406
})
393407

394408
test("--allow-duplicate still creates even when the project is linked to a workspace of that name", async () => {

0 commit comments

Comments
 (0)