From 4e0b5023d33698277653499fc0441ba3248000d3 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 21:16:21 +0530 Subject: [PATCH 01/11] fix: name the workspace and signed-in account when a link hits a hidden workspace When a project's remote is linked to a private workspace the caller cannot see, the service answers 409 with the workspace id and withholds its name. The link command and the TUI then said only "a workspace you can't see, most likely a teammate's", while the workspace menu said the project was not linked. A user signed in with a second account (or a support account) on the same instance had no way to tell which workspace held the link or which account they were looking through. The message now carries the workspace id the service returns and the email and instance of the account the request ran as, read from /users/me. The lookup is best effort: when it fails the message falls back to naming the workspace id alone. Server-sourced text is stripped of control and bidi characters before it reaches the terminal. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/api-client.ts | 67 +++++++++++++++++-- packages/opencode/src/cli/cmd/link.ts | 8 +-- .../src/plugin/tui/altimate/workspace.tsx | 10 +-- .../workspace/create-then-rebind.test.ts | 40 +++++++++-- .../workspace/link-seed-message.test.ts | 19 +++++- 5 files changed, 122 insertions(+), 22 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 5a35b8c549..4e957e5360 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -12,6 +12,7 @@ // for 409/412 and surface it as a typed error rather than a bare status code. import { AltimateApi } from "@/altimate/api/client" import { Telemetry } from "@/altimate/telemetry" +import { stripBidiControls } from "./workspace-name" const REQUEST_TIMEOUT_MS = 15_000 @@ -106,19 +107,55 @@ export class NotConfiguredError extends Error { } } +/** The account a request ran as, named in a hidden-binding conflict. */ +export interface SignedInAccount { + email: string + instance: string +} + +const plain = (text: string) => + // eslint-disable-next-line no-control-regex + stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")).trim() + /** A 409 whose `existing_datamate_name` is withheld: the server hides the name of a workspace - * the caller cannot see, which is almost always a teammate's private one. Reading that as a race - * ("another workspace claimed this project while you were choosing") sent users round a retry - * loop with no way out. */ -export const HIDDEN_BINDING_MESSAGE = - "This project is already linked to a workspace you can't see, most likely a teammate's private one. " + - "Ask its owner to share it with you in the Altimate web app, or to unlink the project, then run `altimate-code link` again." + * the caller cannot see. Reading that as a race ("another workspace claimed this project while + * you were choosing") sent users round a retry loop with no way out. + * + * The workspace is private to another account. That is a teammate's, or the same person's + * under another sign-in on the same instance (a second login, or a support account). A message + * that names neither the workspace nor the signed-in account leaves the second case + * undiagnosable: the person sees "not linked" in the menu and "already linked" on link, and + * nothing says which account they are looking through. So the message carries the workspace id + * (the server always returns it) and the account the request ran as, when known. */ +export function hiddenBindingMessage(detail: ConflictDetail, account?: SignedInAccount): string { + const id = typeof detail.existing_datamate_id === "number" ? ` (workspace id ${detail.existing_datamate_id})` : "" + const email = account ? plain(account.email) : "" + const instance = account ? plain(account.instance) : "" + const who = email + ? instance + ? `${email} on instance "${instance}"` + : email + : "the account you are signed in with" + return ( + `This project is already linked to a workspace${id} that ${who} can't see. ` + + "It is private to another account: a teammate's, or yours under a different sign-in. " + + "Sign in as that account, or ask its owner to share it with you in the Altimate web app or to unlink the project, " + + "then run `altimate-code link` again." + ) +} + +/** `hiddenBindingMessage` for a conflict, naming the account the request ran as. Never throws: + * when the account cannot be read, the message says so generically. */ +export async function describeHiddenBinding(err: unknown, actAs?: ActAs): Promise { + const detail = err instanceof ConflictError ? err.detail : { message: "" } + return hiddenBindingMessage(detail, await WorkspaceApi.signedInAccount(actAs)) +} /** The other half of the same story, told to the person who creates the workspace. * A create from the CLI or the TUI is always `privacy: "private"`, and the server hides a * private workspace's binding from everyone else — so without this note the creator has no * way to know that the teammate who clones the repo next will be told it is unlinked, and - * will hit `HIDDEN_BINDING_MESSAGE` with no idea who to ask. Lives here, beside that + * will hit `hiddenBindingMessage` with no idea who to ask. Lives here, beside that * message, because both the CLI command and the TUI plugin have to say it and neither can * import the other. */ export const QUICK_WORKSPACE_PRIVATE_NOTE = @@ -928,4 +965,20 @@ export namespace WorkspaceApi { if (!Number.isInteger(id) || id <= 0) throw new WorkspaceApiError("The server did not say who this account is.") return id } + + /** The email and instance a request runs as (`actAs`, else the configured credential), for + * naming the account in an error. Undefined when either cannot be read; never throws. */ + export async function signedInAccount(actAs?: ActAs): Promise { + try { + const instance = actAs?.instance ?? (await creds()).instance + const me = await req<{ email?: unknown }>("GET", "/me", { + base: "/users", + reportErrors: false, + ...(actAs ? { actAs } : {}), + }) + return typeof me?.email === "string" && me.email ? { email: me.email, instance } : undefined + } catch { + return undefined + } + } } diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 7cdce3bdbb..091d495058 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -18,7 +18,7 @@ import { AltimateApi } from "@/altimate/api/client" import { WorkspaceApi, ConflictError, - HIDDEN_BINDING_MESSAGE, + describeHiddenBinding, isHiddenBindingConflict, QUICK_WORKSPACE_PRIVATE_NOTE, ForbiddenError, @@ -534,7 +534,7 @@ async function runBrowserHandoff( } catch (err) { bindSpin.stop("Link failed.", 1) if (isHiddenBindingConflict(err)) { - prompts.log.error(`${HIDDEN_BINDING_MESSAGE} Workspace "${projectName}" was created but is not linked.`) + prompts.log.error(`${await describeHiddenBinding(err)} Workspace "${projectName}" was created but is not linked.`) } else if (err instanceof ConflictError) { const existingName = conflictExistingName(err.detail) prompts.log.error( @@ -666,7 +666,7 @@ export async function createThenBindOrRebind( `project is still linked to "${stripControlChars(existing.datamate.name)}".`, ) } else if (isHiddenBindingConflict(err)) { - prompts.log.error(`${HIDDEN_BINDING_MESSAGE} Nothing was created.`) + prompts.log.error(`${await describeHiddenBinding(err)} Nothing was created.`) } else { const existingName = conflictExistingName(err.detail) prompts.log.error( @@ -906,7 +906,7 @@ async function bindOrRebind( } catch (err) { spin.stop(isRebind ? `Re-link failed.` : `Link failed.`, 1) if (isHiddenBindingConflict(err)) { - prompts.log.error(HIDDEN_BINDING_MESSAGE) + prompts.log.error(await describeHiddenBinding(err, actAs)) } else if (err instanceof ConflictError) { const existingName = conflictExistingName(err.detail) prompts.log.error(`Already linked to "${existingName}". Re-run \`altimate-code link\` to switch.`) diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 3826237ee1..b83c4cf941 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -56,7 +56,7 @@ import { import { createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js" import { ConflictError, - HIDDEN_BINDING_MESSAGE, + describeHiddenBinding, isHiddenBindingConflict, QUICK_WORKSPACE_PRIVATE_NOTE, ForbiddenError, @@ -660,7 +660,7 @@ async function runBrowserHandoff( api.ui.toast({ variant: "warning", message: isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? await describeHiddenBinding(err) : `This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Run \`altimate-code link\` to change.`, }) } else if (err instanceof NotFoundError) { @@ -786,7 +786,7 @@ export async function createAndBindInline( // them round a loop with no exit. The three other conflict toasts in this file already // branch here; this one did not. message: isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? await describeHiddenBinding(err) : `This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Use the palette's "Link this project to a workspace" to change.`, duration: 15_000, }) @@ -1154,7 +1154,7 @@ function PickerDialog(props: PickerProps) { // point at OfferDialog's Re-link, which doesn't exist either. Point // at the concrete next action instead. (kilo cycle 6.) msg = isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? await describeHiddenBinding(err) : `Already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Re-run \`altimate-code link\` to change the workspace.` } else if (err instanceof PreconditionFailedError) { msg = "Someone else re-linked this project — reload and try again." @@ -1415,7 +1415,7 @@ export async function bindOrRebindInline( let msg: string if (err instanceof ConflictError) { msg = isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? await describeHiddenBinding(err) : `Already linked to "${err.detail.existing_datamate_name ?? "another workspace"}".` } else if (err instanceof PreconditionFailedError) { msg = "Someone else re-linked this project — reload and try again." diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index 1ae06c16cb..9b697c5e2c 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -49,7 +49,7 @@ const { createAndBindInline, bindOrRebindInline, runWorkspaceManage } = await im ) const { recordApprovedBinding } = await import("@/altimate/workspace/state") const { flushPendingSyncs } = await import("@/altimate/workspace/skill-sync") -const { HIDDEN_BINDING_MESSAGE, QUICK_WORKSPACE_PRIVATE_NOTE } = await import( +const { hiddenBindingMessage, QUICK_WORKSPACE_PRIVATE_NOTE } = await import( "@/altimate/workspace/api-client" ) @@ -298,7 +298,7 @@ describe("TUI: hidden-binding conflict toast", () => { const { api, toasts } = stubApi() // existing=undefined → bindExisting → 409 (name withheld) → hidden-binding toast. await bindOrRebindInline(api, IDENTIFIER, 5, undefined) - expect(toasts.some((t) => t.message === HIDDEN_BINDING_MESSAGE)).toBe(true) + expect(toasts.some((t) => t.message === hiddenBindingMessage({ message: "already linked", existing_datamate_id: 7 }))).toBe(true) expect(toasts.some((t) => /claimed this project while you were choosing/i.test(t.message))).toBe(false) }) @@ -315,12 +315,44 @@ describe("TUI: hidden-binding conflict toast", () => { // No `rebindFrom`: the project looks unlinked to this user, because the binding that // owns it belongs to a workspace they cannot see. This is Bob, a minute after cloning. await createAndBindInline(api, IDENTIFIER, "proj") - expect(toasts.some((t) => t.message === HIDDEN_BINDING_MESSAGE)).toBe(true) + expect(toasts.some((t) => t.message === hiddenBindingMessage({ message: "already linked", existing_datamate_id: 7 }))).toBe(true) // The advice that sent him round the loop: a picker scoped to workspaces he can see // lists none of them, so "use the palette to change" had nothing to offer. expect(toasts.some((t) => /Link this project to a workspace/.test(t.message))).toBe(false) }) + test("names the hidden workspace and the account signed in now, so a second sign-in is diagnosable", async () => { + // The exact body the service returns when the remote is bound to a private workspace the + // caller does not own: the id is sent, the name and path are withheld. + routes = [ + { + match: /datamate-project-bindings/, + method: "POST", + status: 409, + body: { + detail: { + message: "This project is already linked to a different workspace", + existing_datamate_id: 38, + existing_datamate_name: null, + repo_remote: "https://github.com/acme/proj", + project_path: null, + }, + }, + }, + { match: /^\/users\/me$/, method: "GET", status: 200, body: { id: 1, email: "serviceuser@example.com" } }, + ] + const { api, toasts } = stubApi() + await bindOrRebindInline(api, IDENTIFIER, 29, undefined) + const toast = toasts.find((t) => /already linked/.test(t.message)) + expect(toast?.message).toBe( + hiddenBindingMessage( + { message: "x", existing_datamate_id: 38 }, + { email: "serviceuser@example.com", instance: "acme" }, + ), + ) + expect(toast?.message).toContain('(workspace id 38) that serviceuser@example.com on instance "acme" can\'t see') + }) + test("a NAMED 409 is still a real race, and still names the workspace", async () => { routes = [ { @@ -333,7 +365,7 @@ describe("TUI: hidden-binding conflict toast", () => { const { api, toasts } = stubApi() await createAndBindInline(api, IDENTIFIER, "proj") expect(toasts.some((t) => /already linked to "team-ws"/.test(t.message))).toBe(true) - expect(toasts.some((t) => t.message === HIDDEN_BINDING_MESSAGE)).toBe(false) + expect(toasts.some((t) => t.message === hiddenBindingMessage({ message: "already linked", existing_datamate_id: 7 }))).toBe(false) }) }) diff --git a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts index ac8137df23..ff970799dd 100644 --- a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts +++ b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts @@ -24,7 +24,7 @@ test("link reports a completed seed and memory that is off without a retry hint" }) test("a 409 that withholds the workspace name is explained as a teammate's private workspace, not a race", async () => { - const { ConflictError, isHiddenBindingConflict, HIDDEN_BINDING_MESSAGE } = await import( + const { ConflictError, isHiddenBindingConflict, hiddenBindingMessage } = await import( "../../../src/altimate/workspace/api-client" ) expect(isHiddenBindingConflict(new ConflictError({ existing_datamate_id: 7, existing_datamate_name: null } as any))).toBe(true) @@ -33,5 +33,20 @@ test("a 409 that withholds the workspace name is explained as a teammate's priva // A 409 that is not a binding conflict (no workspace id) keeps its own message. expect(isHiddenBindingConflict(new ConflictError({ message: "conflict" } as any))).toBe(false) expect(isHiddenBindingConflict(new Error("x"))).toBe(false) - expect(HIDDEN_BINDING_MESSAGE).toContain("share it with you") + expect(hiddenBindingMessage({ message: "x", existing_datamate_id: 7 })).toContain("share it with you") +}) + +test("the hidden-binding message names the workspace id and the account that cannot see it", async () => { + const { hiddenBindingMessage } = await import("../../../src/altimate/workspace/api-client") + const detail = { message: "This project is already linked to a different workspace", existing_datamate_id: 38, existing_datamate_name: null } + expect(hiddenBindingMessage(detail, { email: "support@example.com", instance: "acme" })).toBe( + 'This project is already linked to a workspace (workspace id 38) that support@example.com on instance "acme" can\'t see. ' + + "It is private to another account: a teammate's, or yours under a different sign-in. " + + "Sign in as that account, or ask its owner to share it with you in the Altimate web app or to unlink the project, " + + "then run `altimate-code link` again.", + ) + // Account unknown (lookup failed): still names the workspace, and says which account in general terms. + expect(hiddenBindingMessage(detail)).toContain("(workspace id 38) that the account you are signed in with can't see") + // Server-sourced text cannot inject terminal control sequences. + expect(hiddenBindingMessage(detail, { email: "a\x1b]8;;evil\x07@x.com", instance: "acme" })).toContain("a]8;;evil@x.com") }) From 7be2850b2d7f23c76d3cd3da1b10abbb87c851d8 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 21:47:30 +0530 Subject: [PATCH 02/11] fix: name the account the failing link request ran as Each hidden-binding site now captures one credential before its bind or create-and-bind and passes it to both the request and the error message, so a sign-in switch while the request is in flight cannot make the message name a different account. The browser handoff binds as the exact credential its tenant check validated. The account lookup reads one credential for both the email and the instance, shares the /users/me request with whoami, and uses a 3 second budget since it only words an error that already happened. The control character sanitizer now lives in workspace-name.ts and is shared with the CLI. Tests cover an account switch during the bind (listed and ambient credential), a failed account lookup, and the CLI create-and-bind path. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/api-client.ts | 48 +++++---- .../src/altimate/workspace/workspace-name.ts | 19 ++++ packages/opencode/src/cli/cmd/link.ts | 37 +++---- .../src/plugin/tui/altimate/workspace.tsx | 28 +++-- .../workspace/create-then-rebind.test.ts | 102 +++++++++++++++++- .../workspace/link-seed-message.test.ts | 2 +- 6 files changed, 180 insertions(+), 56 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 4e957e5360..c31edb6bbc 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -12,9 +12,10 @@ // for 409/412 and surface it as a typed error rather than a bare status code. import { AltimateApi } from "@/altimate/api/client" import { Telemetry } from "@/altimate/telemetry" -import { stripBidiControls } from "./workspace-name" +import { stripControlChars } from "./workspace-name" const REQUEST_TIMEOUT_MS = 15_000 +const SIGNED_IN_LOOKUP_TIMEOUT_MS = 3_000 export interface DatamateRef { id: number @@ -113,9 +114,7 @@ export interface SignedInAccount { instance: string } -const plain = (text: string) => - // eslint-disable-next-line no-control-regex - stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")).trim() +const plain = (text: string) => stripControlChars(text).trim() /** A 409 whose `existing_datamate_name` is withheld: the server hides the name of a workspace * the caller cannot see. Reading that as a race ("another workspace claimed this project while @@ -144,8 +143,9 @@ export function hiddenBindingMessage(detail: ConflictDetail, account?: SignedInA ) } -/** `hiddenBindingMessage` for a conflict, naming the account the request ran as. Never throws: - * when the account cannot be read, the message says so generically. */ +/** `hiddenBindingMessage` for a conflict, naming the account the request ran as. Pass the + * credential the failing request used: read again after the failure, it may already be another + * account's. Never throws: when the account cannot be read, the message says so generically. */ export async function describeHiddenBinding(err: unknown, actAs?: ActAs): Promise { const detail = err instanceof ConflictError ? err.detail : { message: "" } return hiddenBindingMessage(detail, await WorkspaceApi.signedInAccount(actAs)) @@ -717,6 +717,7 @@ export namespace WorkspaceApi { name: string identifier: ProjectIdentifier description?: string + actAs?: ActAs }): Promise { const res = await linkAttempt("create_and_bind", undefined, () => req("POST", "/", { @@ -726,6 +727,7 @@ export namespace WorkspaceApi { project_path: input.identifier.projectPath ?? null, description: input.description ?? null, }, + ...(input.actAs ? { actAs: input.actAs } : {}), }), ) const id = res?.binding?.datamate_id ?? res?.datamate?.id @@ -955,13 +957,7 @@ export namespace WorkspaceApi { * client must compare ownership — skill attachment requires the caller to * OWN the workspace, and the credentials carry no user id of their own. */ export async function whoami(actAs?: ActAs): Promise { - // Not a workspace call: no workspace_api_error row for it. - const me = await req<{ id?: unknown }>("GET", "/me", { - base: "/users", - reportErrors: false, - ...(actAs ? { actAs } : {}), - }) - const id = Number(me?.id) + const id = Number((await me(actAs))?.id) if (!Number.isInteger(id) || id <= 0) throw new WorkspaceApiError("The server did not say who this account is.") return id } @@ -970,15 +966,27 @@ export namespace WorkspaceApi { * naming the account in an error. Undefined when either cannot be read; never throws. */ export async function signedInAccount(actAs?: ActAs): Promise { try { - const instance = actAs?.instance ?? (await creds()).instance - const me = await req<{ email?: unknown }>("GET", "/me", { - base: "/users", - reportErrors: false, - ...(actAs ? { actAs } : {}), - }) - return typeof me?.email === "string" && me.email ? { email: me.email, instance } : undefined + // One credential for both halves, so the email and the instance name the same account. + const who = actAs ?? (await captureCredentials()) + if (!who) return undefined + // Runs after a request already failed, only to word its error: a short budget, so a slow + // answer does not hold the error back. + const answer = await me(who, SIGNED_IN_LOOKUP_TIMEOUT_MS) + return typeof answer?.email === "string" && answer.email + ? { email: answer.email, instance: who.instance } + : undefined } catch { return undefined } } + + /** ``GET /users/me``. Not a workspace call: no workspace_api_error row for it. */ + function me(actAs?: ActAs, timeoutMs?: number) { + return req<{ id?: unknown; email?: unknown }>("GET", "/me", { + base: "/users", + reportErrors: false, + ...(actAs ? { actAs } : {}), + ...(timeoutMs ? { timeoutMs } : {}), + }) + } } diff --git a/packages/opencode/src/altimate/workspace/workspace-name.ts b/packages/opencode/src/altimate/workspace/workspace-name.ts index 60c56ebac0..57169dc672 100644 --- a/packages/opencode/src/altimate/workspace/workspace-name.ts +++ b/packages/opencode/src/altimate/workspace/workspace-name.ts @@ -68,6 +68,25 @@ export function stripBidiControls(text: string): string { return text.replace(BIDI_CONTROLS, "") } +/** Strip C0/C1 control bytes (including ESC) from server-controlled text + * before it reaches a raw-stdout escape-sequence wrapper. Workspace names + * come from ``WorkspaceApi.listDatamates()`` with no charset validation — an + * attacker-controlled name containing its own ``\x1b]8;;`` could otherwise + * prematurely close our hyperlink and open a spoofed one pointing wherever + * they choose, with our trusted URL as the visible (but inert) prefix. + * (CodeRabbit + cubic, PR #1274.) */ +export function stripControlChars(text: string): string { + // C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f) — the previous range only + // covered C0/DEL, leaving C1 controls unstripped. ESC (the OSC 8 breakout + // vector) was always covered, but the doc comment claimed C1 coverage it + // didn't have. (Kilo, PR #1274.) + // Plus the Unicode bidi controls (ALM, LRM/RLM, LRE..RLO, LRI..PDI): they cannot break out of the + // hyperlink (the href is always `buildManageUrl`, never the name) but can visually reverse or + // reorder the displayed name in the picker. (v0.11.2 release review.) + // eslint-disable-next-line no-control-regex + return stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")) +} + /** A workspace name as a dialog shows it: inert, and with no bidi controls. */ export function displayWorkspaceName(name: string): string { return stripBidiControls(inertWorkspaceName(name)) diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 091d495058..380cd35ac7 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -53,9 +53,12 @@ import { findNamesakes, linkPickerOpensOn, namesakeHint, - stripBidiControls, + stripControlChars, } from "@/altimate/workspace/workspace-name" +// Re-exported: other commands and tests import it from here. +export { stripControlChars } + /** The browser sign-in from a plain shell: the Altimate LLM Gateway method of the `altimate-backend` * provider saves the credentials every workspace command reads. `--method` skips the method picker, * so the command also works where stdin is not a terminal (an agent's shell, Claude Code's `!`). */ @@ -64,25 +67,6 @@ export const SIGN_IN_COMMAND = 'altimate-code auth login -p altimate-backend --m const CREATE_NEW_SENTINEL = "__create_new__" const SET_UP_IN_BROWSER_SENTINEL = "__browser_handoff__" -/** Strip C0/C1 control bytes (including ESC) from server-controlled text - * before it reaches a raw-stdout escape-sequence wrapper. Workspace names - * come from ``WorkspaceApi.listDatamates()`` with no charset validation — an - * attacker-controlled name containing its own ``\x1b]8;;`` could otherwise - * prematurely close our hyperlink and open a spoofed one pointing wherever - * they choose, with our trusted URL as the visible (but inert) prefix. - * (CodeRabbit + cubic, PR #1274.) */ -export function stripControlChars(text: string): string { - // C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f) — the previous range only - // covered C0/DEL, leaving C1 controls unstripped. ESC (the OSC 8 breakout - // vector) was always covered, but the doc comment claimed C1 coverage it - // didn't have. (Kilo, PR #1274.) - // Plus the Unicode bidi controls (ALM, LRM/RLM, LRE..RLO, LRI..PDI): they cannot break out of the - // hyperlink (the href is always `buildManageUrl`, never the name) but can visually reverse or - // reorder the displayed name in the picker. (v0.11.2 release review.) - // eslint-disable-next-line no-control-regex - return stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")) -} - /** What a pick in the link picker does: one of the two create paths, or an existing workspace. */ export function linkPickKind(pick: string): "create" | "browser" | "workspace" { if (pick === CREATE_NEW_SENTINEL) return "create" @@ -485,8 +469,11 @@ async function runBrowserHandoff( // browser window can stay open for up to 15 minutes; an account switch in // that window would otherwise bind a callback validated for tenant A // under tenant B (workspace ids are tenant-schema-local). + // The credential checked here is the one the bind runs as, and the one any error names. + let bindAs: ActAs try { const fresh = await AltimateApi.getCredentials() + bindAs = { url: fresh.altimateUrl, instance: fresh.altimateInstanceName, apiKey: fresh.altimateApiKey } if ( fresh.altimateInstanceName !== result.credentials.tenant || fresh.altimateUrl !== result.credentials.apiUrl @@ -507,7 +494,7 @@ async function runBrowserHandoff( const bindSpin = spinner() bindSpin.start("Linking workspace...") try { - const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier) + const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier, bindAs) // Match the two other recordApprovedBinding call sites in this file // (lines 377 and 496) which cache under ``identifier.projectPath ?? // directory``. The raw ``directory`` here caches under a different key @@ -534,7 +521,7 @@ async function runBrowserHandoff( } catch (err) { bindSpin.stop("Link failed.", 1) if (isHiddenBindingConflict(err)) { - prompts.log.error(`${await describeHiddenBinding(err)} Workspace "${projectName}" was created but is not linked.`) + prompts.log.error(`${await describeHiddenBinding(err, bindAs)} Workspace "${projectName}" was created but is not linked.`) } else if (err instanceof ConflictError) { const existingName = conflictExistingName(err.detail) prompts.log.error( @@ -633,6 +620,8 @@ export async function createThenBindOrRebind( // create the workspace on one tenant and rebind on another using an id that // is local to the first. (review, PR #1314) const account = await WorkspaceApi.accountFingerprint().catch(() => null) + // The create-and-bind and any error about it name the same account. + const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined try { // Two different creates, because the server offers two different things. // @@ -649,7 +638,7 @@ export async function createThenBindOrRebind( const ws = await WorkspaceApi.createWorkspaceUnbound({ name }) created = { via: "unbound", datamate: ws } } else { - const res = await WorkspaceApi.createAndBind({ name, identifier }) + const res = await WorkspaceApi.createAndBind({ name, identifier, actAs: createAs }) created = { via: "bound", datamate: res.datamate, binding: res.binding, manage_url: res.manage_url } } } catch (err) { @@ -666,7 +655,7 @@ export async function createThenBindOrRebind( `project is still linked to "${stripControlChars(existing.datamate.name)}".`, ) } else if (isHiddenBindingConflict(err)) { - prompts.log.error(`${await describeHiddenBinding(err)} Nothing was created.`) + prompts.log.error(`${await describeHiddenBinding(err, createAs)} Nothing was created.`) } else { const existingName = conflictExistingName(err.detail) prompts.log.error( diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index b83c4cf941..0e48f44845 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -622,8 +622,11 @@ async function runBrowserHandoff( // ids are tenant-schema-local (same integer, different workspace). Compare // the credential fingerprint the handoff was validated against with the // credentials we're about to bind under, and refuse if either drifted. + // The credential checked here is the one the bind runs as, and the one any error names. + let bindAs: ActAs try { const fresh = await AltimateApi.getCredentials() + bindAs = { url: fresh.altimateUrl, instance: fresh.altimateInstanceName, apiKey: fresh.altimateApiKey } if ( fresh.altimateInstanceName !== result.credentials.tenant || fresh.altimateUrl !== result.credentials.apiUrl @@ -646,7 +649,7 @@ async function runBrowserHandoff( // to the returned workspace via the existing bind endpoint. Same code path // as PickerDialog's attach mode. try { - const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier) + const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier, bindAs) await recordApprovedBinding(api.state.path.directory, { datamateId: res.binding.datamate_id, datamateName: res.binding.datamate_name, @@ -660,7 +663,7 @@ async function runBrowserHandoff( api.ui.toast({ variant: "warning", message: isHiddenBindingConflict(err) - ? await describeHiddenBinding(err) + ? await describeHiddenBinding(err, bindAs) : `This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Run \`altimate-code link\` to change.`, }) } else if (err instanceof NotFoundError) { @@ -767,12 +770,14 @@ export async function createAndBindInline( // requests resolve credentials independently, and a workspace id means // nothing on a different account. const account = await WorkspaceApi.accountFingerprint().catch(() => null) + // The create-and-bind and any error about it name the same account. + const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined try { if (rebindFrom) { const ws = await WorkspaceApi.createWorkspaceUnbound({ name }) res = { via: "unbound", datamate: ws } } else { - const created = await WorkspaceApi.createAndBind({ name, identifier }) + const created = await WorkspaceApi.createAndBind({ name, identifier, actAs: createAs }) res = { via: "bound", datamate: created.datamate, binding: created.binding } } } catch (err) { @@ -786,7 +791,7 @@ export async function createAndBindInline( // them round a loop with no exit. The three other conflict toasts in this file already // branch here; this one did not. message: isHiddenBindingConflict(err) - ? await describeHiddenBinding(err) + ? await describeHiddenBinding(err, createAs) : `This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Use the palette's "Link this project to a workspace" to change.`, duration: 15_000, }) @@ -1096,9 +1101,11 @@ function PickerDialog(props: PickerProps) { async function pick(datamateId: number) { if (submitting) return submitting = true + // The bind or re-link and any error about it name the same account. + const pickAs = (await WorkspaceApi.captureCredentials()) ?? undefined try { if (props.mode === "attach") { - const res = await WorkspaceApi.bindExisting(datamateId, props.identifier) + const res = await WorkspaceApi.bindExisting(datamateId, props.identifier, pickAs) await recordApprovedBinding(props.api.state.path.directory, { datamateId: res.binding.datamate_id, datamateName: res.binding.datamate_name, @@ -1127,6 +1134,7 @@ function PickerDialog(props: PickerProps) { targetDatamateId: datamateId, expectedCurrentDatamateId: props.expectedCurrentDatamateId, matchedBy: props.matchedBy, + actAs: pickAs, }) await recordApprovedBinding(props.api.state.path.directory, { datamateId: res.binding.datamate_id, @@ -1154,7 +1162,7 @@ function PickerDialog(props: PickerProps) { // point at OfferDialog's Re-link, which doesn't exist either. Point // at the concrete next action instead. (kilo cycle 6.) msg = isHiddenBindingConflict(err) - ? await describeHiddenBinding(err) + ? await describeHiddenBinding(err, pickAs) : `Already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Re-run \`altimate-code link\` to change the workspace.` } else if (err instanceof PreconditionFailedError) { msg = "Someone else re-linked this project — reload and try again." @@ -1372,6 +1380,8 @@ export async function bindOrRebindInline( }) return } + // The bind and any error about it name the same account: the listed one, else the one signed in now. + const bindAs = listedAs ?? (await WorkspaceApi.captureCredentials()) ?? undefined try { const res = await (async () => { if (existing) { @@ -1380,10 +1390,10 @@ export async function bindOrRebindInline( targetDatamateId, expectedCurrentDatamateId: existing.datamateId, matchedBy: existing.matchedBy, - actAs: listedAs ?? undefined, + actAs: bindAs, }) } - return WorkspaceApi.bindExisting(targetDatamateId, identifier, listedAs ?? undefined) + return WorkspaceApi.bindExisting(targetDatamateId, identifier, bindAs) })() const recorded = await recordApprovedBinding( api.state.path.directory, @@ -1415,7 +1425,7 @@ export async function bindOrRebindInline( let msg: string if (err instanceof ConflictError) { msg = isHiddenBindingConflict(err) - ? await describeHiddenBinding(err) + ? await describeHiddenBinding(err, bindAs) : `Already linked to "${err.detail.existing_datamate_name ?? "another workspace"}".` } else if (err instanceof PreconditionFailedError) { msg = "Someone else re-linked this project — reload and try again." diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index 9b697c5e2c..c3e34eacc4 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -59,19 +59,25 @@ interface Call { method: string path: string body: Record + tenant?: string } let calls: Call[] = [] let routes: Array<{ match: RegExp; method?: string; status: number; body: unknown }> = [] +/** Runs when a request matches, before its answer: lets a test act while a request is in flight. */ +let onRequest: ((call: Call) => void) | undefined function stubFetch() { globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { const url = new URL(String(input)) const method = String(init?.method ?? "GET") - calls.push({ + const call: Call = { method, path: url.pathname, body: init?.body ? JSON.parse(String(init.body)) : {}, - }) + tenant: new Headers(init?.headers).get("x-tenant") ?? undefined, + } + calls.push(call) + onRequest?.(call) const route = routes.find( (r) => r.match.test(url.pathname) && (r.method === undefined || r.method === method), ) @@ -114,6 +120,7 @@ const EXISTING = { beforeEach(() => { calls = [] routes = [] + onRequest = undefined opened.length = 0 stubFetch() }) @@ -353,6 +360,60 @@ describe("TUI: hidden-binding conflict toast", () => { expect(toast?.message).toContain('(workspace id 38) that serviceuser@example.com on instance "acme" can\'t see') }) + const HIDDEN_409 = { + match: /datamate-project-bindings/, + method: "POST", + status: 409, + body: { + detail: { + message: "This project is already linked to a different workspace", + existing_datamate_id: 38, + existing_datamate_name: null, + repo_remote: "https://github.com/acme/proj", + project_path: null, + }, + }, + } + const CREDENTIALS = path.join(SANDBOX, "home", ".altimate", "altimate.json") + const ACME = { altimateUrl: API_URL, altimateInstanceName: "acme", altimateApiKey: "test-key" } + /** Signs in as another account while the bind is in flight, and back afterwards. */ + const switchAccountDuringBind = () => { + onRequest = (call) => { + if (call.method === "POST" && call.path.includes("/bind")) + writeFileSync(CREDENTIALS, JSON.stringify({ ...ACME, altimateInstanceName: "other", altimateApiKey: "other-key" })) + } + } + + for (const listed of [true, false]) { + test(`names the account the bind ran as, not one signed in since (${listed ? "listed" : "ambient"} credential)`, async () => { + routes = [ + HIDDEN_409, + { match: /^\/users\/me$/, method: "GET", status: 200, body: { id: 1, email: "serviceuser@example.com" } }, + ] + switchAccountDuringBind() + const { api, toasts } = stubApi() + try { + const listedAs = listed ? { url: API_URL, instance: "acme", apiKey: "test-key" } : undefined + await bindOrRebindInline(api, IDENTIFIER, 29, undefined, listedAs) + } finally { + writeFileSync(CREDENTIALS, JSON.stringify(ACME)) + } + expect(calls.filter((c) => c.path === "/users/me").map((c) => c.tenant)).toEqual(["acme"]) + expect(toasts.find((t) => /already linked/.test(t.message))?.message).toContain( + 'that serviceuser@example.com on instance "acme" can\'t see', + ) + }) + } + + test("when the account lookup fails, the message still names the workspace", async () => { + routes = [HIDDEN_409, { match: /^\/users\/me$/, method: "GET", status: 500, body: { detail: "boom" } }] + const { api, toasts } = stubApi() + await bindOrRebindInline(api, IDENTIFIER, 29, undefined) + expect(toasts.find((t) => /already linked/.test(t.message))?.message).toBe( + hiddenBindingMessage({ message: "x", existing_datamate_id: 38 }), + ) + }) + test("a NAMED 409 is still a real race, and still names the workspace", async () => { routes = [ { @@ -481,3 +542,40 @@ describe("TUI: /workspace menu options", () => { expect(values).not.toContain("unlink") }) }) + +describe("CLI: hidden-binding conflict", () => { + test("create-and-bind names the hidden workspace and the account it ran as, not one signed in since", async () => { + const credentials = path.join(SANDBOX, "home", ".altimate", "altimate.json") + const acme = { altimateUrl: API_URL, altimateInstanceName: "acme", altimateApiKey: "test-key" } + onRequest = (call) => { + if (call.method === "POST" && call.path === "/datamate-project-bindings/") + writeFileSync(credentials, JSON.stringify({ ...acme, altimateInstanceName: "other", altimateApiKey: "other-key" })) + } + routes = [ + { + match: /datamate-project-bindings\/$/, + method: "POST", + status: 409, + body: { detail: { message: "already linked", existing_datamate_id: 38, existing_datamate_name: null } }, + }, + { match: /^\/users\/me$/, method: "GET", status: 200, body: { id: 1, email: "serviceuser@example.com" } }, + ] + const written: string[] = [] + const write = process.stdout.write.bind(process.stdout) + process.stdout.write = ((chunk: string | Uint8Array) => { + written.push(String(chunk)) + return true + }) as typeof process.stdout.write + try { + await createThenBindOrRebind(IDENTIFIER, "proj", "/tmp/proj", null) + } finally { + process.stdout.write = write + writeFileSync(credentials, JSON.stringify(acme)) + } + expect(calls.filter((c) => c.path === "/users/me").map((c) => c.tenant)).toEqual(["acme"]) + const out = written.join("") + expect(out).toContain('(workspace id 38) that serviceuser@example.com on instance "acme" can\'t see') + expect(out).toContain("Nothing was created.") + expect(process.exitCode).toBe(1) + }) +}) diff --git a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts index ff970799dd..4a4667641f 100644 --- a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts +++ b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts @@ -23,7 +23,7 @@ test("link reports a completed seed and memory that is off without a retry hint" expect(seedMessage(null)).toContain("Sync") }) -test("a 409 that withholds the workspace name is explained as a teammate's private workspace, not a race", async () => { +test("a 409 that withholds the workspace name is a hidden binding, not a race", async () => { const { ConflictError, isHiddenBindingConflict, hiddenBindingMessage } = await import( "../../../src/altimate/workspace/api-client" ) From d463b91dc55b793c1dd4a893559e78434f736ed3 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 22:02:49 +0530 Subject: [PATCH 03/11] test: cover an account answer with no email; tidy the shared sanitizer's docstring Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/workspace-name.ts | 19 +++++-------------- .../workspace/create-then-rebind.test.ts | 9 +++++++++ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/workspace-name.ts b/packages/opencode/src/altimate/workspace/workspace-name.ts index 57169dc672..e2094bbb24 100644 --- a/packages/opencode/src/altimate/workspace/workspace-name.ts +++ b/packages/opencode/src/altimate/workspace/workspace-name.ts @@ -68,21 +68,12 @@ export function stripBidiControls(text: string): string { return text.replace(BIDI_CONTROLS, "") } -/** Strip C0/C1 control bytes (including ESC) from server-controlled text - * before it reaches a raw-stdout escape-sequence wrapper. Workspace names - * come from ``WorkspaceApi.listDatamates()`` with no charset validation — an - * attacker-controlled name containing its own ``\x1b]8;;`` could otherwise - * prematurely close our hyperlink and open a spoofed one pointing wherever - * they choose, with our trusted URL as the visible (but inert) prefix. - * (CodeRabbit + cubic, PR #1274.) */ +/** Strip C0/C1 control bytes (including ESC) and bidi controls from server-controlled text + * before it reaches the terminal. Workspace names, emails and instance names come from the + * service with no charset validation: an embedded ``\x1b]8;;`` could close a hyperlink and open + * a spoofed one, and bidi controls can visually reverse or reorder the displayed text. */ export function stripControlChars(text: string): string { - // C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f) — the previous range only - // covered C0/DEL, leaving C1 controls unstripped. ESC (the OSC 8 breakout - // vector) was always covered, but the doc comment claimed C1 coverage it - // didn't have. (Kilo, PR #1274.) - // Plus the Unicode bidi controls (ALM, LRM/RLM, LRE..RLO, LRI..PDI): they cannot break out of the - // hyperlink (the href is always `buildManageUrl`, never the name) but can visually reverse or - // reorder the displayed name in the picker. (v0.11.2 release review.) + // C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f), then the Unicode bidi controls. // eslint-disable-next-line no-control-regex return stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")) } diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index c3e34eacc4..e415c34f56 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -405,6 +405,15 @@ describe("TUI: hidden-binding conflict toast", () => { }) } + test("when the account answer has no email, the message still names the workspace", async () => { + routes = [HIDDEN_409, { match: /^\/users\/me$/, method: "GET", status: 200, body: { id: 1 } }] + const { api, toasts } = stubApi() + await bindOrRebindInline(api, IDENTIFIER, 29, undefined) + expect(toasts.find((t) => /already linked/.test(t.message))?.message).toBe( + hiddenBindingMessage({ message: "x", existing_datamate_id: 38 }), + ) + }) + test("when the account lookup fails, the message still names the workspace", async () => { routes = [HIDDEN_409, { match: /^\/users\/me$/, method: "GET", status: 500, body: { detail: "boom" } }] const { api, toasts } = stubApi() From b5e998cd3aed57c8635cd38d5df641115769a990 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 09:27:58 +0530 Subject: [PATCH 04/11] fix: close the picker before the account lookup; bound and validate message values The picker now closes before it waits on the account lookup, so a slow lookup cannot close a dialog the user opened in the meantime. The workspace id is shown only when it is a positive integer. The email and instance are put on one line, stripped of control and bidi characters, and clipped to 254 characters (inertMessageValue in workspace-name.ts). Tests cover the picker ordering, bad ids, long values, and bidi and line separator injection. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/api-client.ts | 19 +++++------- .../src/altimate/workspace/workspace-name.ts | 16 ++++++++-- .../src/plugin/tui/altimate/workspace.tsx | 8 +++-- .../test/altimate/plugin/workspace.test.ts | 29 ++++++++++++++++++- .../workspace/link-seed-message.test.ts | 16 ++++++++-- 5 files changed, 69 insertions(+), 19 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index c31edb6bbc..2a95257fbf 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -12,7 +12,7 @@ // for 409/412 and surface it as a typed error rather than a bare status code. import { AltimateApi } from "@/altimate/api/client" import { Telemetry } from "@/altimate/telemetry" -import { stripControlChars } from "./workspace-name" +import { inertMessageValue } from "./workspace-name" const REQUEST_TIMEOUT_MS = 15_000 const SIGNED_IN_LOOKUP_TIMEOUT_MS = 3_000 @@ -114,8 +114,6 @@ export interface SignedInAccount { instance: string } -const plain = (text: string) => stripControlChars(text).trim() - /** A 409 whose `existing_datamate_name` is withheld: the server hides the name of a workspace * the caller cannot see. Reading that as a race ("another workspace claimed this project while * you were choosing") sent users round a retry loop with no way out. @@ -127,14 +125,13 @@ const plain = (text: string) => stripControlChars(text).trim() * nothing says which account they are looking through. So the message carries the workspace id * (the server always returns it) and the account the request ran as, when known. */ export function hiddenBindingMessage(detail: ConflictDetail, account?: SignedInAccount): string { - const id = typeof detail.existing_datamate_id === "number" ? ` (workspace id ${detail.existing_datamate_id})` : "" - const email = account ? plain(account.email) : "" - const instance = account ? plain(account.instance) : "" - const who = email - ? instance - ? `${email} on instance "${instance}"` - : email - : "the account you are signed in with" + const workspaceId = detail.existing_datamate_id + const validId = typeof workspaceId === "number" && Number.isSafeInteger(workspaceId) && workspaceId > 0 + const id = validId ? ` (workspace id ${workspaceId})` : "" + const email = account ? inertMessageValue(account.email) : "" + const instance = account ? inertMessageValue(account.instance) : "" + let who = "the account you are signed in with" + if (email) who = instance ? `${email} on instance "${instance}"` : email return ( `This project is already linked to a workspace${id} that ${who} can't see. ` + "It is private to another account: a teammate's, or yours under a different sign-in. " + diff --git a/packages/opencode/src/altimate/workspace/workspace-name.ts b/packages/opencode/src/altimate/workspace/workspace-name.ts index e2094bbb24..b6249718b2 100644 --- a/packages/opencode/src/altimate/workspace/workspace-name.ts +++ b/packages/opencode/src/altimate/workspace/workspace-name.ts @@ -69,8 +69,8 @@ export function stripBidiControls(text: string): string { } /** Strip C0/C1 control bytes (including ESC) and bidi controls from server-controlled text - * before it reaches the terminal. Workspace names, emails and instance names come from the - * service with no charset validation: an embedded ``\x1b]8;;`` could close a hyperlink and open + * before it reaches the terminal. Workspace names come from the service with no charset + * validation: an embedded ``\x1b]8;;`` could close a hyperlink and open * a spoofed one, and bidi controls can visually reverse or reorder the displayed text. */ export function stripControlChars(text: string): string { // C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f), then the Unicode bidi controls. @@ -78,6 +78,18 @@ export function stripControlChars(text: string): string { return stripBidiControls(text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")) } +/** Longest server-sourced value (an email, an instance name) rendered inside a message. */ +export const MAX_MESSAGE_VALUE_CHARS = 254 + +/** Server-sourced text placed inside a message: on one line, no control or bidi characters, + * and clipped so a bad value cannot flood a toast or a terminal line. */ +export function inertMessageValue(text: string): string { + const points = Array.from(oneLine(stripBidiControls(text))) + return points.length > MAX_MESSAGE_VALUE_CHARS + ? points.slice(0, MAX_MESSAGE_VALUE_CHARS - 1).join("") + "…" + : points.join("") +} + /** A workspace name as a dialog shows it: inert, and with no bidi controls. */ export function displayWorkspaceName(name: string): string { return stripBidiControls(inertWorkspaceName(name)) diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 0e48f44845..110db11e86 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -1155,7 +1155,10 @@ function PickerDialog(props: PickerProps) { // Surface as a toast so the user sees the specific failure. Dialog // closes either way — the palette command ``altimate.workspace.link`` // (or re-running ``altimate-code link``) re-enters the flow, so the - // user always has a way to try again from a clean slate. + // user always has a way to try again from a clean slate. Closed before + // the account lookup below, which can take a moment: closing after it + // would dismiss whatever dialog the user opened in the meantime. + props.api.ui.dialog.clear() let msg: string if (err instanceof ConflictError) { // The picker doesn't have a "Re-link" option; the referral used to @@ -1174,7 +1177,6 @@ function PickerDialog(props: PickerProps) { msg = err instanceof Error ? err.message : "Failed to link workspace" } props.api.ui.toast({ variant: "error", message: msg }) - props.api.ui.dialog.clear() } finally { submitting = false } @@ -2797,7 +2799,7 @@ export function canInstallWith(nodeMajor: number | null, hasNpm: boolean): boole } /** Test seam: the link dialogs, rendered against a stand-in `api.ui.DialogSelect`. */ -export const linkDialogInternals = { OfferDialog, OnDemandPickerDialog } +export const linkDialogInternals = { OfferDialog, OnDemandPickerDialog, PickerDialog } /** Test seam for the raise path's process-wide state. */ export const engineOfferInternals = { diff --git a/packages/opencode/test/altimate/plugin/workspace.test.ts b/packages/opencode/test/altimate/plugin/workspace.test.ts index c212d09a33..993ffadaca 100644 --- a/packages/opencode/test/altimate/plugin/workspace.test.ts +++ b/packages/opencode/test/altimate/plugin/workspace.test.ts @@ -56,7 +56,7 @@ const { syncInternals } = await import("../../../src/altimate/workspace/engine-s // per-test override of the module state. import { AltimateApi } from "../../../src/altimate/api/client" import { stubEmptySkillList } from "../workspace/skill-list-fixture" -import { WorkspaceApi } from "../../../src/altimate/workspace/api-client" +import { ConflictError, WorkspaceApi } from "../../../src/altimate/workspace/api-client" import { findNamesakes } from "../../../src/altimate/workspace/workspace-name" import { createRoot } from "solid-js" import * as Manage from "../../../src/altimate/workspace/manage" @@ -1078,6 +1078,33 @@ describe("link dialogs: a workspace that already has this project's name", () => await settle() expect(calls.bindAs).toEqual(["acme"]) }) + + // The hidden-binding message waits on an account lookup. The picker must close before it, + // or a dialog the user opened in the meantime is the one that gets closed. + test("picker: a hidden-binding failure closes the picker before the account lookup", async () => { + stubWorkspaces([{ id: 2, name: "analytics", ownerId: ME }]) + stubCreds("acme", "https://api.acme.example.com") + original.signedInAccount = api.signedInAccount + let answer: (a: { email: string; instance: string }) => void = () => {} + api.signedInAccount = () => new Promise((resolve) => (answer = resolve)) + api.bindExisting = async () => { + throw new ConflictError({ message: "already linked", existing_datamate_id: 38, existing_datamate_name: null }) + } + const { tui, h } = harness() + render(() => linkDialogInternals.PickerDialog({ api: tui, identifier, mode: "attach" })) + await settle() + h.selects[0]!.onSelect({ value: 2 }) + await settle() + // Lookup still pending: the picker is already closed, and nothing has been said yet. + expect(h.cleared).toBe(1) + expect(h.toasts).toEqual([]) + answer({ email: "serviceuser@example.com", instance: "acme" }) + await settle() + // The lookup's answer arrives as a toast and closes nothing else. + expect(h.cleared).toBe(1) + expect(h.toasts).toHaveLength(1) + expect(h.toasts[0]).toContain('(workspace id 38) that serviceuser@example.com on instance "acme"') + }) }) describe("/integrations", () => { diff --git a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts index 4a4667641f..e7abd6a2b9 100644 --- a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts +++ b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts @@ -47,6 +47,18 @@ test("the hidden-binding message names the workspace id and the account that can ) // Account unknown (lookup failed): still names the workspace, and says which account in general terms. expect(hiddenBindingMessage(detail)).toContain("(workspace id 38) that the account you are signed in with can't see") - // Server-sourced text cannot inject terminal control sequences. - expect(hiddenBindingMessage(detail, { email: "a\x1b]8;;evil\x07@x.com", instance: "acme" })).toContain("a]8;;evil@x.com") + // Server-sourced text cannot inject terminal control sequences, bidi overrides or line breaks. + const injected = hiddenBindingMessage(detail, { + email: "a\x1b]8;;evil\x07@x.com\u202e", + instance: "ac\u2028me\u0085", + }) + expect(injected).toContain('a ]8;;evil @x.com on instance "ac me" can\'t see') + expect(injected).not.toMatch(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u202e]/) + // A value that cannot be a workspace id is left out rather than printed. + for (const bad of [0, -3, 1.5]) + expect(hiddenBindingMessage({ ...detail, existing_datamate_id: bad })).toContain("linked to a workspace that the account") + // An over-long server value is clipped. + const long = hiddenBindingMessage(detail, { email: "x".repeat(5000) + "@x.com", instance: "acme" }) + expect(long).toContain("x".repeat(253) + "… on instance") + expect(long.length).toBeLessThan(700) }) From 4ae061b0af4b2471fe4ef667a2c3e8af86db6805 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 09:37:57 +0530 Subject: [PATCH 05/11] fix: record each link under the account its write ran as Every link whose server write is pinned to a captured credential now records the local link under that same account (digestOf in state.ts). An account switch while the request runs can no longer store one account's workspace under the next account's scope. When the record is refused for that reason, the TUI says the link stands but nothing was synced, instead of the usual confirmation. The browser handoff reuses captureCredentials() for its tenant check instead of building the credential by hand. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/workspace/state.ts | 6 ++ packages/opencode/src/cli/cmd/link.ts | 42 ++++----- .../src/plugin/tui/altimate/workspace.tsx | 91 +++++++++++-------- .../workspace/create-then-rebind.test.ts | 29 +++++- 4 files changed, 103 insertions(+), 65 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index 959d859d44..fb501c52f9 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -57,6 +57,12 @@ export function credentialDigest(apiUrl: string, tenant: string, apiKey: string) return createHash("sha256").update(`${apiUrl}|${tenant}|${apiKey}`).digest("hex") } +/** `credentialDigest` of a captured credential, or undefined when there is none. Pins a + * local record to the account its server write ran as. */ +export function digestOf(credential?: { url: string; instance: string; apiKey: string } | null): string | undefined { + return credential ? credentialDigest(credential.url, credential.instance, credential.apiKey) : undefined +} + const log = Log.create({ service: "altimate-workspace-state" }) export interface CachedBinding { diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 380cd35ac7..ba4089274f 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -45,7 +45,7 @@ import { resolveWorkspaceWebUrl, type HandoffResult, } from "@/altimate/workspace/browser-handoff" -import { accountDigest, credentialDigest, isApprovedRow, recordApprovedBinding } from "@/altimate/workspace/state" +import { accountDigest, credentialDigest, digestOf, isApprovedRow, recordApprovedBinding } from "@/altimate/workspace/state" import type { SeedOutcome } from "@/altimate/workspace/memory-backfill" import { confirmsNamesake, @@ -449,10 +449,9 @@ async function runBrowserHandoff( projectName: string, directory: string, ): Promise { - // The account this bind acts as; the seed refuses (account-changed) if it switches mid-way. - // Unreadable credentials cannot link anyway, and must not leave the bind unguarded. - const linkAccount = await accountDigest() - if (linkAccount === null) { + // Unreadable credentials cannot link anyway: stop before opening the browser. The bind + // and its local record use the credential captured after the browser returns. + if ((await accountDigest()) === null) { prompts.log.error("Could not read your Altimate credentials, so nothing was linked. Check /connect and try again.") process.exitCode = 1 return @@ -469,27 +468,22 @@ async function runBrowserHandoff( // browser window can stay open for up to 15 minutes; an account switch in // that window would otherwise bind a callback validated for tenant A // under tenant B (workspace ids are tenant-schema-local). - // The credential checked here is the one the bind runs as, and the one any error names. - let bindAs: ActAs - try { - const fresh = await AltimateApi.getCredentials() - bindAs = { url: fresh.altimateUrl, instance: fresh.altimateInstanceName, apiKey: fresh.altimateApiKey } - if ( - fresh.altimateInstanceName !== result.credentials.tenant || - fresh.altimateUrl !== result.credentials.apiUrl - ) { - spin.stop( - `Credentials changed while the browser was open (was ${result.credentials.tenant}, now ${fresh.altimateInstanceName}). Re-run to link this project.`, - 1, - ) - process.exitCode = 1 - return - } - } catch { + // The credential checked here is the one the bind runs as, the one its record is pinned to, + // and the one any error names. + const bindAs = await WorkspaceApi.captureCredentials() + if (!bindAs) { spin.stop("Lost Altimate credentials while the browser was open — sign in and re-run.", 1) process.exitCode = 1 return } + if (bindAs.instance !== result.credentials.tenant || bindAs.url !== result.credentials.apiUrl) { + spin.stop( + `Credentials changed while the browser was open (was ${result.credentials.tenant}, now ${bindAs.instance}). Re-run to link this project.`, + 1, + ) + process.exitCode = 1 + return + } spin.stop(`Workspace approved. Linking it to this project...`) const bindSpin = spinner() bindSpin.start("Linking workspace...") @@ -507,7 +501,7 @@ async function runBrowserHandoff( repoRemote: res.binding.repo_remote, projectPath: res.binding.project_path, linkedAt: Date.now(), - }, { awaitBackfill: true, account: linkAccount }) + }, { awaitBackfill: true, account: digestOf(bindAs) }) bindSpin.stop(`Linked to "${stripControlChars(res.binding.datamate_name)}".`) prompts.log.info(seedMessage(seed)) const manageUrl = await manageUrlFor(res.binding.datamate_id) @@ -728,7 +722,7 @@ export async function createThenBindOrRebind( repoRemote: serverBinding?.repo_remote ?? identifier.repoRemote ?? null, projectPath: serverBinding?.project_path ?? identifier.projectPath ?? null, linkedAt: Date.now(), - }, { awaitBackfill: true, account: linkAccount }) + }, { awaitBackfill: true, account: digestOf(createAs) ?? linkAccount }) prompts.log.info(seedMessage(seed)) // The quick create is private, and the server hides a private workspace's link from // everyone else: a teammate who clones this repo is told it is unlinked. diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 110db11e86..1bdbd53b5e 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -87,6 +87,7 @@ import { sameIdentifier } from "@/altimate/workspace/remote-identity" import { accountDigest, credentialDigest, + digestOf, readLocalBinding, recordApprovedBinding, resolvePinnedBindingForRouting, @@ -473,6 +474,27 @@ function WorkspaceLinkedDialog(props: LinkedProps) { ) } +/** The confirmation after a link, unless the account was switched while it ran: the server + * link stands, but the local record and memory seed were refused, so the usual confirmation + * (which promises memory sync) would not hold. */ +async function confirmLink( + api: TuiPluginApi, + recorded: Awaited>, + label: LinkedProps["verb"], + datamateId: number, + datamateName: string, +): Promise { + if (recorded?.status === "account-changed") { + api.ui.toast({ + variant: "warning", + message: "Linked, but your Altimate account changed during the link, so saved memory was not sent.", + duration: 8_000, + }) + return + } + await showLinkedConfirmation(api, label, datamateId, datamateName) +} + /** Show the persistent linked-confirmation dialog. Builds the manage URL * best-effort; degrades gracefully on BYOK/unresolvable. */ async function showLinkedConfirmation( @@ -622,42 +644,37 @@ async function runBrowserHandoff( // ids are tenant-schema-local (same integer, different workspace). Compare // the credential fingerprint the handoff was validated against with the // credentials we're about to bind under, and refuse if either drifted. - // The credential checked here is the one the bind runs as, and the one any error names. - let bindAs: ActAs - try { - const fresh = await AltimateApi.getCredentials() - bindAs = { url: fresh.altimateUrl, instance: fresh.altimateInstanceName, apiKey: fresh.altimateApiKey } - if ( - fresh.altimateInstanceName !== result.credentials.tenant || - fresh.altimateUrl !== result.credentials.apiUrl - ) { - api.ui.toast({ - variant: "error", - message: `Your Altimate credentials changed while the browser was open (was ${result.credentials.tenant}, now ${fresh.altimateInstanceName}). Re-run to link this project.`, - duration: 15_000, - }) - return - } - } catch { + // The credential checked here is the one the bind runs as, the one its record is pinned to, + // and the one any error names. + const bindAs = await WorkspaceApi.captureCredentials() + if (!bindAs) { api.ui.toast({ variant: "error", message: "Lost Altimate credentials while the browser was open — sign in and re-run.", }) return } + if (bindAs.instance !== result.credentials.tenant || bindAs.url !== result.credentials.apiUrl) { + api.ui.toast({ + variant: "error", + message: `Your Altimate credentials changed while the browser was open (was ${result.credentials.tenant}, now ${bindAs.instance}). Re-run to link this project.`, + duration: 15_000, + }) + return + } // Handoff succeeded and credentials are still consistent — bind the project // to the returned workspace via the existing bind endpoint. Same code path // as PickerDialog's attach mode. try { const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier, bindAs) - await recordApprovedBinding(api.state.path.directory, { + const recorded = await recordApprovedBinding(api.state.path.directory, { datamateId: res.binding.datamate_id, datamateName: res.binding.datamate_name, repoRemote: res.binding.repo_remote, projectPath: res.binding.project_path, linkedAt: Date.now(), - }) - await showLinkedConfirmation(api, "Linked", res.binding.datamate_id, res.binding.datamate_name) + }, { account: digestOf(bindAs) }) + await confirmLink(api, recorded, "Linked", res.binding.datamate_id, res.binding.datamate_name) } catch (err) { if (err instanceof ConflictError) { api.ui.toast({ @@ -848,14 +865,14 @@ export async function createAndBindInline( // toast fallback keeps the user informed without taking the process down. // (Kilo cycle 5.) try { - await recordApprovedBinding(api.state.path.directory, { + const recorded = await recordApprovedBinding(api.state.path.directory, { datamateId: res.datamate.id, datamateName: res.datamate.name, repoRemote: serverBinding?.repo_remote ?? identifier.repoRemote ?? null, projectPath: serverBinding?.project_path ?? identifier.projectPath ?? null, linkedAt: Date.now(), - }) - await showLinkedConfirmation(api, "Created", res.datamate.id, res.datamate.name) + }, { account: digestOf(createAs) }) + await confirmLink(api, recorded, "Created", res.datamate.id, res.datamate.name) } catch (err) { // Log the failure so a regression in ``showLinkedConfirmation`` doesn't // vanish silently, then fall back to a plain toast. Previously ``void err`` @@ -1106,15 +1123,16 @@ function PickerDialog(props: PickerProps) { try { if (props.mode === "attach") { const res = await WorkspaceApi.bindExisting(datamateId, props.identifier, pickAs) - await recordApprovedBinding(props.api.state.path.directory, { + const recorded = await recordApprovedBinding(props.api.state.path.directory, { datamateId: res.binding.datamate_id, datamateName: res.binding.datamate_name, repoRemote: res.binding.repo_remote, projectPath: res.binding.project_path, linkedAt: Date.now(), - }) - await showLinkedConfirmation( + }, { account: digestOf(pickAs) }) + await confirmLink( props.api, + recorded, "Linked", res.binding.datamate_id, res.binding.datamate_name, @@ -1136,15 +1154,16 @@ function PickerDialog(props: PickerProps) { matchedBy: props.matchedBy, actAs: pickAs, }) - await recordApprovedBinding(props.api.state.path.directory, { + const recorded = await recordApprovedBinding(props.api.state.path.directory, { datamateId: res.binding.datamate_id, datamateName: res.binding.datamate_name, repoRemote: res.binding.repo_remote, projectPath: res.binding.project_path, linkedAt: Date.now(), - }) - await showLinkedConfirmation( + }, { account: digestOf(pickAs) }) + await confirmLink( props.api, + recorded, "Re-linked", res.binding.datamate_id, res.binding.datamate_name, @@ -1406,19 +1425,11 @@ export async function bindOrRebindInline( projectPath: res.binding.project_path, linkedAt: Date.now(), }, - listedAccount ? { account: listedAccount } : undefined, + { account: digestOf(bindAs) }, ) - if (recorded?.status === "account-changed") { - // The bind ran as the listed account; only the local record and seed were refused. - api.ui.toast({ - variant: "warning", - message: "Linked, but your Altimate account changed during the link, so saved memory was not sent.", - duration: 8_000, - }) - return - } - await showLinkedConfirmation( + await confirmLink( api, + recorded, isRebind ? "Re-linked" : "Linked", res.binding.datamate_id, res.binding.datamate_name, diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index e415c34f56..c46d8eba76 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -47,7 +47,7 @@ const { createThenBindOrRebind } = await import("@/cli/cmd/link") const { createAndBindInline, bindOrRebindInline, runWorkspaceManage } = await import( "@/plugin/tui/altimate/workspace" ) -const { recordApprovedBinding } = await import("@/altimate/workspace/state") +const { recordApprovedBinding, readLocalBinding } = await import("@/altimate/workspace/state") const { flushPendingSyncs } = await import("@/altimate/workspace/skill-sync") const { hiddenBindingMessage, QUICK_WORKSPACE_PRIVATE_NOTE } = await import( "@/altimate/workspace/api-client" @@ -259,6 +259,33 @@ describe("TUI: createAndBindInline", () => { expect(sequence()).toEqual(["POST /datamate-project-bindings/"]) }) + test("a create whose account is switched mid-request is not recorded under the next account", async () => { + routes = [ + { + match: /datamate-project-bindings\/$/, + method: "POST", + status: 200, + body: { datamate: { id: 7, name: "proj" }, binding: BINDING, manage_url: "https://x.test/w/7" }, + }, + ] + const credentials = path.join(SANDBOX, "home", ".altimate", "altimate.json") + const acme = { altimateUrl: API_URL, altimateInstanceName: "acme", altimateApiKey: "test-key" } + onRequest = (call) => { + if (call.method === "POST" && call.path === "/datamate-project-bindings/") + writeFileSync(credentials, JSON.stringify({ ...acme, altimateInstanceName: "other", altimateApiKey: "other-key" })) + } + const { api, toasts } = stubApi() + try { + await createAndBindInline(api, IDENTIFIER, "proj") + // Workspace 7 belongs to "acme": the account signed in now must not find it as its link. + expect(await readLocalBinding("/tmp/proj")).toBeNull() + // And the confirmation says the link stands but nothing was synced, instead of the usual one. + expect(toasts.some((t) => t.variant === "warning" && /account changed during the link/.test(t.message))).toBe(true) + } finally { + writeFileSync(credentials, JSON.stringify(acme)) + } + }) + test("a failed rebind toasts the orphan instead of reporting success", async () => { routes = [ { match: /\/datamates\/$/, method: "POST", status: 200, body: { id: 7 } }, From 33d4e2f422fbf4058ea6d9da5f7241d0033c150e Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 09:39:50 +0530 Subject: [PATCH 06/11] refactor: share the code-point clip between workspace names and message values Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/workspace-name.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/workspace-name.ts b/packages/opencode/src/altimate/workspace/workspace-name.ts index b6249718b2..6459c52d8a 100644 --- a/packages/opencode/src/altimate/workspace/workspace-name.ts +++ b/packages/opencode/src/altimate/workspace/workspace-name.ts @@ -15,9 +15,13 @@ * what the model reads. */ export const MAX_WORKSPACE_NAME_CHARS = 80 export function inertWorkspaceName(name: string): string { - const cleaned = oneLine(name) - const points = Array.from(cleaned) - return points.length > MAX_WORKSPACE_NAME_CHARS ? points.slice(0, MAX_WORKSPACE_NAME_CHARS - 1).join("") + "…" : cleaned + return clipCodePoints(oneLine(name), MAX_WORKSPACE_NAME_CHARS) +} + +/** `text` cut to at most `max` code points, ending in "…" when cut. Never splits a surrogate pair. */ +function clipCodePoints(text: string, max: number): string { + const points = Array.from(text) + return points.length > max ? points.slice(0, max - 1).join("") + "…" : text } /** The rendered label — quoted name plus id — after JSON escaping, budgeted on that @@ -84,10 +88,7 @@ export const MAX_MESSAGE_VALUE_CHARS = 254 /** Server-sourced text placed inside a message: on one line, no control or bidi characters, * and clipped so a bad value cannot flood a toast or a terminal line. */ export function inertMessageValue(text: string): string { - const points = Array.from(oneLine(stripBidiControls(text))) - return points.length > MAX_MESSAGE_VALUE_CHARS - ? points.slice(0, MAX_MESSAGE_VALUE_CHARS - 1).join("") + "…" - : points.join("") + return clipCodePoints(oneLine(stripBidiControls(text)), MAX_MESSAGE_VALUE_CHARS) } /** A workspace name as a dialog shows it: inert, and with no bidi controls. */ From c725ecc30914f53479f32bfef4b1cebb6d4aa0a8 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 09:59:44 +0530 Subject: [PATCH 07/11] fix: close the picker when a link's account changes mid-request When the local record is refused because the account changed, the picker now closes, as the confirmation would have replaced it. The create, browser handoff and inline paths already close their dialog at the start, so only the picker passes the flag. The CLI create flow pins its record to the create's own credential, without the earlier flow-start fallback. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/link.ts | 9 ++++---- .../src/plugin/tui/altimate/workspace.tsx | 6 ++++++ .../test/altimate/plugin/workspace.test.ts | 21 +++++++++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index ba4089274f..33db63aab2 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -590,10 +590,9 @@ export async function createThenBindOrRebind( /** False for a headless run: print the manage URL, but there is nobody at a browser to look at it. */ opts: { openBrowser?: boolean } = {}, ): Promise { - // The account this bind acts as; the seed refuses (account-changed) if it switches mid-way. - // Unreadable credentials cannot link anyway, and must not leave the bind unguarded. - const linkAccount = await accountDigest() - if (linkAccount === null) { + // Unreadable credentials cannot create anyway: stop before the create. The create and its + // local record use the credential captured just before the request. + if ((await accountDigest()) === null) { prompts.log.error("Could not read your Altimate credentials, so nothing was linked. Check /connect and try again.") process.exitCode = 1 return @@ -722,7 +721,7 @@ export async function createThenBindOrRebind( repoRemote: serverBinding?.repo_remote ?? identifier.repoRemote ?? null, projectPath: serverBinding?.project_path ?? identifier.projectPath ?? null, linkedAt: Date.now(), - }, { awaitBackfill: true, account: digestOf(createAs) ?? linkAccount }) + }, { awaitBackfill: true, account: digestOf(createAs) }) prompts.log.info(seedMessage(seed)) // The quick create is private, and the server hides a private workspace's link from // everyone else: a teammate who clones this repo is told it is unlinked. diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 1bdbd53b5e..dba08b21d4 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -483,8 +483,12 @@ async function confirmLink( label: LinkedProps["verb"], datamateId: number, datamateName: string, + /** The link was started from a dialog that is still open (the picker). The confirmation + * would replace it; without one, close it, or choosing again from it links a second time. */ + openDialog = false, ): Promise { if (recorded?.status === "account-changed") { + if (openDialog) api.ui.dialog.clear() api.ui.toast({ variant: "warning", message: "Linked, but your Altimate account changed during the link, so saved memory was not sent.", @@ -1136,6 +1140,7 @@ function PickerDialog(props: PickerProps) { "Linked", res.binding.datamate_id, res.binding.datamate_name, + true, ) return } else { @@ -1167,6 +1172,7 @@ function PickerDialog(props: PickerProps) { "Re-linked", res.binding.datamate_id, res.binding.datamate_name, + true, ) return } diff --git a/packages/opencode/test/altimate/plugin/workspace.test.ts b/packages/opencode/test/altimate/plugin/workspace.test.ts index 993ffadaca..b247b15cc7 100644 --- a/packages/opencode/test/altimate/plugin/workspace.test.ts +++ b/packages/opencode/test/altimate/plugin/workspace.test.ts @@ -1105,6 +1105,27 @@ describe("link dialogs: a workspace that already has this project's name", () => expect(h.toasts).toHaveLength(1) expect(h.toasts[0]).toContain('(workspace id 38) that serviceuser@example.com on instance "acme"') }) + + test("picker: a link whose account is switched mid-request closes the picker and says so", async () => { + stubWorkspaces([{ id: 2, name: "analytics", ownerId: ME }]) + stubCreds("acme", "https://api.acme.example.com") + api.bindExisting = async (id: number) => { + stubCreds("other-tenant", "https://api.other.example.com") + return { + binding: { id: 1, datamate_id: id, datamate_name: "analytics", repo_remote: identifier.repoRemote, project_path: null }, + } + } + const { tui, h } = harness() + render(() => linkDialogInternals.PickerDialog({ api: tui, identifier, mode: "attach" })) + await settle() + h.selects[0]!.onSelect({ value: 2 }) + await settle() + // Linked server-side under "acme", but the account changed: no confirmation dialog, the + // picker closed so it cannot link a second time, and the warning explains why. + expect(h.replaced).toHaveLength(0) + expect(h.cleared).toBe(1) + expect(h.toasts.some((m) => m.includes("account changed during the link"))).toBe(true) + }) }) describe("/integrations", () => { From fc8ba55a23bbbfb8461b31f414c5f81c06390441 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 10:11:47 +0530 Subject: [PATCH 08/11] fix: run the already-linked create and its rebind as the captured account When a project already linked elsewhere gets a new workspace, the unbound create and the rebind that follows now run as the same credential the flow captured, which is also the one its local record is pinned to (createWorkspaceUnbound takes an optional actAs, like createAndBind). Applies to the CLI and the TUI. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/workspace/api-client.ts | 2 + packages/opencode/src/cli/cmd/link.ts | 10 ++-- .../src/plugin/tui/altimate/workspace.tsx | 5 +- .../workspace/create-then-rebind.test.ts | 53 ++++++++++++++++++- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 2a95257fbf..4af0971b40 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -784,6 +784,7 @@ export namespace WorkspaceApi { export async function createWorkspaceUnbound(input: { name: string description?: string + actAs?: ActAs }): Promise<{ id: number; name: string }> { // The id check sits inside the reported attempt: a create whose answer is unusable is a // failed link step, not a created workspace. @@ -798,6 +799,7 @@ export namespace WorkspaceApi { knowledge_engine_enabled: true, privacy: "private", }, + ...(input.actAs ? { actAs: input.actAs } : {}), }) // `typeof` FIRST, before any arithmetic. `Number()` coerces, so the // previous `Number.isSafeInteger(Number(data?.id))` accepted `true` as 1, diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 33db63aab2..d7afb6d7f6 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -590,8 +590,9 @@ export async function createThenBindOrRebind( /** False for a headless run: print the manage URL, but there is nobody at a browser to look at it. */ opts: { openBrowser?: boolean } = {}, ): Promise { - // Unreadable credentials cannot create anyway: stop before the create. The create and its - // local record use the credential captured just before the request. + // Unreadable credentials cannot create anyway: stop before the create. Every write below + // (the create, and the rebind that may follow) and the local record use the one credential + // captured just before the create. if ((await accountDigest()) === null) { prompts.log.error("Could not read your Altimate credentials, so nothing was linked. Check /connect and try again.") process.exitCode = 1 @@ -613,7 +614,7 @@ export async function createThenBindOrRebind( // create the workspace on one tenant and rebind on another using an id that // is local to the first. (review, PR #1314) const account = await WorkspaceApi.accountFingerprint().catch(() => null) - // The create-and-bind and any error about it name the same account. + // Every write in this flow, its local record and any error about it use this one account. const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined try { // Two different creates, because the server offers two different things. @@ -628,7 +629,7 @@ export async function createThenBindOrRebind( // Create unbound first, then repoint, which is what the row's own hint // promises. if (existing) { - const ws = await WorkspaceApi.createWorkspaceUnbound({ name }) + const ws = await WorkspaceApi.createWorkspaceUnbound({ name, actAs: createAs }) created = { via: "unbound", datamate: ws } } else { const res = await WorkspaceApi.createAndBind({ name, identifier, actAs: createAs }) @@ -694,6 +695,7 @@ export async function createThenBindOrRebind( targetDatamateId: created.datamate.id, expectedCurrentDatamateId: existing.datamate.id, matchedBy: existing.matchedBy, + actAs: createAs, }) reboundBinding = res.binding rebindSpin.stop(`Project is now linked to "${safeCreatedName}".`) diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index dba08b21d4..0bf4b361c2 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -791,11 +791,11 @@ export async function createAndBindInline( // requests resolve credentials independently, and a workspace id means // nothing on a different account. const account = await WorkspaceApi.accountFingerprint().catch(() => null) - // The create-and-bind and any error about it name the same account. + // Every write in this flow, its local record and any error about it use this one account. const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined try { if (rebindFrom) { - const ws = await WorkspaceApi.createWorkspaceUnbound({ name }) + const ws = await WorkspaceApi.createWorkspaceUnbound({ name, actAs: createAs }) res = { via: "unbound", datamate: ws } } else { const created = await WorkspaceApi.createAndBind({ name, identifier, actAs: createAs }) @@ -844,6 +844,7 @@ export async function createAndBindInline( targetDatamateId: res.datamate.id, expectedCurrentDatamateId: rebindFrom.expectedCurrentDatamateId, matchedBy: rebindFrom.matchedBy, + actAs: createAs, }) reboundBinding = rebound.binding } catch (err) { diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index c46d8eba76..ea52082f67 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -49,7 +49,7 @@ const { createAndBindInline, bindOrRebindInline, runWorkspaceManage } = await im ) const { recordApprovedBinding, readLocalBinding } = await import("@/altimate/workspace/state") const { flushPendingSyncs } = await import("@/altimate/workspace/skill-sync") -const { hiddenBindingMessage, QUICK_WORKSPACE_PRIVATE_NOTE } = await import( +const { hiddenBindingMessage, QUICK_WORKSPACE_PRIVATE_NOTE, WorkspaceApi } = await import( "@/altimate/workspace/api-client" ) @@ -191,6 +191,31 @@ describe("CLI: createThenBindOrRebind", () => { expect(process.exitCode ?? 0).toBe(0) }) + test("the unbound create and its rebind both run as the credential the flow captured", async () => { + routes = [ + { match: /\/datamates\/$/, method: "POST", status: 200, body: { id: 7 } }, + { match: /by-remote/, method: "PUT", status: 200, body: { binding: BINDING } }, + ] + const api = WorkspaceApi as unknown as Record Promise> + const original = { create: api.createWorkspaceUnbound, rebind: api.rebindByRemote } + const ranAs: string[] = [] + api.createWorkspaceUnbound = (input: { actAs?: { instance: string } }) => { + ranAs.push(`create:${input.actAs?.instance}`) + return original.create(input) + } + api.rebindByRemote = (input: { actAs?: { instance: string } }) => { + ranAs.push(`rebind:${input.actAs?.instance}`) + return original.rebind(input) + } + try { + await createThenBindOrRebind(IDENTIFIER, "proj", "/tmp/proj", EXISTING) + } finally { + api.createWorkspaceUnbound = original.create + api.rebindByRemote = original.rebind + } + expect(ranAs).toEqual(["create:acme", "rebind:acme"]) + }) + test("a failed rebind reports the orphan rather than claiming success", async () => { routes = [ { match: /\/datamates\/$/, method: "POST", status: 200, body: { id: 7 } }, @@ -259,6 +284,32 @@ describe("TUI: createAndBindInline", () => { expect(sequence()).toEqual(["POST /datamate-project-bindings/"]) }) + test("the unbound create and its rebind both run as the credential the flow captured", async () => { + routes = [ + { match: /\/datamates\/$/, method: "POST", status: 200, body: { id: 7 } }, + { match: /by-remote/, method: "PUT", status: 200, body: { binding: BINDING } }, + ] + const ws = WorkspaceApi as unknown as Record Promise> + const original = { create: ws.createWorkspaceUnbound, rebind: ws.rebindByRemote } + const ranAs: string[] = [] + ws.createWorkspaceUnbound = (input: { actAs?: { instance: string } }) => { + ranAs.push(`create:${input.actAs?.instance}`) + return original.create(input) + } + ws.rebindByRemote = (input: { actAs?: { instance: string } }) => { + ranAs.push(`rebind:${input.actAs?.instance}`) + return original.rebind(input) + } + const { api } = stubApi() + try { + await createAndBindInline(api, IDENTIFIER, "proj", { expectedCurrentDatamateId: 3, matchedBy: "remote" }) + } finally { + ws.createWorkspaceUnbound = original.create + ws.rebindByRemote = original.rebind + } + expect(ranAs).toEqual(["create:acme", "rebind:acme"]) + }) + test("a create whose account is switched mid-request is not recorded under the next account", async () => { routes = [ { From 9f5b8e2249e6d05aae60818881dcc50ee2af62bd Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 10:22:47 +0530 Subject: [PATCH 09/11] fix: derive the pre-rebind account check from the captured credential The check that refuses the rebind after an account switch now compares against the credential the create ran as, not a separate read taken a moment earlier. The comment says what the captured credential covers (the create, the rebind, the local record and errors) and what it does not (the memory seed and skill sync). Adds a request-level test that createWorkspaceUnbound sends to the given credential's host, tenant and key. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/link.ts | 12 ++++++------ .../src/plugin/tui/altimate/workspace.tsx | 11 ++++++----- .../workspace/create-workspace-unbound.test.ts | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index d7afb6d7f6..3dfcbce953 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -609,13 +609,13 @@ export async function createThenBindOrRebind( | { via: "bound"; datamate: DatamateRef; binding: Binding; manage_url: string } | { via: "unbound"; datamate: DatamateRef } let created: Created - // Captured BEFORE the create and re-checked before the rebind. Each request - // resolves credentials on its own, so an account switch in between would - // create the workspace on one tenant and rebind on another using an id that - // is local to the first. (review, PR #1314) - const account = await WorkspaceApi.accountFingerprint().catch(() => null) - // Every write in this flow, its local record and any error about it use this one account. + // The create, the rebind that may follow, the local record and any error about them all use + // this one credential. The memory seed and skill sync that follow the record use the current + // one, and the record refuses if the account changed. const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined + // Re-checked before the rebind: the rebind is refused if the signed-in account changed since, + // since the user would not find the link on the account they are on now. + const account = createAs ? { apiUrl: createAs.url, tenant: createAs.instance } : null try { // Two different creates, because the server offers two different things. // diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 0bf4b361c2..3d4933b119 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -787,12 +787,13 @@ export async function createAndBindInline( | { via: "bound"; datamate: DatamateRef; binding: Binding } | { via: "unbound"; datamate: DatamateRef } let res: Created - // Captured before the create and re-checked before the rebind: the two - // requests resolve credentials independently, and a workspace id means - // nothing on a different account. - const account = await WorkspaceApi.accountFingerprint().catch(() => null) - // Every write in this flow, its local record and any error about it use this one account. + // The create, the rebind that may follow, the local record and any error about them all use + // this one credential. The memory seed and skill sync that follow the record use the current + // one, and the record refuses if the account changed. const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined + // Re-checked before the rebind: the rebind is refused if the signed-in account changed since, + // since the user would not find the link on the account they are on now. + const account = createAs ? { apiUrl: createAs.url, tenant: createAs.instance } : null try { if (rebindFrom) { const ws = await WorkspaceApi.createWorkspaceUnbound({ name, actAs: createAs }) diff --git a/packages/opencode/test/altimate/workspace/create-workspace-unbound.test.ts b/packages/opencode/test/altimate/workspace/create-workspace-unbound.test.ts index fcd8c80cc9..9482023604 100644 --- a/packages/opencode/test/altimate/workspace/create-workspace-unbound.test.ts +++ b/packages/opencode/test/altimate/workspace/create-workspace-unbound.test.ts @@ -50,6 +50,7 @@ interface Captured { url: string method: string body: Record + headers: Headers } let captured: Captured[] = [] @@ -61,6 +62,7 @@ function respondWith(status: number, reply: unknown) { url: String(input), method: String(init?.method ?? "GET"), body: init?.body ? JSON.parse(String(init.body)) : {}, + headers: new Headers(init?.headers), }) return new Response(JSON.stringify(reply), { status, @@ -83,6 +85,19 @@ afterAll(() => { }) describe("createWorkspaceUnbound", () => { + test("runs as the given credential, not the configured one", async () => { + respondWith(200, { id: 77 }) + await WorkspaceApi.createWorkspaceUnbound({ + name: "jaffle_shop", + actAs: { url: "https://other.example.test", instance: "other", apiKey: "other-key" }, + }) + + expect(captured).toHaveLength(1) + expect(captured[0].url).toBe("https://other.example.test/datamates/") + expect(captured[0].headers.get("x-tenant")).toBe("other") + expect(captured[0].headers.get("authorization")).toBe("Bearer other-key") + }) + test("posts to /datamates/, NOT to the binding router", async () => { respondWith(200, { id: 77 }) await WorkspaceApi.createWorkspaceUnbound({ name: "jaffle_shop" }) From b5f64c735cb70870a4d109e8134e1af302903600 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 10:41:05 +0530 Subject: [PATCH 10/11] fix: create nothing when no credential can be captured The create flows (CLI and TUI) now stop before any write when the credential cannot be read, instead of falling back to independent reads that skip the pre-rebind account check. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/link.ts | 9 +++++-- .../src/plugin/tui/altimate/workspace.tsx | 11 ++++++-- .../workspace/create-then-rebind.test.ts | 27 +++++++++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 3dfcbce953..0677d6fb57 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -612,10 +612,15 @@ export async function createThenBindOrRebind( // The create, the rebind that may follow, the local record and any error about them all use // this one credential. The memory seed and skill sync that follow the record use the current // one, and the record refuses if the account changed. - const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined + const createAs = await WorkspaceApi.captureCredentials() + if (!createAs) { + prompts.log.error("Could not read your Altimate credentials, so nothing was created. Check /connect and try again.") + process.exitCode = 1 + return + } // Re-checked before the rebind: the rebind is refused if the signed-in account changed since, // since the user would not find the link on the account they are on now. - const account = createAs ? { apiUrl: createAs.url, tenant: createAs.instance } : null + const account = { apiUrl: createAs.url, tenant: createAs.instance } try { // Two different creates, because the server offers two different things. // diff --git a/packages/opencode/src/plugin/tui/altimate/workspace.tsx b/packages/opencode/src/plugin/tui/altimate/workspace.tsx index 3d4933b119..4390d4e0cf 100644 --- a/packages/opencode/src/plugin/tui/altimate/workspace.tsx +++ b/packages/opencode/src/plugin/tui/altimate/workspace.tsx @@ -790,10 +790,17 @@ export async function createAndBindInline( // The create, the rebind that may follow, the local record and any error about them all use // this one credential. The memory seed and skill sync that follow the record use the current // one, and the record refuses if the account changed. - const createAs = (await WorkspaceApi.captureCredentials()) ?? undefined + const createAs = await WorkspaceApi.captureCredentials() + if (!createAs) { + api.ui.toast({ + variant: "error", + message: "Could not read your Altimate credentials, so nothing was created. Check /connect and try again.", + }) + return + } // Re-checked before the rebind: the rebind is refused if the signed-in account changed since, // since the user would not find the link on the account they are on now. - const account = createAs ? { apiUrl: createAs.url, tenant: createAs.instance } : null + const account = { apiUrl: createAs.url, tenant: createAs.instance } try { if (rebindFrom) { const ws = await WorkspaceApi.createWorkspaceUnbound({ name, actAs: createAs }) diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index ea52082f67..e0cb8a4084 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -191,6 +191,19 @@ describe("CLI: createThenBindOrRebind", () => { expect(process.exitCode ?? 0).toBe(0) }) + test("with no readable credential it creates nothing", async () => { + const ws = WorkspaceApi as unknown as Record Promise> + const original = ws.captureCredentials + ws.captureCredentials = async () => null + try { + await createThenBindOrRebind(IDENTIFIER, "proj", "/tmp/proj", EXISTING) + } finally { + ws.captureCredentials = original + } + expect(sequence()).toEqual([]) + expect(process.exitCode).toBe(1) + }) + test("the unbound create and its rebind both run as the credential the flow captured", async () => { routes = [ { match: /\/datamates\/$/, method: "POST", status: 200, body: { id: 7 } }, @@ -310,6 +323,20 @@ describe("TUI: createAndBindInline", () => { expect(ranAs).toEqual(["create:acme", "rebind:acme"]) }) + test("with no readable credential it creates nothing", async () => { + const ws = WorkspaceApi as unknown as Record Promise> + const original = ws.captureCredentials + ws.captureCredentials = async () => null + const { api, toasts } = stubApi() + try { + await createAndBindInline(api, IDENTIFIER, "proj", { expectedCurrentDatamateId: 3, matchedBy: "remote" }) + } finally { + ws.captureCredentials = original + } + expect(sequence()).toEqual([]) + expect(toasts.some((t) => t.variant === "error" && /nothing was created/.test(t.message))).toBe(true) + }) + test("a create whose account is switched mid-request is not recorded under the next account", async () => { routes = [ { From 974bbf1a7dfedc67941f0eee78a0d5684ae14212 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Thu, 19 Nov 2026 11:07:35 +0530 Subject: [PATCH 11/11] fix: read the create's credential once, before the spinner starts The CLI create flow captures its credential before anything starts and uses that one read for the readability check, so an unreadable credential no longer leaves the spinner running over the error, and the duplicate check and message are gone. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/link.ts | 20 ++++++------------- .../workspace/create-then-rebind.test.ts | 12 +++++++++++ 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/opencode/src/cli/cmd/link.ts b/packages/opencode/src/cli/cmd/link.ts index 0677d6fb57..56fd23ee76 100644 --- a/packages/opencode/src/cli/cmd/link.ts +++ b/packages/opencode/src/cli/cmd/link.ts @@ -590,11 +590,12 @@ export async function createThenBindOrRebind( /** False for a headless run: print the manage URL, but there is nobody at a browser to look at it. */ opts: { openBrowser?: boolean } = {}, ): Promise { - // Unreadable credentials cannot create anyway: stop before the create. Every write below - // (the create, and the rebind that may follow) and the local record use the one credential - // captured just before the create. - if ((await accountDigest()) === null) { - prompts.log.error("Could not read your Altimate credentials, so nothing was linked. Check /connect and try again.") + // The create, the rebind that may follow, the local record and any error about them all use + // this one credential, captured before anything starts. The memory seed and skill sync that + // follow the record use the current one, and the record refuses if the account changed. + const createAs = await WorkspaceApi.captureCredentials() + if (!createAs) { + prompts.log.error("Could not read your Altimate credentials, so nothing was created. Check /connect and try again.") process.exitCode = 1 return } @@ -609,15 +610,6 @@ export async function createThenBindOrRebind( | { via: "bound"; datamate: DatamateRef; binding: Binding; manage_url: string } | { via: "unbound"; datamate: DatamateRef } let created: Created - // The create, the rebind that may follow, the local record and any error about them all use - // this one credential. The memory seed and skill sync that follow the record use the current - // one, and the record refuses if the account changed. - const createAs = await WorkspaceApi.captureCredentials() - if (!createAs) { - prompts.log.error("Could not read your Altimate credentials, so nothing was created. Check /connect and try again.") - process.exitCode = 1 - return - } // Re-checked before the rebind: the rebind is refused if the signed-in account changed since, // since the user would not find the link on the account they are on now. const account = { apiUrl: createAs.url, tenant: createAs.instance } diff --git a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts index e0cb8a4084..c25bc0c177 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -195,13 +195,25 @@ describe("CLI: createThenBindOrRebind", () => { const ws = WorkspaceApi as unknown as Record Promise> const original = ws.captureCredentials ws.captureCredentials = async () => null + const written: string[] = [] + const streams = [process.stdout, process.stderr] + const writes = streams.map((s) => s.write) + for (const s of streams) + s.write = ((chunk: string | Uint8Array) => { + written.push(String(chunk)) + return true + }) as typeof s.write try { await createThenBindOrRebind(IDENTIFIER, "proj", "/tmp/proj", EXISTING) } finally { + streams.forEach((s, i) => (s.write = writes[i]!)) ws.captureCredentials = original } expect(sequence()).toEqual([]) expect(process.exitCode).toBe(1) + // Stopped before the spinner started, so nothing is left spinning over the error. + expect(written.join("")).not.toContain("Creating workspace") + expect(written.join("")).toContain("nothing was created") }) test("the unbound create and its rebind both run as the credential the flow captured", async () => {