diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b92f011..7b928b681 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements - On phones, the top bar's **⋯** menu no longer repeats the session name already shown in the title, and its theme and language pickers open fully instead of being cut off at the bar's edge. +- omp-web no longer exits when a browser disconnects in the middle of a POST request, for example when a tab closes while a request is still in flight. A Next.js bug (vercel/next.js#99278) could turn that disconnect into an uncaught `Error: aborted`, which the crash handler treated as fatal. These disconnects are now logged to `diagnostics.log` as `client-abort` and the server keeps running; every other uncaught error still exits. +- When `PI_CODING_AGENT_DIR` points away from `~/.omp/agent`, the crash journal (`diagnostics.log`) is written to `/omp-web/` instead of `~/.omp/omp-web/`, so isolated test and development servers no longer write to the real journal. - Keep **Collapse input** available after expanding a long user message with **Show full input**, so the message can be collapsed again. - Agent host tools (`open_url`, `notify`, `open_file`) no longer fail when you switch to another session mid-run. Any open omp-web tab now answers them, and a URL or file from a session you are not viewing opens only after you confirm it in a dialog. - Ask before opening links from the agent. Turn on **Open agent links without asking** in Settings → Interface & Behavior to open links from the session you are viewing right away; links from other sessions always ask. diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 8399eaf99..679ff5d26 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -1,6 +1,6 @@ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs"; import { join } from "path"; -import { getConfigRoot } from "@/lib/omp/paths"; +import { getDiagnosticsDir } from "@/lib/omp/paths"; export async function register(): Promise { // Honor HTTP(S)_PROXY/NO_PROXY for server-side fetch (update checks, skill @@ -60,8 +60,9 @@ export async function register(): Promise { // are killed with their terminal; pages then show endless loading until the // process is restarted). Append fatal errors and event-loop stalls to a file // so the next incident explains itself. Node's default crash semantics are - // preserved — this only adds the record before exiting. - const logDir = join(getConfigRoot(), "omp-web"); + // preserved — this only adds the record before exiting — except for client + // aborts, which are journaled and survived (see below). + const logDir = getDiagnosticsDir(); const logPath = join(logDir, "diagnostics.log"); const appendDiag = (kind: string, detail: string) => { try { @@ -74,6 +75,17 @@ export async function register(): Promise { }; const describe = (value: unknown) => (value instanceof Error ? `${value.name}: ${value.message}\n${value.stack ?? ""}` : String(value)); process.on("uncaughtException", (error) => { + // A client disconnecting mid-request can surface here as an unhandled + // `Error: aborted` (ECONNRESET): for POSTs through proxy.ts, Next's body + // cloning drops the request's `error` listeners (replaceRequestBody, + // vercel/next.js#99278). That is a peer event, not a corrupted server: + // journal it (one line, no stack, so aborts cannot rotate real crash + // records out of the journal quickly) and keep serving, as Next's own + // handler does. + if (error instanceof Error && error.message === "aborted" && (error as NodeJS.ErrnoException).code === "ECONNRESET") { + appendDiag("client-abort", "uncaughtException Error: aborted (ECONNRESET)"); + return; + } appendDiag("crash", `uncaughtException ${describe(error)}`); // An uncaughtException listener suppresses Node's default exit; keep the // crash-visible semantics by exiting explicitly. diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs new file mode 100644 index 000000000..39f566e7e --- /dev/null +++ b/lib/instrumentation-crash-policy.test.mjs @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("..", import.meta.url)); + +const readOrEmpty = (file) => { + try { + return readFileSync(file, "utf8"); + } catch { + return ""; + } +}; + +// Runs instrumentation.node.ts's register() in a child, then throws `error` +// uncaught. Returns the exit status (0 = kept serving) plus the journals under +// the agent dir and under ~/.omp (the default, un-isolated location). +function throwAfterRegister(errorExpr, { agentDir = "agent" } = {}) { + const home = mkdtempSync(join(tmpdir(), "omp-web-crash-policy-")); + try { + const script = ` + const { createJiti } = await import("jiti"); + const jiti = createJiti(${JSON.stringify(join(root, "lib/"))}, { tsconfigPaths: true }); + const { register } = await jiti.import(${JSON.stringify(join(root, "instrumentation.node.ts"))}); + await register(); + setTimeout(() => { throw ${errorExpr}; }, 0); + setTimeout(() => process.exit(0), 300); + `; + const result = spawnSync(process.execPath, ["--input-type=module", "-e", script], { + cwd: root, + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + PI_CODING_AGENT_DIR: join(home, agentDir), + OMP_WEB_OMP_BIN: join(home, "missing-omp"), + }, + encoding: "utf8", + timeout: 60_000, + }); + return { + status: result.status, + stderr: result.stderr, + journal: readOrEmpty(join(home, agentDir, "omp-web", "diagnostics.log")), + homeJournal: readOrEmpty(join(home, ".omp", "omp-web", "diagnostics.log")), + }; + } finally { + rmSync(home, { recursive: true, force: true }); + } +} + +test("a client disconnect surfacing as uncaught `aborted` is journaled without exiting", () => { + const { status, journal, stderr } = throwAfterRegister(`Object.assign(new Error("aborted"), { code: "ECONNRESET" })`); + assert.equal(status, 0, stderr); + assert.match(journal, /\[client-abort\] uncaughtException Error: aborted/); + assert.doesNotMatch(journal, /\[crash\]/); +}); + +test("the journal follows an isolated agent dir and keeps ~/.omp/omp-web by default", () => { + const isolated = throwAfterRegister(`new Error("boom")`); + assert.match(isolated.journal, /\[crash\] uncaughtException Error: boom/); + assert.equal(isolated.homeJournal, "", "an isolated run must not write the real journal"); + + const byDefault = throwAfterRegister(`new Error("boom")`, { agentDir: join(".omp", "agent") }); + assert.match(byDefault.homeJournal, /\[crash\] uncaughtException Error: boom/); +}); + +test("any other uncaught exception still exits with code 2", () => { + for (const errorExpr of [ + `new Error("boom")`, + `Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" })`, + `Object.assign(new Error("aborted by peer"), { code: "ECONNRESET" })`, + `Object.assign(new Error("aborted"), { code: "ERR_OTHER" })`, + `null`, + `undefined`, + ]) { + const { status, journal, stderr } = throwAfterRegister(errorExpr); + assert.equal(status, 2, `${errorExpr}\n${stderr}`); + assert.match(journal, /\[crash\] uncaughtException/, errorExpr); + } +}); diff --git a/lib/omp/paths.ts b/lib/omp/paths.ts index 7234f1449..e528354a2 100644 --- a/lib/omp/paths.ts +++ b/lib/omp/paths.ts @@ -40,6 +40,13 @@ function isDefaultAgentDir(): boolean { return true; } +/** omp-web's crash/stall journal directory: ~/.omp/omp-web, or + * /omp-web when PI_CODING_AGENT_DIR points elsewhere, so isolated + * runs (tests, dev servers) never write the real journal. */ +export function getDiagnosticsDir(): string { + return path.join(isDefaultAgentDir() ? getConfigRoot() : getAgentDir(), "omp-web"); +} + /** XDG data root for the default agent dir: only honored on linux/darwin when * $XDG_DATA_HOME/omp already exists — omp treats the XDG layout as opt-in via * `omp config init-xdg`. XDG flattens the `agent/` prefix: