Skip to content

Commit 5ac0744

Browse files
fix: keep the answered status on a failed link; check the created id inside the attempt
A body that fails after the server answered now throws with that status, so the link failure is not classed as network; a create whose id is unusable is a failed link step, not a created workspace. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE
1 parent b3c9f90 commit 5ac0744

2 files changed

Lines changed: 37 additions & 20 deletions

File tree

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

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,9 @@ export class WorkspaceApiError extends Error {
154154
constructor(
155155
msg: string,
156156
public readonly status?: number,
157+
/** Where it failed: on the wire before any answer, or in an answer the server gave (its
158+
* status, when known, is `status`). A statusless error is transport unless said otherwise. */
159+
public readonly failure: "transport" | "response" = status === undefined ? "transport" : "response",
157160
) {
158161
super(msg)
159162
this.name = "WorkspaceApiError"
@@ -263,7 +266,7 @@ export function linkFailureReason(err: unknown): "auth" | "not_found" | "network
263266
if (err instanceof ConflictError || err instanceof PreconditionFailedError) return "conflict"
264267
if (err instanceof WorkspaceApiError) {
265268
if (err.status === 401) return "auth"
266-
if (err.status === undefined) return "network" // unreachable or timed out: req() sets no status
269+
if (err.status === undefined && err.failure === "transport") return "network" // unreachable or timed out
267270
}
268271
return "other"
269272
}
@@ -415,7 +418,9 @@ async function req<T>(
415418
kind: answered === undefined ? "timeout" : answered >= 500 ? "5xx" : answered >= 400 ? "4xx" : "timeout",
416419
workspaceId: bodyWorkspaceId,
417420
})
418-
throw new WorkspaceApiError(`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`)
421+
// The answer's status rides on the error too, so a link failure after an answer is not
422+
// classified as a network failure.
423+
throw new WorkspaceApiError(`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`, answered)
419424
}
420425
// The server answered and the body failed afterwards (readBounded's cap, a cut stream):
421426
// classify by the status it answered with, so an oversized 500 is still a 5xx row; only a
@@ -431,6 +436,7 @@ async function req<T>(
431436
reportApiError({ endpoint, kind: "network", workspaceId: bodyWorkspaceId })
432437
}
433438
const msg = err instanceof Error ? err.message : String(err)
439+
if (answered !== undefined) throw new WorkspaceApiError(`Response from ${target} failed: ${msg}`, answered)
434440
throw new WorkspaceApiError(`Cannot reach ${target}: ${msg}`)
435441
} finally {
436442
clearTimeout(timeout)
@@ -695,8 +701,10 @@ export namespace WorkspaceApi {
695701
name: string
696702
description?: string
697703
}): Promise<{ id: number; name: string }> {
698-
const data = await linkAttempt("create_unbound", undefined, () =>
699-
req<{ id: number }>("POST", "/", {
704+
// The id check sits inside the reported attempt: a create whose answer is unusable is a
705+
// failed link step, not a created workspace.
706+
const id = await linkAttempt("create_unbound", undefined, async () => {
707+
const data = await req<{ id: number }>("POST", "/", {
700708
base: "/datamates",
701709
body: {
702710
name: input.name,
@@ -706,21 +714,24 @@ export namespace WorkspaceApi {
706714
knowledge_engine_enabled: true,
707715
privacy: "private",
708716
},
709-
}),
710-
)
711-
// `typeof` FIRST, before any arithmetic. `Number()` coerces, so the
712-
// previous `Number.isSafeInteger(Number(data?.id))` accepted `true` as 1,
713-
// `"7"` as 7 and `[5]` as 5 — a malformed body would have rebound the
714-
// project to whatever those coerced to (workspace 1, in the boolean case)
715-
// instead of failing. The server's `CreateDatamateResponse` is `{id: int}`
716-
// and FastAPI enforces it, so anything else here is a contract break worth
717-
// refusing loudly rather than guessing at.
718-
const id: unknown = (data as { id?: unknown } | null | undefined)?.id
719-
if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) {
720-
throw new WorkspaceApiError(
721-
`Workspace was created but the server returned no usable id (${JSON.stringify(id) ?? "undefined"}).`,
722-
)
723-
}
717+
})
718+
// `typeof` FIRST, before any arithmetic. `Number()` coerces, so the
719+
// previous `Number.isSafeInteger(Number(data?.id))` accepted `true` as 1,
720+
// `"7"` as 7 and `[5]` as 5 — a malformed body would have rebound the
721+
// project to whatever those coerced to (workspace 1, in the boolean case)
722+
// instead of failing. The server's `CreateDatamateResponse` is `{id: int}`
723+
// and FastAPI enforces it, so anything else here is a contract break worth
724+
// refusing loudly rather than guessing at.
725+
const id: unknown = (data as { id?: unknown } | null | undefined)?.id
726+
if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) {
727+
throw new WorkspaceApiError(
728+
`Workspace was created but the server returned no usable id (${JSON.stringify(id) ?? "undefined"}).`,
729+
undefined,
730+
"response",
731+
)
732+
}
733+
return id
734+
})
724735
// The create-then-rebind path for an already-linked project: the workspace exists
725736
// from here; the rebind that follows reports the switch and the link.
726737
Telemetry.track({

‎packages/opencode/test/altimate/workspace/link-telemetry.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ describe("workspace link telemetry", () => {
113113
replies = [{ status: 200, body: { id: "7" } }] // malformed id: refused, and not reported as created
114114
await expect(WorkspaceApi.createWorkspaceUnbound({ name: "x" })).rejects.toThrow(/no usable id/)
115115
expect(of("workspace_created")).toHaveLength(0)
116+
// ...but it is a failed link step: the answer was unusable, which is not a network failure.
117+
expect(of("workspace_link_failed")).toEqual([expect.objectContaining({ how: "create_unbound", reason: "other" })])
116118

117119
events = []
118120
replies = [{ status: 409, body: { detail: { message: "name taken" } } }]
@@ -259,7 +261,11 @@ describe("workspace link telemetry", () => {
259261
}),
260262
{ status: 500 },
261263
)) as typeof globalThis.fetch
262-
await expect(altimateRequest("GET", "/x", { base: "/datamates", timeoutMs: 200 })).rejects.toThrow(/timed out/)
264+
const stalled: any = await altimateRequest("GET", "/x", { base: "/datamates", timeoutMs: 200 }).catch((e) => e)
265+
expect(stalled).toBeInstanceOf(WorkspaceApiError)
266+
expect(stalled.message).toMatch(/timed out/)
267+
expect(stalled.status).toBe(500) // the answer's status rides on the error
268+
expect(linkFailureReason(stalled)).toBe("other") // answered: not a network failure
263269
expect(of("workspace_api_error")).toEqual([expect.objectContaining({ status_class: "5xx", status: 500 })])
264270

265271
events = []

0 commit comments

Comments
 (0)