Repository navigation
fix: server error paths that still answered an empty 500 or lost the message #1848
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
ralphstodomingo marked this conversation as resolved.
Resolved
|
||
| 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) => { | ||
|
ralphstodomingo marked this conversation as resolved.
Resolved
|
||
| 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( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor — log record loses the rest of the cause return Effect.promise(() => recordUnknownError("httpapi", ref, error)).pipe(The previous line logged |
||
| // altimate_change end | ||
| Effect.as( | ||
| HttpServerResponse.jsonUnsafe( | ||
| new NamedError.Unknown({ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor — some NamedErrors still publish only their name error: new NamedError.Unknown({ message: clientMessage(err) }).toObject(),
|
||
| // altimate_change end | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,109 @@ describe("full server, remote config unavailable", () => { | |
| }) | ||
| }) | ||
| }) | ||
|
|
||
| describe("full server, HttpApi error boundary", () => { | ||
| afterEach(async () => { | ||
| await disposeAllInstances() | ||
| }) | ||
|
|
||
| // 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<T>(run: () => T | Promise<T>) { | ||
| const printed: string[] = [] | ||
| 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 = [ | ||
| ...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)), | ||
| ] | ||
| 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. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor — network-dependent test // /api/config is not an /api route: it falls through to the web UI proxy, whose fetch fails.This only passes while the hosted UI upstream ( |
||
| 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(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 () => { | ||
| 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)) | ||
|
ralphstodomingo marked this conversation as resolved.
Resolved
Comment on lines
+336
to
+338
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor — flaky SSE parsing for (const line of buffered.split("\n")) {
if (!line.startsWith("data: ")) continue
const event = JSON.parse(line.slice("data: ".length))This loop also parses the trailing fragment after the last |
||
| 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) | ||
| }) | ||
Uh oh!
There was an error while loading. Please reload this page.