Skip to content

Commit d011067

Browse files
committed
fix(workspace): review round — cache key, AbortSignal, isSafeInteger, migrate wrap, test isolation
Five findings on #1100: 1. link.ts:257 — Browser-flow recordApprovedBinding now caches under `identifier.projectPath ?? directory`, matching the other two call sites (lines 377 and 496). Otherwise `altimate-code link -d ./myproj` writes under a different key than the canonical form and the TUI sidebar can miss it. (coderabbitai #1100 comment 3841173342.) 2. workspace.tsx runBrowserHandoff — Module-level AbortController for the active handoff, aborted + replaced when a new one starts. Without this, an abandoned handoff kept its loopback listener bound for the full 15-minute callback window. Threaded through as the `signal` arg openWorkspaceBrowserHandoff already accepts. (coderabbitai #1100 review 5005112438.) 3. browser-handoff.test.ts — `isolateWebUrlOverride()` helper wired into all three describes (resolveWorkspaceWebUrl, runHandoffWithOpener end-to-end, port walk). Saves/restores ALTIMATE_WORKSPACE_WEB_URL around every test so a shell or CI env with the override set can't silently break the assertions. (coderabbitai #1100 review 5005112438.) 4. browser-handoff.ts:285 — Number.isSafeInteger, not isInteger. A workspace_id above 2^53 would round on `Number(...)` and still pass the isInteger guard, so the CLI could bind to a different workspace than the SaaS created. Unreachable today (auto-increment IDs stay well below the safe range) but a one-word hardening. (kilo-code-bot #1100 comment 3841208550.) 5. state.ts migrateToCanonicalKeys — Wrap the migration writeCache in try/catch. Without it, a read-only state dir or full disk raised a spurious "Workspace setup failed" toast from the offline-fallback readLocalBinding path, even though the binding was perfectly readable. The migrated shape is still returned in-memory; the next successful recordApprovedBinding persists the canonical form. (kilo-code-bot #1100 comment 3841208552.)
1 parent a6f592b commit d011067

5 files changed

Lines changed: 59 additions & 4 deletions

File tree

‎packages/opencode/src/altimate/workspace/browser-handoff.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,13 @@ async function startListener(pending: HandoffPending): Promise<{ server: Server;
283283
return
284284
}
285285
const workspaceId = Number(workspaceIdRaw)
286-
if (!Number.isInteger(workspaceId) || workspaceId <= 0) {
286+
// isSafeInteger, not isInteger: ``Number("9007199254740993")`` rounds
287+
// to ``9007199254740992``, which passes ``isInteger`` and is still
288+
// positive — the CLI would then bind to a different workspace than
289+
// the SaaS actually created. Unreachable today (auto-increment IDs
290+
// stay far below 2^53) but a one-word hardening. (kilo-code-bot #1100
291+
// comment 3841208550.)
292+
if (!Number.isSafeInteger(workspaceId) || workspaceId <= 0) {
287293
const msg = `Invalid workspace_id: ${workspaceIdRaw}`
288294
respond(400, htmlError(msg))
289295
pending.reject(markReason(new Error(msg), "error"))

‎packages/opencode/src/altimate/workspace/state.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,20 @@ function migrateToCanonicalKeys(cache: CacheFile): CacheFile {
113113
if (!existing || existing.linkedAt <= v.linkedAt) migrated[canon] = v
114114
}
115115
const next: CacheFile = { ...cache, bindings: migrated }
116-
writeCache(next)
116+
// Best-effort — a failing write (read-only state dir, full disk, EACCES)
117+
// must not throw out of ``readLocalBinding``. The migrated shape is
118+
// still returned in-memory for THIS call, and the next successful
119+
// ``recordApprovedBinding`` will persist the canonical form. Without
120+
// this wrap, the offline-fallback path (``workspace.tsx`` runFlow →
121+
// readLocalBinding) surfaces a "Workspace setup failed" toast for a
122+
// perfectly-readable binding. (kilo-code-bot #1100 comment 3841208552.)
123+
try {
124+
writeCache(next)
125+
} catch (err) {
126+
log.warn("could not persist canonical-key migration; retry on next write", {
127+
err: String(err),
128+
})
129+
}
117130
return next
118131
}
119132

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,13 @@ async function runBrowserHandoff(
248248
bindSpin.start("Linking workspace...")
249249
try {
250250
const res = await WorkspaceApi.bindExisting(result.workspaceId, identifier)
251-
await recordApprovedBinding(directory, {
251+
// Match the two other recordApprovedBinding call sites in this file
252+
// (lines 377 and 496) which cache under ``identifier.projectPath ??
253+
// directory``. The raw ``directory`` here caches under a different key
254+
// when the caller passes a relative or symlinked ``-d`` path, so a
255+
// later readLocalBinding from the TUI sidebar can miss the binding.
256+
// (coderabbitai #1100 comment 3841173342.)
257+
await recordApprovedBinding(identifier.projectPath ?? directory, {
252258
datamateId: res.binding.datamate_id,
253259
datamateName: res.binding.datamate_name,
254260
repoRemote: res.binding.repo_remote,

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,12 @@ async function showLinkedConfirmation(
322322
))
323323
}
324324

325+
/** Held across ``runBrowserHandoff`` invocations so a second handoff can
326+
* supersede a still-open first one — otherwise the first loopback listener
327+
* stays bound for its full 15-minute callback window and the second flow
328+
* walks past its port. (coderabbitai #1100 review 5005112438.) */
329+
let activeHandoffAbort: AbortController | null = null
330+
325331
/** Post-scan / on-demand browser-handoff runner. Opens the SaaS approval
326332
* modal, waits for the callback, and binds the current project to the
327333
* returned workspace via the existing ``POST /bind`` endpoint. Every failure
@@ -337,7 +343,11 @@ async function runBrowserHandoff(
337343
variant: "info",
338344
message: "Opening browser to set up your workspace — approve there, then check back here for the confirmation.",
339345
})
340-
const result: HandoffResult = await openWorkspaceBrowserHandoff({ identifier, projectName })
346+
// Supersede any still-open handoff before starting a new one.
347+
if (activeHandoffAbort) activeHandoffAbort.abort()
348+
activeHandoffAbort = new AbortController()
349+
const signal = activeHandoffAbort.signal
350+
const result: HandoffResult = await openWorkspaceBrowserHandoff({ identifier, projectName, signal })
341351
if (!result.ok) {
342352
toastHandoffFailure(api, result)
343353
return

‎packages/opencode/test/altimate/workspace/browser-handoff.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,25 @@ async function fireCallback(redirect: string, params: Record<string, string>): P
6464
// resolveWorkspaceWebUrl — the deployment-support gate
6565
// ─────────────────────────────────────────────────────────────────────────────
6666

67+
// ``ALTIMATE_WORKSPACE_WEB_URL`` short-circuits resolveWorkspaceWebUrl and
68+
// re-routes the loopback callback base URL. Devs set it for local testing,
69+
// and CI shells sometimes carry it too. Save/restore around every test so
70+
// the assertions below aren't at the mercy of the surrounding environment.
71+
// (coderabbitai #1100 review 5005112438.)
72+
function isolateWebUrlOverride() {
73+
let saved: string | undefined
74+
beforeEach(() => {
75+
saved = process.env["ALTIMATE_WORKSPACE_WEB_URL"]
76+
delete process.env["ALTIMATE_WORKSPACE_WEB_URL"]
77+
})
78+
afterEach(() => {
79+
if (saved === undefined) delete process.env["ALTIMATE_WORKSPACE_WEB_URL"]
80+
else process.env["ALTIMATE_WORKSPACE_WEB_URL"] = saved
81+
})
82+
}
83+
6784
describe("resolveWorkspaceWebUrl", () => {
85+
isolateWebUrlOverride()
6886
test("freemium API host resolves to <tenant>.ws.myaltimate.com", () => {
6987
const url = resolveWorkspaceWebUrl("https://api.myaltimate.com", "acme")
7088
expect(url).not.toBeNull()
@@ -119,6 +137,7 @@ describe("openWorkspaceBrowserHandoff pre-flight", () => {
119137
// ─────────────────────────────────────────────────────────────────────────────
120138

121139
describe("runHandoffWithOpener end-to-end", () => {
140+
isolateWebUrlOverride()
122141
beforeEach(() => stubCreds("acme", "https://api.myaltimate.com"))
123142
afterEach(() => unstubCreds())
124143

@@ -274,6 +293,7 @@ describe("runHandoffWithOpener end-to-end", () => {
274293
// ─────────────────────────────────────────────────────────────────────────────
275294

276295
describe("port walk", () => {
296+
isolateWebUrlOverride()
277297
beforeEach(() => stubCreds("acme", "https://api.myaltimate.com"))
278298
afterEach(() => unstubCreds())
279299

0 commit comments

Comments
 (0)