Skip to content

Commit 7b21606

Browse files
saravmajesticclaude
andcommitted
fix: [AI-9171] address review — fix the TUI's copy of the same bug
Review round on PR #1314. The important one is sahrizvi's: the TUI had the identical defect and this PR did not touch it. **The TUI carried the same bug.** `createAndBindInline` called `createAndBind` unconditionally, so on an already-linked project the server 409'd before creating anything and the rebind below was unreachable — exactly what this PR fixes in `link.ts`. Its `rebindFrom` doc asserted the assumption the bug rested on ("createAndBind succeeds but leaves the binding pointing at the OLD workspace"); that is corrected too. Both surfaces now make the same split, so the CLI and the TUI cannot disagree about what that row does. **`Number()` coerced its way past the id guard.** `Number.isSafeInteger(Number(x))` accepts `true` as 1, `"7"` as 7 and `[5]` as 5, so a malformed body would have rebound the project to workspace 1 rather than failing. The type check now runs before the arithmetic, and it throws a typed `WorkspaceApiError` rather than a bare `Error`, matching every other failure in that module. **The account is pinned across the two-step.** Create and rebind resolve credentials independently, so a re-login in between created the workspace on one tenant and sent the rebind to another with an id local to the first. Both surfaces capture the account before the create and refuse the rebind if it changed. The API key is deliberately not part of the fingerprint: rotating a key for the same user on the same tenant is not an identity change. **The rebind's own binding row is what gets cached.** The response was discarded and the local identifiers cached instead, so a path-keyed row rebound through `/by-path` was cached carrying a `repo_remote` the server never stored. **The 409 message no longer guesses.** It was written for the bind path and claimed a binding race; the unbound create sends no identifiers and cannot produce one. Split by which call actually ran. **`created` is a discriminated union** rather than one shape with optional halves, so `binding` and `manage_url` are only reachable on the path that has them. Not changed, with reason: cubic asked for the nested `{datamate:{id}}` shape to be accepted. `POST /datamates/` declares `response_model=CreateDatamateResponse` (`{id: int}`) and FastAPI enforces it, so that shape cannot come back from this endpoint. The strict guard above turns a contract break into a loud failure, which is the better outcome than silently accepting an unexpected shape. Tests: `create-then-rebind.test.ts` asserts the *sequence of endpoints* for both surfaces, because the bug was never in a payload — it was in which request got sent. Covers unlinked, already-linked, a failed rebind (non-zero exit / error toast, not a claimed success), and a 409 that must not reach the rebind. Each one fails if the corresponding fix is reverted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 2efd7f3 commit 7b21606

5 files changed

Lines changed: 422 additions & 40 deletions

File tree

‎packages/opencode/src/altimate/workspace/api-client.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,28 @@ export namespace WorkspaceApi {
413413
* this has to move with them; there is no endpoint that applies them without
414414
* also binding.
415415
*/
416+
/** Who the next call will act as.
417+
*
418+
* A create-then-rebind pair is two requests, and `req()` resolves credentials
419+
* independently for each. If the account changes in between — a re-login, an
420+
* edited `altimate.json` — the workspace is created in one tenant and the
421+
* rebind is sent to another with an id that is local to the first. Callers
422+
* capture this before the create and re-check it before the rebind.
423+
*
424+
* The API key is deliberately not part of it: rotating a key for the same
425+
* user on the same tenant is not an identity change, and comparing it would
426+
* abort a legitimate flow. */
427+
export async function accountFingerprint(): Promise<{ apiUrl: string; tenant: string }> {
428+
const c = await creds()
429+
return { apiUrl: c.url, tenant: c.instance }
430+
}
431+
432+
/** True when `before` still describes the account in effect. */
433+
export async function sameAccount(before: { apiUrl: string; tenant: string }): Promise<boolean> {
434+
const now = await accountFingerprint().catch(() => null)
435+
return now !== null && now.apiUrl === before.apiUrl && now.tenant === before.tenant
436+
}
437+
416438
export async function createWorkspaceUnbound(input: {
417439
name: string
418440
description?: string
@@ -428,9 +450,18 @@ export namespace WorkspaceApi {
428450
privacy: "private",
429451
},
430452
})
431-
const id = Number(data?.id)
432-
if (!Number.isSafeInteger(id) || id <= 0) {
433-
throw new Error(`Workspace was created but the server returned no usable id (${String(data?.id)}).`)
453+
// `typeof` FIRST, before any arithmetic. `Number()` coerces, so the
454+
// previous `Number.isSafeInteger(Number(data?.id))` accepted `true` as 1,
455+
// `"7"` as 7 and `[5]` as 5 — a malformed body would have rebound the
456+
// project to whatever those coerced to (workspace 1, in the boolean case)
457+
// instead of failing. The server's `CreateDatamateResponse` is `{id: int}`
458+
// and FastAPI enforces it, so anything else here is a contract break worth
459+
// refusing loudly rather than guessing at.
460+
const id: unknown = (data as { id?: unknown } | null | undefined)?.id
461+
if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) {
462+
throw new WorkspaceApiError(
463+
`Workspace was created but the server returned no usable id (${JSON.stringify(id) ?? "undefined"}).`,
464+
)
434465
}
435466
return { id, name: input.name }
436467
}

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

Lines changed: 65 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -476,16 +476,33 @@ function handoffFailureMessage(result: Extract<HandoffResult, { ok: false }>): s
476476
* real (billable) SaaS resource the CLI knows nothing about and the project
477477
* is still bound to the old workspace (M2 in the consensus review). When
478478
* rebind fails, the error message tells the user the workspace was created
479-
* and how to recover; we do NOT silently swallow the orphan. */
480-
async function createThenBindOrRebind(
479+
* and how to recover; we do NOT silently swallow the orphan.
480+
*
481+
* Exported for tests. The branch it picks — atomic create-and-bind when the
482+
* project is free, unbound-create-then-rebind when it is already linked — is
483+
* the whole of AI-9171, and nothing else in this file can assert it. */
484+
export async function createThenBindOrRebind(
481485
identifier: ProjectIdentifier,
482486
name: string,
483487
directory: string,
484488
existing: ProjectBindingLookup | null,
485489
): Promise<void> {
486490
const spin = prompts.spinner()
487491
spin.start(`Creating workspace "${name}"...`)
488-
let created: { datamate: DatamateRef; binding?: Binding; manage_url?: string }
492+
// Discriminated on how the workspace was made, because the two creates return
493+
// genuinely different things: only `bound` carries a server binding row and a
494+
// manage_url. An optional-field shape let the rest of this function reach for
495+
// `binding` on the path that never has one and silently fall through to a
496+
// default. (review, PR #1314)
497+
type Created =
498+
| { via: "bound"; datamate: DatamateRef; binding: Binding; manage_url: string }
499+
| { via: "unbound"; datamate: DatamateRef }
500+
let created: Created
501+
// Captured BEFORE the create and re-checked before the rebind. Each request
502+
// resolves credentials on its own, so an account switch in between would
503+
// create the workspace on one tenant and rebind on another using an id that
504+
// is local to the first. (review, PR #1314)
505+
const account = await WorkspaceApi.accountFingerprint().catch(() => null)
489506
try {
490507
// Two different creates, because the server offers two different things.
491508
//
@@ -500,22 +517,31 @@ async function createThenBindOrRebind(
500517
// own hint promises.
501518
if (existing) {
502519
const ws = await WorkspaceApi.createWorkspaceUnbound({ name })
503-
created = { datamate: ws }
520+
created = { via: "unbound", datamate: ws }
504521
} else {
505-
created = await WorkspaceApi.createAndBind({ name, identifier })
522+
const res = await WorkspaceApi.createAndBind({ name, identifier })
523+
created = { via: "bound", datamate: res.datamate, binding: res.binding, manage_url: res.manage_url }
506524
}
507525
} catch (err) {
508526
spin.stop("Failed to create workspace.", 1)
509-
// A 409 here can only be a binding this caller did not know about: the
510-
// already-linked path does not bind at all, and the unlinked path only
511-
// reaches the server after a pre-check that said the project was free. So
512-
// someone else's binding on the same remote/path landed in between.
527+
// Split by which call actually ran, because they cannot 409 for the same
528+
// reason. `createAndBind` sends the project identifiers, so its conflict is
529+
// a binding race. The unbound create sends none — it cannot produce an
530+
// identity conflict at all, so attributing one there would have sent the
531+
// user looking for a race that did not happen. (review, PR #1314)
513532
if (err instanceof ConflictError) {
514-
const existingName = conflictExistingName(err.detail)
515-
prompts.log.error(
516-
`Another workspace, "${existingName}", claimed this project while you were choosing. ` +
517-
`Nothing was created. Run \`altimate-code link\` again to see the current list.`,
518-
)
533+
if (existing) {
534+
prompts.log.error(
535+
`The workspace could not be created: ${err.message}. Nothing was created, and this ` +
536+
`project is still linked to "${stripControlChars(existing.datamate.name)}".`,
537+
)
538+
} else {
539+
const existingName = conflictExistingName(err.detail)
540+
prompts.log.error(
541+
`Another workspace, "${existingName}", claimed this project while you were choosing. ` +
542+
`Nothing was created. Run \`altimate-code link\` again to see the current list.`,
543+
)
544+
}
519545
} else {
520546
prompts.log.error(err instanceof Error ? err.message : String(err))
521547
}
@@ -531,16 +557,31 @@ async function createThenBindOrRebind(
531557
// The already-linked path created an unbound workspace above, so the binding
532558
// still points at the OLD one — repoint it now. The unlinked path already got
533559
// its binding from the atomic create, so there is nothing left to do.
560+
let reboundBinding: Binding | null = null
534561
if (existing) {
535562
const rebindSpin = prompts.spinner()
536563
rebindSpin.start(`Repointing project at "${safeCreatedName}"...`)
564+
// The workspace exists on the account that was in effect a moment ago, and
565+
// its id means nothing anywhere else. Rebinding under a different account
566+
// would point this project at whatever id collides there.
567+
if (account && !(await WorkspaceApi.sameAccount(account))) {
568+
rebindSpin.stop("Could not repoint the project.", 1)
569+
prompts.log.error(
570+
`The signed-in account changed while "${safeCreatedName}" was being created, so it was ` +
571+
`not linked to this project. The workspace exists on the previous account. Re-run ` +
572+
`\`altimate-code link\` to link this project on the account you are on now.`,
573+
)
574+
process.exitCode = 1
575+
return
576+
}
537577
try {
538-
await rebindByMatchedIdentifier({
578+
const res = await rebindByMatchedIdentifier({
539579
identifier,
540580
targetDatamateId: created.datamate.id,
541581
expectedCurrentDatamateId: existing.datamate.id,
542582
matchedBy: existing.matchedBy,
543583
})
584+
reboundBinding = res.binding
544585
rebindSpin.stop(`Project is now linked to "${safeCreatedName}".`)
545586
} catch (err) {
546587
rebindSpin.stop("Could not repoint the project.", 1)
@@ -554,20 +595,24 @@ async function createThenBindOrRebind(
554595
// Prefer the canonicalized ``identifier.projectPath`` over the raw
555596
// ``--directory`` argument so ``altimate-code link -d ./myproj`` and its
556597
// symlink-resolved twin both write under the same cache key (Kilo cycle 6).
557-
// The unbound path has no server binding row to echo, so fall back to the
558-
// identifier we just rebound on — the same values the rebind wrote.
598+
// Whichever call last wrote the row is what gets cached. `createAndBind`
599+
// returns it directly; the unbound path gets it from the rebind. Caching the
600+
// local identifiers instead would record fields the server never stored — a
601+
// path-keyed row rebound through `/by-path` would be cached carrying a
602+
// `repo_remote` that is not on the server's row. (review, PR #1314)
603+
const serverBinding = created.via === "bound" ? created.binding : reboundBinding
559604
await recordApprovedBinding(identifier.projectPath ?? directory, {
560605
datamateId: created.datamate.id,
561606
datamateName: created.datamate.name,
562-
repoRemote: created.binding?.repo_remote ?? identifier.repoRemote ?? null,
563-
projectPath: created.binding?.project_path ?? identifier.projectPath ?? null,
607+
repoRemote: serverBinding?.repo_remote ?? identifier.repoRemote ?? null,
608+
projectPath: serverBinding?.project_path ?? identifier.projectPath ?? null,
564609
linkedAt: Date.now(),
565610
}, { awaitBackfill: true })
566611
prompts.log.info("Saved memory blocks will sync to this workspace if memory is enabled for it.")
567612
// ``createAndBind`` hands back a manage_url; the unbound create does not, so
568613
// derive it from credentials exactly as the rest of this file does. Null on
569614
// BYOK / unresolvable deployments — then there is simply nothing to show.
570-
const manageUrl = created.manage_url ?? (await manageUrlFor(created.datamate.id))
615+
const manageUrl = created.via === "bound" ? created.manage_url : await manageUrlFor(created.datamate.id)
571616
if (manageUrl) {
572617
prompts.log.info(`Manage it at: ${manageUrl}`)
573618
// Guard against a server that hands back a non-http(s) manage_url — ``open``

‎packages/opencode/src/plugin/tui/altimate/workspace.tsx‎

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
NotFoundError,
3838
PreconditionFailedError,
3939
WorkspaceApi,
40+
type Binding,
4041
type DatamateRef,
4142
type MatchedIdentifier,
4243
type ProjectBindingLookup,
@@ -493,22 +494,48 @@ function toastHandoffFailure(api: TuiPluginApi, result: Extract<HandoffResult, {
493494
}
494495
}
495496

496-
async function createAndBindInline(
497+
/** Exported for tests — see `createThenBindOrRebind`. This is the TUI's copy of
498+
* the same flow, and it carried the same bug. */
499+
export async function createAndBindInline(
497500
api: TuiPluginApi,
498501
identifier: ProjectIdentifier,
499502
name: string,
500-
/** When present, this project is already bound to another workspace.
501-
* createAndBind succeeds but leaves the binding pointing at the OLD
502-
* workspace; without this rebind step the new workspace is an orphaned
503-
* (billable) SaaS resource the CLI knows nothing about (M2). */
503+
/** When present, this project is already bound to another workspace — which
504+
* changes WHICH create runs, not just whether a rebind follows. See the note
505+
* in the body: the atomic create-and-bind cannot be used here, because the
506+
* server refuses it before creating anything. Without the rebind that follows
507+
* the unbound create, the new workspace is an orphaned (billable) SaaS
508+
* resource the CLI knows nothing about (M2). */
504509
rebindFrom?: { expectedCurrentDatamateId: number; matchedBy: MatchedIdentifier },
505510
): Promise<void> {
506511
api.ui.dialog.clear()
507-
let res: Awaited<ReturnType<typeof WorkspaceApi.createAndBind>>
512+
// The same split the CLI makes in `cli/cmd/link.ts` (AI-9171), for the same
513+
// reason. `createAndBind` pre-checks the project identifiers server-side and
514+
// 409s BEFORE creating anything, so on an already-linked project the catch
515+
// below fired and the rebind further down was unreachable — this row never
516+
// worked. The `rebindFrom` comment above described the opposite ("creates and
517+
// binds, leaving the binding pointing at the OLD workspace"); that was the
518+
// assumption the bug rested on. Create unbound first, then repoint.
519+
type Created =
520+
| { via: "bound"; datamate: DatamateRef; binding: Binding }
521+
| { via: "unbound"; datamate: DatamateRef }
522+
let res: Created
523+
// Captured before the create and re-checked before the rebind: the two
524+
// requests resolve credentials independently, and a workspace id means
525+
// nothing on a different account.
526+
const account = await WorkspaceApi.accountFingerprint().catch(() => null)
508527
try {
509-
res = await WorkspaceApi.createAndBind({ name, identifier })
528+
if (rebindFrom) {
529+
const ws = await WorkspaceApi.createWorkspaceUnbound({ name })
530+
res = { via: "unbound", datamate: ws }
531+
} else {
532+
const created = await WorkspaceApi.createAndBind({ name, identifier })
533+
res = { via: "bound", datamate: created.datamate, binding: created.binding }
534+
}
510535
} catch (err) {
511-
if (err instanceof ConflictError) {
536+
// Only the bound path sends identifiers, so only it can lose an identity
537+
// race. The unbound create sends none.
538+
if (err instanceof ConflictError && !rebindFrom) {
512539
api.ui.toast({
513540
variant: "warning",
514541
message: `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.`,
@@ -522,19 +549,27 @@ async function createAndBindInline(
522549
return
523550
}
524551

552+
let reboundBinding: Binding | null = null
525553
if (rebindFrom) {
526-
// The atomic create-and-bind wrote a NEW binding for the new workspace,
527-
// but the existing binding for THIS project's remote/path still points
528-
// at the old workspace. Repoint via the matched-identifier rebind
529-
// endpoint. If rebind fails, tell the user the workspace exists but
530-
// the link didn't switch — do not silently orphan.
554+
// The workspace above was created UNBOUND, so this project's binding still
555+
// points at the old one. Repoint it. If this fails the workspace exists but
556+
// the link did not switch — say so rather than silently orphan it.
557+
if (account && !(await WorkspaceApi.sameAccount(account))) {
558+
api.ui.toast({
559+
variant: "error",
560+
message: `The signed-in account changed while "${res.datamate.name}" was being created, so it was not linked to this project. The workspace exists on the previous account.`,
561+
duration: 15_000,
562+
})
563+
return
564+
}
531565
try {
532-
await rebindByMatchedIdentifier({
566+
const rebound = await rebindByMatchedIdentifier({
533567
identifier,
534568
targetDatamateId: res.datamate.id,
535569
expectedCurrentDatamateId: rebindFrom.expectedCurrentDatamateId,
536570
matchedBy: rebindFrom.matchedBy,
537571
})
572+
reboundBinding = rebound.binding
538573
} catch (err) {
539574
api.ui.toast({
540575
variant: "error",
@@ -545,6 +580,10 @@ async function createAndBindInline(
545580
}
546581
}
547582

583+
// Whichever call actually wrote the server row: the atomic create returns it,
584+
// the unbound path gets it from the rebind.
585+
const serverBinding = res.via === "bound" ? res.binding : reboundBinding
586+
548587
// Post-success tail — this function is invoked fire-and-forget
549588
// (``void createAndBindInline(...)``), so a bare rejection here would
550589
// surface as an unhandled promise and terminate the TUI. Contain the
@@ -557,8 +596,8 @@ async function createAndBindInline(
557596
await recordApprovedBinding(api.state.path.directory, {
558597
datamateId: res.datamate.id,
559598
datamateName: res.datamate.name,
560-
repoRemote: res.binding.repo_remote,
561-
projectPath: res.binding.project_path,
599+
repoRemote: serverBinding?.repo_remote ?? identifier.repoRemote ?? null,
600+
projectPath: serverBinding?.project_path ?? identifier.projectPath ?? null,
562601
linkedAt: Date.now(),
563602
})
564603
await showLinkedConfirmation(api, "Created", res.datamate.id, res.datamate.name)

0 commit comments

Comments
 (0)