diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 5a35b8c549..4af0971b40 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -12,8 +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 { inertMessageValue } from "./workspace-name" const REQUEST_TIMEOUT_MS = 15_000 +const SIGNED_IN_LOOKUP_TIMEOUT_MS = 3_000 export interface DatamateRef { id: number @@ -106,19 +108,51 @@ export class NotConfiguredError extends Error { } } +/** The account a request ran as, named in a hidden-binding conflict. */ +export interface SignedInAccount { + email: string + instance: string +} + /** 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 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. " + + "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. 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)) +} /** 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 = @@ -680,6 +714,7 @@ export namespace WorkspaceApi { name: string identifier: ProjectIdentifier description?: string + actAs?: ActAs }): Promise { const res = await linkAttempt("create_and_bind", undefined, () => req("POST", "/", { @@ -689,6 +724,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 @@ -748,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. @@ -762,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, @@ -918,14 +956,36 @@ 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", { + 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 + } + + /** 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 { + // 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 } : {}), }) - const id = Number(me?.id) - if (!Number.isInteger(id) || id <= 0) throw new WorkspaceApiError("The server did not say who this account is.") - return id } } 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/altimate/workspace/workspace-name.ts b/packages/opencode/src/altimate/workspace/workspace-name.ts index 60c56ebac0..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 @@ -68,6 +72,25 @@ export function stripBidiControls(text: string): string { return text.replace(BIDI_CONTROLS, "") } +/** Strip C0/C1 control bytes (including ESC) and bidi controls from server-controlled text + * 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. + // eslint-disable-next-line no-control-regex + 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 { + return clipCodePoints(oneLine(stripBidiControls(text)), MAX_MESSAGE_VALUE_CHARS) +} + /** 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 7cdce3bdbb..56fd23ee76 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, @@ -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, @@ -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" @@ -465,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 @@ -485,29 +468,27 @@ 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). - try { - const fresh = await AltimateApi.getCredentials() - 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...") 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 @@ -520,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) @@ -534,7 +515,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, bindAs)} Workspace "${projectName}" was created but is not linked.`) } else if (err instanceof ConflictError) { const existingName = conflictExistingName(err.detail) prompts.log.error( @@ -609,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 { - // 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) { - 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 } @@ -628,11 +610,9 @@ 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) + // 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 } try { // Two different creates, because the server offers two different things. // @@ -646,10 +626,10 @@ 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 }) + 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 +646,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, createAs)} Nothing was created.`) } else { const existingName = conflictExistingName(err.detail) prompts.log.error( @@ -712,6 +692,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}".`) @@ -739,7 +720,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) }) 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. @@ -906,7 +887,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..4390d4e0cf 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, @@ -87,6 +87,7 @@ import { sameIdentifier } from "@/altimate/workspace/remote-identity" import { accountDigest, credentialDigest, + digestOf, readLocalBinding, recordApprovedBinding, resolvePinnedBindingForRouting, @@ -473,6 +474,31 @@ 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, + /** 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.", + 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,45 +648,43 @@ 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. - try { - const fresh = await AltimateApi.getCredentials() - 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) - await recordApprovedBinding(api.state.path.directory, { + const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier, bindAs) + 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({ variant: "warning", message: isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? 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) { @@ -763,16 +787,26 @@ 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) + // 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) { + 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 = { apiUrl: createAs.url, tenant: createAs.instance } 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 }) + const created = await WorkspaceApi.createAndBind({ name, identifier, actAs: createAs }) res = { via: "bound", datamate: created.datamate, binding: created.binding } } } catch (err) { @@ -786,7 +820,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, 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, }) @@ -818,6 +852,7 @@ export async function createAndBindInline( targetDatamateId: res.datamate.id, expectedCurrentDatamateId: rebindFrom.expectedCurrentDatamateId, matchedBy: rebindFrom.matchedBy, + actAs: createAs, }) reboundBinding = rebound.binding } catch (err) { @@ -843,14 +878,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`` @@ -1096,21 +1131,25 @@ 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) - await recordApprovedBinding(props.api.state.path.directory, { + const res = await WorkspaceApi.bindExisting(datamateId, props.identifier, pickAs) + 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, + true, ) return } else { @@ -1127,19 +1166,22 @@ function PickerDialog(props: PickerProps) { targetDatamateId: datamateId, expectedCurrentDatamateId: props.expectedCurrentDatamateId, 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, + true, ) return } @@ -1147,14 +1189,17 @@ 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 // 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, 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." @@ -1166,7 +1211,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 } @@ -1372,6 +1416,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 +1426,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, @@ -1394,19 +1440,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, @@ -1415,7 +1453,7 @@ export async function bindOrRebindInline( let msg: string if (err instanceof ConflictError) { msg = isHiddenBindingConflict(err) - ? HIDDEN_BINDING_MESSAGE + ? 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." @@ -2787,7 +2825,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..b247b15cc7 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,54 @@ 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"') + }) + + 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", () => { 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..c25bc0c177 100644 --- a/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts +++ b/packages/opencode/test/altimate/workspace/create-then-rebind.test.ts @@ -47,9 +47,9 @@ 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 { HIDDEN_BINDING_MESSAGE, QUICK_WORKSPACE_PRIVATE_NOTE } = await import( +const { hiddenBindingMessage, QUICK_WORKSPACE_PRIVATE_NOTE, WorkspaceApi } = await import( "@/altimate/workspace/api-client" ) @@ -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() }) @@ -184,6 +191,56 @@ 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 + 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 () => { + 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 } }, @@ -252,6 +309,73 @@ 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("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 = [ + { + 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 } }, @@ -298,7 +422,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 +439,107 @@ 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') + }) + + 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 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() + 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 = [ { @@ -333,7 +552,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) }) }) @@ -449,3 +668,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/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" }) 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..e7abd6a2b9 100644 --- a/packages/opencode/test/altimate/workspace/link-seed-message.test.ts +++ b/packages/opencode/test/altimate/workspace/link-seed-message.test.ts @@ -23,8 +23,8 @@ 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 () => { - const { ConflictError, isHiddenBindingConflict, HIDDEN_BINDING_MESSAGE } = await import( +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" ) expect(isHiddenBindingConflict(new ConflictError({ existing_datamate_id: 7, existing_datamate_name: null } as any))).toBe(true) @@ -33,5 +33,32 @@ 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, 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) })