Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 195 additions & 0 deletions packages/opencode/test/server/altimate-error-handlers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// 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<T>(run: () => Promise<T>) {
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
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 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()
}
}

// 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")
Comment on lines +88 to +89

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor — silence check only rejects two strings

expect(printed).not.toContain(body.data.ref)
expect(printed).not.toContain("quiet marker")

The test promises the handler prints nothing, but any other output — console.error("request failed"), a bare process.stderr.write("\n") — still passes, and that is exactly what would disturb the in-process TUI. In this middleware unit test it's safe to assert nothing was captured at all (expect(printed).toBe(""), or return the raw entries and assert an empty array). For the full-server test (154-155) keep the targeted checks, since unrelated startup output could make a blanket assertion flaky.

})

test("still gets its response when opencode.log can't be opened", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor — "or written" half of the ticket isn't covered

test("still gets its response when opencode.log can't be opened", async () => {

#1847 asks that the response still go out when opencode.log can't be opened or written. The folder trick only covers the open failure; an open that succeeds followed by a failing write (e.g. a stubbed write that rejects, or a read-only file on POSIX) has no test. Either add that case or narrow the claim in the PR description.

// 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())
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
try {
Comment on lines +96 to +98

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor — setup outside try

if (existed) await rename(logFile(), saved)
await mkdir(logFile())
try {

If mkdir throws, opencode.log stays renamed to .saved-<pid>, the finally never runs, and later tests in the process that read the log fail with a confusing ENOENT. Move the mkdir (and the rename) inside the try, and guard the restore so it only renames back when the stash actually happened (e.g. track a stashed flag set after a successful rename).

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 replaced = false
let servers: Array<{ stop: (force?: boolean) => unknown }> = []

afterEach(async () => {
for (const server of servers) await server.stop(true)
servers = []
// 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()
})

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)
replaced = true
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)
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
expect(printed).not.toContain("failed to decode")
})

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
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor — Windows skip reports as a pass

if (process.platform === "win32") return // the busy window is a POSIX `sleep` in the session's shell

The early return makes this show up as a passing test on Windows, so the busy branch looks covered when it never ran. Use test.skipIf(process.platform === "win32")("a busy session answers 400 with its message", async () => { … }, 30_000).

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(
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
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++) {
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
await Bun.sleep(50)
response = await removeMessage()
}
expect(response.status).toBe(400)
Comment on lines +182 to +186

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor — opaque failure when the setup fails

for (let attempt = 0; response.status !== 400 && attempt < 40; attempt++) {
  await Bun.sleep(50)
  response = await removeMessage()
}
expect(response.status).toBe(400)

The test depends on the shell route marking the session busy before it validates providerID: "none" / the agent. If that ordering changes, the session is never busy and this fails with "expected 400, received 404" without saying the shell request itself failed. When the poll runs out, await shell and include its status/body in the failure (or assert the shell request is still pending when the 400 arrives) so a setup failure reads as one.

expect(await response.json()).toEqual({
name: "UnknownError",
data: { message: `Session ${session.id} is busy` },
})
} finally {
await shell
}
}, 30_000)
})
Loading