Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
// altimate_change end

// Keep typed HttpApi failures on their declared error path; this boundary only replaces defect-only empty 500s.
Comment thread
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) => {
Comment thread
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) ||
Expand All @@ -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(

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 — log record loses the rest of the cause

return Effect.promise(() => recordUnknownError("httpapi", ref, error)).pipe(

The previous line logged Cause.pretty(cause) from the request fiber. Now only the one selected reason is recorded (wrapped as Cause.die(error) and run in a separate Effect.runPromise), so any other reasons in the cause (parallel failures, a finalizer error) and the fiber's spans/annotations are dropped, and a typed failure is logged as if it were a defect. Consider letting recordUnknownError take the full cause (optional param) and log Cause.pretty(cause); annotating the request method/path would also make a ref easier to trace back to a request.

// altimate_change end
Effect.as(
HttpServerResponse.jsonUnsafe(
new NamedError.Unknown({
Expand Down
8 changes: 7 additions & 1 deletion packages/opencode/src/server/routes/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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(),

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 — some NamedErrors still publish only their name

error: new NamedError.Unknown({ message: clientMessage(err) }).toObject(),

clientMessage only finds a NamedError's text in data.message. A NamedError whose data has no message — e.g. Provider.ModelNotFoundError ({ providerID, modelID, suggestions }) for an unknown model — still produces session.error with message: "ProviderModelNotFoundError", which is the symptom #1846 describes. The typed handler has the same gap, so this isn't a regression. Either publish the NamedError's own toObject() when it is one, or at least list this case under the PR's Limits (a generic summary of arbitrary data risks leaking fields, so a deliberate formatter is preferable to stringifying it).

// altimate_change end
})
})
})
Expand Down
126 changes: 119 additions & 7 deletions packages/opencode/test/server/altimate-error-bodies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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.

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 — 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 (UI_UPSTREAM in src/server/shared/ui.ts) fails to resolve/connect. If that host comes up, or a resolver/proxy answers for it, the proxy forwards its status and the test fails; in a build with an embedded UI the path isn't exercised at all, and DNS timing can eat the timeout. Please make the failure deterministic — inject a failing HttpClient layer or point the upstream at a closed loopback port (the httpapi-ui.test.ts fixtures already do client injection), or add a direct errorLayer unit test with a route that fails with HttpClientError.

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))
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
Comment on lines +336 to +338

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 — 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 \n. When an SSE chunk is split mid-event and that fragment starts with data: , JSON.parse throws and the test fails intermittently. Split off the remainder first and only parse complete lines, e.g. const lines = buffered.split("\n"); buffered = lines.pop() ?? ""; for (const line of lines) ….

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)
})
Loading