From a1e962a0fac83f12fc99f4e8e5f09ce86cec9496 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 27 Nov 2026 23:48:23 +0800 Subject: [PATCH 1/3] fix: server error paths that still answered an empty 500 or lost the message - An unknown /api path answers the fixed body and a ref, recorded in opencode.log, not printed. - Forwarded HttpApi routes answer an unavailable remote config 502. - prompt_async's session.error carries a NamedError's text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- .../instance/httpapi/middleware/error.ts | 34 +++-- .../opencode/src/server/routes/session.ts | 8 +- .../test/server/altimate-error-bodies.test.ts | 119 ++++++++++++++++-- 3 files changed, 146 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts index 21b53aba75..9af85c39c2 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts @@ -2,20 +2,30 @@ import { NamedError } from "@opencode-ai/core/util/error" import { ConfigErrorV1 } from "@opencode-ai/core/v1/config/error" import { Cause, Effect } from "effect" import { HttpRouter, HttpServerError, HttpServerRespondable, HttpServerResponse } from "effect/unstable/http" +// altimate_change start — the 502 and the opencode.log record the Hono handlers use +import { recordUnknownError, upstreamStatus } from "@/altimate/server/error-response" +// altimate_change end // Keep typed HttpApi failures on their declared error path; this boundary only replaces defect-only empty 500s. export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) => effect.pipe( Effect.catchCause((cause) => { - const defect = cause.reasons.filter(Cause.isDieReason).find((reason) => { - if (HttpServerResponse.isHttpServerResponse(reason.defect)) return false - if (HttpServerError.isHttpServerError(reason.defect)) return false - if (HttpServerRespondable.isRespondable(reason.defect)) return false + // altimate_change start — an undeclared failure reaches this boundary too, such as the web UI proxy's + // HttpClientError for a path no route serves (an unknown /api route): answer it as a defect is answered, not + // with an empty 500 that nothing logs. Declared HttpApi errors are responses before they get here. + const errors = cause.reasons.flatMap((reason) => + Cause.isDieReason(reason) ? [reason.defect] : Cause.isFailReason(reason) ? [reason.error] : [], + ) + const index = errors.findIndex((error) => { + if (HttpServerResponse.isHttpServerResponse(error)) return false + if (HttpServerError.isHttpServerError(error)) return false + if (HttpServerRespondable.isRespondable(error)) return false return true }) - if (!defect) return Effect.failCause(cause) + if (index === -1) return Effect.failCause(cause) - const error = defect.defect + const error = errors[index] + // altimate_change end if ( ConfigErrorV1.JsonError.isInstance(error) || ConfigErrorV1.InvalidError.isInstance(error) || @@ -24,10 +34,20 @@ export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) ) { return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status: 400 })) } + // altimate_change start — an unavailable remote config answers 502 with the remote's name and status, as the + // Hono handlers do, instead of the fixed unknown-error body + if (error instanceof NamedError) { + const status = upstreamStatus(error.name) + if (status) return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status })) + } + // altimate_change end const ref = `err_${crypto.randomUUID().slice(0, 8)}` - return Effect.logError("failed", { ref, error, cause: Cause.pretty(cause) }).pipe( + // altimate_change start — recorded under the ref in opencode.log, as the Hono handlers do: the default logger + // here prints to the console, which the in-process TUI owns, and leaves the ref in no file + return Effect.promise(() => recordUnknownError("httpapi", ref, error)).pipe( + // altimate_change end Effect.as( HttpServerResponse.jsonUnsafe( new NamedError.Unknown({ diff --git a/packages/opencode/src/server/routes/session.ts b/packages/opencode/src/server/routes/session.ts index b711dbe4d9..243e05325f 100644 --- a/packages/opencode/src/server/routes/session.ts +++ b/packages/opencode/src/server/routes/session.ts @@ -20,6 +20,9 @@ import { Log } from "../../util/log" // altimate_change start — client trace propagation import { TraceContext } from "@/altimate/observability/trace-context" // altimate_change end +// altimate_change start — client-safe error messages +import { clientMessage } from "@/altimate/server/error-response" +// altimate_change end // altimate_change start — run-scoped request interruption and effort overrides import { withBudgetControl } from "@/altimate/session/run-budget-control" import { RunBudget } from "@/altimate/run-budget" @@ -996,7 +999,10 @@ export const SessionRoutes = lazy(() => log.error("prompt_async failed", { sessionID, error: err }) Bus.publish(Session.Event.Error, { sessionID, - error: new NamedError.Unknown({ message: err instanceof Error ? err.message : String(err) }).toObject(), + // altimate_change start — as the HttpApi handler does: a NamedError's text from data.message (its own + // message is only its name), and no stack frames + error: new NamedError.Unknown({ message: clientMessage(err) }).toObject(), + // altimate_change end }) }) }) diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index b53e4d87df..8f23d8f28f 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -2,9 +2,9 @@ // // What the server's catch-all error handlers send back: never an error's text, stack or file paths, only a fixed // message and a ref (the error is logged in full under that ref). A remote config that can't be fetched answers 502 -// with its name and status. Covers server.ts's handler through the full app, middleware.ts's handler directly, and -// the shared helpers. -import { afterEach, describe, expect, test } from "bun:test" +// with its name and status. Covers server.ts's handler, the /api (HttpApi) error boundary and prompt_async's error +// event through the full app, middleware.ts's handler directly, and the shared helpers. +import { afterEach, describe, expect, spyOn, test } from "bun:test" import path from "path" import { unlink } from "fs/promises" import { Hono } from "hono" @@ -198,15 +198,21 @@ describe("full server, remote config unavailable", () => { }) }) - test("an /api route sends no stack either (an empty 500: the instance fails to load before any handler runs)", async () => { + test("a forwarded HttpApi route answers 502 too, as the Hono routes do", async () => { const remote = Bun.serve({ port: 0, fetch: () => new Response("upstream exploded", { status: 500 }) }) servers.push(remote) await withWellKnown(remote.url.origin) await using dir = await tmpdir({ git: true }) - const response = await Server.Default().request("/api/config", { headers: { "x-opencode-directory": dir.path } }) + const response = await Server.Default().request("/experimental/workspace", { + headers: { "x-opencode-directory": dir.path }, + }) const text = await response.text() - expect(response.status).toBe(500) - expect(text).toBe("") + expect(response.status).toBe(502) + expect(text).not.toMatch(STACKISH) + expect(JSON.parse(text)).toEqual({ + name: "ConfigRemoteUnavailableError", + data: { remote: `${remote.url.origin}/.well-known/opencode`, status: 500, reason: "HTTP 500" }, + }) }) test("a failing remote config URL is named by its template, never with the token filled in", async () => { @@ -252,3 +258,102 @@ describe("full server, remote config unavailable", () => { }) }) }) + +describe("full server, HttpApi error boundary", () => { + afterEach(async () => { + await disposeAllInstances() + }) + + // Everything the process prints to the console or its standard streams while `run` runs. + async function printedDuring(run: () => T | Promise) { + const printed: string[] = [] + const record = (...args: unknown[]) => void printed.push(args.map(String).join(" ")) + const spies = [ + spyOn(console, "log").mockImplementation(record), + spyOn(console, "error").mockImplementation(record), + spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => (record(chunk), true)), + spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => (record(chunk), true)), + ] + try { + return { result: await run(), printed: printed.join("\n") } + } finally { + for (const spy of spies) spy.mockRestore() + } + } + + test("an /api path no route serves answers the fixed message and a ref, recorded only in opencode.log", async () => { + // /api/config is not an /api route: it falls through to the web UI proxy, whose fetch fails. + await using dir = await tmpdir({ git: true }) + const { result: response, printed } = await printedDuring(() => + Server.Default().request("/api/config", { headers: { "x-opencode-directory": dir.path } }), + ) + const text = await response.text() + expect(response.status).toBe(500) + expect(text).not.toMatch(STACKISH) + const body = JSON.parse(text) + expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) + expect(body.data.ref).toMatch(/^err_[0-9a-f-]{8}$/) + const logged = await Bun.file(path.join(Global.Path.log, "opencode.log")).text() + const line = logged.split("\n").find((entry) => entry.includes(`ref=${body.data.ref}`)) + expect(line).toContain("level=ERROR") + expect(line).toContain("service=httpapi") + expect(printed).not.toContain(body.data.ref) + }) + + test("a declared HttpApi error keeps its own status and body", async () => { + await using dir = await tmpdir({ git: true }) + const response = await Server.Default().request("/api/session/ses_nope", { + headers: { "x-opencode-directory": dir.path }, + }) + expect(response.status).toBe(404) + expect(await response.json()).toMatchObject({ _tag: "SessionNotFoundError", sessionID: "ses_nope" }) + }) +}) + +describe("full server, prompt_async", () => { + afterEach(async () => { + await disposeAllInstances() + }) + + // Reads the server's event stream until a session.error event for the session arrives. + async function sessionError(events: Response, sessionID: string, timeoutMs = 15_000) { + const reader = events.body!.getReader() + const decoder = new TextDecoder() + const timeout = setTimeout(() => reader.cancel(), timeoutMs) + let buffered = "" + try { + while (true) { + const { value, done } = await reader.read() + if (done) return undefined + buffered += decoder.decode(value, { stream: true }) + for (const line of buffered.split("\n")) { + if (!line.startsWith("data: ")) continue + const event = JSON.parse(line.slice("data: ".length)) + if (event.type === "session.error" && event.properties.sessionID === sessionID) return event.properties + } + buffered = buffered.slice(buffered.lastIndexOf("\n") + 1) + } + } finally { + clearTimeout(timeout) + await reader.cancel().catch(() => undefined) + } + } + + test("a prompt that fails publishes its NamedError's text, not its name", async () => { + await using dir = await tmpdir({ git: true }) + const app = Server.Default() + const headers = { "x-opencode-directory": dir.path, "content-type": "application/json" } + const session = await (await app.request("/session", { method: "POST", headers, body: "{}" })).json() + const events = await app.request("/event", { headers }) + const response = await app.request(`/session/${session.id}/prompt_async`, { + method: "POST", + headers, + body: JSON.stringify({ agent: "no-such-agent", parts: [{ type: "text", text: "hi" }] }), + }) + expect(response.status).toBe(204) + const error = await sessionError(events, session.id) + expect(error?.error.name).toBe("UnknownError") + expect(error?.error.data.message).toStartWith('Agent not found: "no-such-agent".') + expect(error?.error.data.message).not.toMatch(STACKISH) + }, 30_000) +}) From 0ad36ed62668e3997dfbce67caf395d981635d3d Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:28:17 +0800 Subject: [PATCH 2/3] test: the `/api` print check also rejects the error's text Checking only for the ref let the middleware print the error without it. The test now also checks the log line names `HttpClientError` and that nothing printed does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- packages/opencode/test/server/altimate-error-bodies.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index 8f23d8f28f..72657a0bfc 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -297,7 +297,9 @@ describe("full server, HttpApi error boundary", () => { const line = logged.split("\n").find((entry) => entry.includes(`ref=${body.data.ref}`)) expect(line).toContain("level=ERROR") expect(line).toContain("service=httpapi") + expect(line).toContain("HttpClientError") expect(printed).not.toContain(body.data.ref) + expect(printed).not.toContain("HttpClientError") }) test("a declared HttpApi error keeps its own status and body", async () => { From 5a153d4c1ad5519c1c46a692d767faf0e68f54e8 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:39:47 +0800 Subject: [PATCH 3/3] test: the print checks watch every console method Bun's `console.info` and `console.debug` don't go through `process.stdout.write`, so the checks missed them. The helper now spies every console method, records objects as Bun prints them and decodes byte chunks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- .../test/server/altimate-error-bodies.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index 72657a0bfc..396537515d 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -264,13 +264,18 @@ describe("full server, HttpApi error boundary", () => { await disposeAllInstances() }) - // Everything the process prints to the console or its standard streams while `run` runs. + // Everything printed while `run` runs, through any console method (Bun's console.info and console.debug don't go + // through process.stdout.write) or either standard stream's write. Objects are recorded as Bun prints them. async function printedDuring(run: () => T | Promise) { const printed: string[] = [] - const record = (...args: unknown[]) => void printed.push(args.map(String).join(" ")) + const text = (arg: unknown) => + typeof arg === "string" ? arg : arg instanceof Uint8Array ? new TextDecoder().decode(arg) : Bun.inspect(arg) + const record = (...args: unknown[]) => void printed.push(args.map(text).join(" ")) + const methods = Object.keys(console).filter( + (key) => key !== "Console" && typeof Reflect.get(console, key) === "function", + ) const spies = [ - spyOn(console, "log").mockImplementation(record), - spyOn(console, "error").mockImplementation(record), + ...methods.map((method) => spyOn(console, method as "log").mockImplementation(record)), spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => (record(chunk), true)), spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => (record(chunk), true)), ]