From ab1ffee351bf5b292028791feb3368fb46967a49 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 27 Nov 2026 23:48:32 +0800 Subject: [PATCH 1/4] test: the server error handlers' log record, console silence and server.ts branches - The opencode.log record keeps stack frames and a nested cause. - Nothing is printed; a log that can't be opened still gets a response. - server.ts's unknown-error and busy branches through the full server. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- .../server/altimate-error-handlers.test.ts | 184 ++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 packages/opencode/test/server/altimate-error-handlers.test.ts diff --git a/packages/opencode/test/server/altimate-error-handlers.test.ts b/packages/opencode/test/server/altimate-error-handlers.test.ts new file mode 100644 index 0000000000..a15a72222d --- /dev/null +++ b/packages/opencode/test/server/altimate-error-handlers.test.ts @@ -0,0 +1,184 @@ +// altimate_change - new file +// +// How the server's Hono error handlers record an error they don't recognise: the full error, stack frames and nested +// causes included, in opencode.log under the ref the response carries; nothing on the console or the standard +// streams (the TUI owns them when it runs the server in-process); and a response even when opencode.log can't be +// written. Also server.ts's unknown-error and busy-session branches through the full server. +import { afterEach, describe, expect, spyOn, test } from "bun:test" +import path from "path" +import { mkdir, rename, rm, unlink } from "fs/promises" +import { Hono } from "hono" +import { Server } from "../../src/server/server" +import { errorHandler } from "../../src/server/middleware" +import { UNEXPECTED } from "../../src/altimate/server/error-response" +import { Log } from "../../src/util/log" +import { Global } from "@/global" +import { Filesystem } from "@/util/filesystem" +import { disposeAllInstances, tmpdir } from "../fixture/fixture" + +// Stack frames and source paths, as V8, JSC and Bun print them. +const STACKISH = /\n\s+at\s|\.(ts|js):\d+:\d+|node_modules/ +const logFile = () => path.join(Global.Path.log, "opencode.log") + +// Runs `run` with the print-logs flags unset, the default for `serve`. +async function withoutPrintLogs(run: () => Promise) { + const saved = [process.env["ALTIMATE_PRINT_LOGS"], process.env["OPENCODE_PRINT_LOGS"]] as const + delete process.env["ALTIMATE_PRINT_LOGS"] + delete process.env["OPENCODE_PRINT_LOGS"] + try { + return await run() + } finally { + if (saved[0] === undefined) delete process.env["ALTIMATE_PRINT_LOGS"] + else process.env["ALTIMATE_PRINT_LOGS"] = saved[0] + if (saved[1] === undefined) delete process.env["OPENCODE_PRINT_LOGS"] + else process.env["OPENCODE_PRINT_LOGS"] = saved[1] + } +} + +// Everything printed to the console or the 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(console, "warn").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() + } +} + +// The opencode.log line recorded under `ref`. +async function loggedUnder(ref: string) { + const logged = await Bun.file(logFile()).text() + return logged.split("\n").find((entry) => entry.includes(`ref=${ref}`)) +} + +function honoApp(thrown: unknown) { + return new Hono().onError(errorHandler(Log.create({ service: "test" }))).get("/boom", () => { + throw thrown + }) +} + +describe("middleware.ts errorHandler, an unknown error", () => { + test("is recorded with its stack frames and its nested cause", async () => { + const err = new Error("outer marker", { cause: new Error("inner marker") }) + const body = await withoutPrintLogs(async () => (await honoApp(err).request("/boom")).json()) + const line = await loggedUnder(body.data.ref) + expect(line).toContain("outer marker") + expect(line).toContain("inner marker") + // A frame of this file, where both errors were made. + expect(line).toMatch(/at .*altimate-error-handlers\.test\.ts:\d+/) + }) + + test("prints nothing to the console or the standard streams", async () => { + const { result: body, printed } = await withoutPrintLogs(() => + printedDuring(async () => (await honoApp(new Error("quiet marker")).request("/boom")).json()), + ) + expect(await loggedUnder(body.data.ref)).toContain("quiet marker") + expect(printed).not.toContain(body.data.ref) + expect(printed).not.toContain("quiet marker") + }) + + test("still gets its response when opencode.log can't be opened", async () => { + // A folder where the log file should be: opening it for append fails. + const saved = `${logFile()}.saved-${process.pid}` + const existed = await Filesystem.exists(logFile()) + if (existed) await rename(logFile(), saved) + await mkdir(logFile()) + try { + const response = await withoutPrintLogs(async () => honoApp(new Error("unlogged marker")).request("/boom")) + expect(response.status).toBe(500) + const body = await response.json() + expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) + expect(body.data.ref).toMatch(/^err_[0-9a-f-]{8}$/) + } finally { + await rm(logFile(), { recursive: true, force: true }) + if (existed) await rename(saved, logFile()) + } + }) +}) + +describe("server.ts handler, through the full server", () => { + const authPath = () => path.join(Global.Path.data, "auth.json") + let original: string | undefined + let servers: Array<{ stop: (force?: boolean) => unknown }> = [] + + afterEach(async () => { + for (const server of servers) await server.stop(true) + servers = [] + if (original !== undefined) await Filesystem.write(authPath(), original) + else await unlink(authPath()).catch(() => undefined) + original = undefined + await disposeAllInstances() + }) + + test("an unknown error answers the fixed message and a ref, and is recorded under it, never printed", async () => { + // A remote config that answers 200 with a body that isn't JSON: loading the config fails with a plain Error. + const remote = Bun.serve({ + port: 0, + fetch: () => new Response("{not json", { headers: { "content-type": "application/json" } }), + }) + servers.push(remote) + original = await Filesystem.readText(authPath()).catch(() => undefined) + await Filesystem.write( + authPath(), + JSON.stringify({ [remote.url.origin]: { type: "wellknown", key: "TEST_TOKEN", token: "test-token" } }), + ) + await using dir = await tmpdir({ git: true }) + const { result: response, printed } = await withoutPrintLogs(() => + printedDuring(() => Server.Default().request("/agent", { headers: { "x-opencode-directory": dir.path } })), + ) + const text = await response.text() + expect(response.status).toBe(500) + expect(text).not.toContain("failed to decode") + expect(text).not.toMatch(STACKISH) + const body = JSON.parse(text) + expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) + expect(await loggedUnder(body.data.ref)).toContain("failed to decode remote config") + expect(printed).not.toContain(body.data.ref) + }) + + test("a busy session answers 400 with its message", async () => { + if (process.platform === "win32") return // the busy window is a POSIX `sleep` in the session's shell + 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() + // The session stays busy while its shell runs the command; no model is called for a shell command. + const shell = Promise.resolve( + app.request(`/session/${session.id}/shell`, { + method: "POST", + headers, + body: JSON.stringify({ agent: "builder", model: { providerID: "none", modelID: "none" }, command: "sleep 3" }), + }), + ) + try { + // Any message id: the route checks the session first. + const removeMessage = () => + Promise.resolve( + app.request(`/session/${session.id}/message/msg_00000000000000000000000000`, { + method: "DELETE", + headers, + }), + ) + let response = await removeMessage() + for (let attempt = 0; response.status !== 400 && attempt < 40; attempt++) { + await Bun.sleep(50) + response = await removeMessage() + } + expect(response.status).toBe(400) + expect(await response.json()).toEqual({ + name: "UnknownError", + data: { message: `Session ${session.id} is busy` }, + }) + } finally { + await shell + } + }, 30_000) +}) From debb4d526cd837d5180a842f4a983b89e9788dd4 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:21:37 +0800 Subject: [PATCH 2/4] test: put `auth.json` back only after the test that replaced it The busy-session test never wrote `auth.json`, yet the shared `afterEach` deleted any file already there. Restore it only when a test replaced it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- .../test/server/altimate-error-handlers.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/opencode/test/server/altimate-error-handlers.test.ts b/packages/opencode/test/server/altimate-error-handlers.test.ts index a15a72222d..2e9d278edd 100644 --- a/packages/opencode/test/server/altimate-error-handlers.test.ts +++ b/packages/opencode/test/server/altimate-error-handlers.test.ts @@ -107,13 +107,18 @@ describe("middleware.ts errorHandler, an unknown error", () => { describe("server.ts handler, through the full server", () => { const authPath = () => path.join(Global.Path.data, "auth.json") let original: string | undefined + let replaced = false let servers: Array<{ stop: (force?: boolean) => unknown }> = [] afterEach(async () => { for (const server of servers) await server.stop(true) servers = [] - if (original !== undefined) await Filesystem.write(authPath(), original) - else await unlink(authPath()).catch(() => undefined) + // Only a test that wrote auth.json puts back what was there before it. + if (replaced) { + if (original !== undefined) await Filesystem.write(authPath(), original) + else await unlink(authPath()).catch(() => undefined) + } + replaced = false original = undefined await disposeAllInstances() }) @@ -126,6 +131,7 @@ describe("server.ts handler, through the full server", () => { }) servers.push(remote) original = await Filesystem.readText(authPath()).catch(() => undefined) + replaced = true await Filesystem.write( authPath(), JSON.stringify({ [remote.url.origin]: { type: "wellknown", key: "TEST_TOKEN", token: "test-token" } }), From 36362b7c4d5ba3049fa048d78be771ea66ed675b Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:28:58 +0800 Subject: [PATCH 3/4] test: the full-server print check also rejects the error's text Checking only for the ref let `server.ts` print the error without it. The test now also checks that nothing printed carries the error's text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvt5gnJKUdaiAK5SupM --- packages/opencode/test/server/altimate-error-handlers.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/opencode/test/server/altimate-error-handlers.test.ts b/packages/opencode/test/server/altimate-error-handlers.test.ts index 2e9d278edd..c7e7cec631 100644 --- a/packages/opencode/test/server/altimate-error-handlers.test.ts +++ b/packages/opencode/test/server/altimate-error-handlers.test.ts @@ -148,6 +148,7 @@ describe("server.ts handler, through the full server", () => { expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) expect(await loggedUnder(body.data.ref)).toContain("failed to decode remote config") expect(printed).not.toContain(body.data.ref) + expect(printed).not.toContain("failed to decode") }) test("a busy session answers 400 with its message", async () => { From 488393203f6ef671c72ba98f603da5d738facc20 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 14:40:29 +0800 Subject: [PATCH 4/4] 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-handlers.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/opencode/test/server/altimate-error-handlers.test.ts b/packages/opencode/test/server/altimate-error-handlers.test.ts index c7e7cec631..3fc79fa699 100644 --- a/packages/opencode/test/server/altimate-error-handlers.test.ts +++ b/packages/opencode/test/server/altimate-error-handlers.test.ts @@ -35,14 +35,18 @@ async function withoutPrintLogs(run: () => Promise) { } } -// Everything printed to the console or the 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), - spyOn(console, "warn").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)), ]