diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..701be0930 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **A busy omp is no longer killed by a slow answer.** Every command timeout used to destroy the child and report `session_unresponsive`; omp blocks its event loop for tens of seconds on large sessions, so a status poll that timed out looked like a dead session and recycled a live run. A timeout now keeps the child and answers `503 session_slow` on the status routes: the web UI retries the poll, a prompt that may already have reached omp is reported as `maybeStarted` instead of being dropped, and an unconfirmed abort says so. Only a child that produced no frame and no answer for five minutes (`OMP_WEB_STALL_DESTROY_MS`, `0` disables) is reaped; it is recorded as `exited` with `detail: "stalled"`. Stop still reaches the child when its command queue is full, and a prompt whose ack timed out keeps the child until that stall window instead of the shorter disconnect cleanup. +- **An idle session no longer looks like a working one.** The agent routes distinguish `running` (a turn is in flight) from `alive` (the child exists), so a freshly spawned omp that is still loading a large session stops showing a busy chat. While a run is marked but the child sends no events, the answer carries `silentForMs` and the composer appends "no events for N min" past three minutes. The 503 reports the child's real `alive` state, and a session switch whose ack timed out is rekeyed once a later state read shows the new identity, so the old id stops routing to the new conversation. +- **Renaming a session cannot be written behind the live child's back.** A rename that times out answers 503 instead of falling back to the on-disk title slot, which the child would overwrite on its next flush. +- **A rejected background task no longer ends the server.** An unhandled rejection is journaled and logged (rate-limited) while the server keeps serving; uncaught exceptions keep their crash semantics. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 892d71293..618bb4fed 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -35,7 +35,7 @@ function commandErrorResponse(error: unknown) { return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } if (error instanceof WebRpcError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + return NextResponse.json({ error: error.message, code: error.code, ...error.details }, { status: 400 }); } if (error instanceof RpcCommandError) { return NextResponse.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 }); @@ -150,14 +150,39 @@ export async function GET( try { const session = getRpcSession(id); if (!session || !session.isAlive()) { - return NextResponse.json({ running: false }); + return NextResponse.json({ running: false, alive: false }); } try { const state = await session.send({ type: "get_state" }); - return NextResponse.json({ running: true, state }); + // `running` is the run, `alive` the child. A live omp that is merely idle + // (freshly spawned, between turns) must never look like a run in flight, + // or every client shows a working state over a chat nobody asked anything. + // `get_state` reconciled the wrapper's flags above, so the run state is + // authoritative here. + return NextResponse.json({ running: session.isRunning(), alive: true, state }); } catch (error) { - if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return NextResponse.json({ running: false, recovered: true }); + // omp being slow is not the run ending: answer 503 so clients retry the + // poll instead of treating the session as idle/recovered. 0.6.0's own + // get_state timeout reports `session_state_timeout`; native clients know + // only one "still running, retry" state, so both codes answer as + // `session_slow`. + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + // A blocked child answers nothing, so this 503 is the client's only + // chance to learn how long the run it still shows has been silent — and + // whether that run exists at all: an idle child that is just loading a + // large session answers `session_slow` too, and clients must be able to + // settle on that instead of keeping the run marked until the next + // successful poll. + return NextResponse.json({ + error: error.message, + code: "session_slow", + ...error.details, + running: session.isRunning(), + // The timeout that answers this 503 may just have disposed a stalled + // child; the body must not advertise a process that is gone. + alive: session.isAlive(), + silentForMs: session.silentForMs(), + }, { status: 503 }); } throw error; } diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index 97cd2386b..569589530 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -35,6 +35,11 @@ function sessionsErrorResponse(error: unknown): NextResponse { if (error instanceof WebRpcError && error.code === "session_busy") { return NextResponse.json({ error: error.message, code: error.code }, { status: 409 }); } + // Same "still running, retry" answer as the state polls: omp did not confirm + // the command within its bound, so the caller must not treat it as done. + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + return NextResponse.json({ error: error.message, code: "session_slow" }, { status: 503 }); + } if (error instanceof SessionFileTooLargeError) { return NextResponse.json( { error: "Session file is too large to open in omp-web", code: "session_file_too_large" }, @@ -234,18 +239,23 @@ export async function GET( // ?includeState=1 inlines the wrapper's live agent state (same shape as // GET /api/agent/[id]) so the client's post-turn refresh is one request // instead of two. On a get_state failure the field is omitted entirely — - // callers treat a missing `agent` as "fetch it separately". - let agent: { running: boolean; state?: unknown } | undefined; + // callers treat a missing `agent` as "fetch it separately"; a child that is + // gone answers `{ running: false, alive: false }` like the other routes. + let agent: { running: boolean; alive: boolean; state?: unknown } | undefined; if (includeState) { const rpc = getRpcSession(id); if (rpc?.isAlive()) { try { - agent = { running: true, state: await rpc.send({ type: "get_state" }) }; + // Same split as GET /api/agent/[id]: `running` is the run in flight, + // `alive` the child (an idle wrapper is alive, not running). + const state = await rpc.send({ type: "get_state" }); + agent = { running: rpc.isRunning(), alive: true, state }; } catch { // Leave agent unset; the session payload is still valid without it. } } else { - agent = { running: false }; + // Same shape as GET /api/agent/[id]: a dead/absent child is not a run. + agent = { running: false, alive: false }; } } @@ -285,8 +295,16 @@ export async function PATCH( await rpc.send({ type: "set_session_name", name: name.trim() }); renamed = true; } catch (error) { - if (error instanceof WebRpcError && error.code === "session_busy") throw error; - // Fall back to the on-disk title slot below. + // A timeout was never confirmed by omp: it still holds the old name in + // memory and would clobber a file write on its next flush. Answer + // "busy, try again" instead of reporting a rename that did not happen. + if (error instanceof WebRpcError + && (error.code === "session_busy" || error.code === "session_slow" || error.code === "session_state_timeout")) { + throw error; + } + // The child answered with an error (it rejected the command, nothing was + // applied) or went away before answering: with no live writer left, the + // on-disk title slot below is safe. } } if (!renamed) { diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index fe4b961a5..96da4c02c 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -15,21 +15,40 @@ export async function GET( if (rpc?.isAlive()) { try { const state = await rpc.send({ type: "get_state" }); - return NextResponse.json({ running: true, state }); + // `running` = a run is in flight, `alive` = the child exists. An idle + // child that just answered `get_state` is alive and not running; the + // flags were reconciled by that answer, so this is authoritative. + return NextResponse.json({ running: rpc.isRunning(), alive: true, state }); } catch (error) { - if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return NextResponse.json({ running: false, recovered: true }); + // omp being slow is not the run ending: answer 503 so clients retry + // instead of treating the session as idle/recovered. Both the code + // this tree raises (`session_slow`) and 0.6.0's own + // `session_state_timeout` mean the same thing to a client. + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + // Same clock as the success body: a blocked child answers nothing, + // so the 503 is where a client learns how long the run it still + // shows has been silent — and whether there is a run at all. + return NextResponse.json({ + error: error.message, + code: "session_slow", + ...error.details, + running: rpc.isRunning(), + // The timeout behind this 503 may have disposed a stalled child; + // `alive` is the child, so read it after the catch. + alive: rpc.isAlive(), + silentForMs: rpc.silentForMs(), + }, { status: 503 }); } throw error; } } const exited = getExitedRpcSession(id); - if (exited) return NextResponse.json({ running: false, exited }); + if (exited) return NextResponse.json({ running: false, alive: false, exited }); const resolved = await resolveSessionPathOr404(id); if ("response" in resolved) return resolved.response; - return NextResponse.json({ running: false }); + return NextResponse.json({ running: false, alive: false }); } catch (error) { return apiErrorResponse(error); } diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 52a5354aa..ea0923e62 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -71,6 +71,13 @@ interface Props { onOpenProviders?: () => void; } +/** Below this a slow phase is merely slow. Past it the status line names how + * long omp has been silent (server frame clock): the child can answer + * `get_state` for hours while its run sits in an advisor/auto-retry loop, and + * "Thinking…" alone then claims progress that is not happening. The liveness + * watchdog's five-minute window is what actually ends such a run. */ +const AGENT_SILENT_NOTICE_MS = 3 * 60_000; + function phaseLabel(phase: AgentPhase): string { if (phase?.kind === "running_tools") { const names = phase.tools.map((tool) => tool.name); @@ -518,7 +525,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa toolPreset, liveModelMeta, retryInfo, contextUsage, forkingEntryId, editingEntryId, - isCompacting, compactResult, tokensPerSecond, displayModel: displayModelValue, sessionStats, + isCompacting, compactResult, tokensPerSecond, agentSilentMs, displayModel: displayModelValue, sessionStats, slashCommands, slashCommandsLoading, queuedMessages, advisorActive, advisorEnabled, handleAdvisorChange, notices, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, skillDiagnostics, setSkillStartupDiagnostics, @@ -1023,9 +1030,12 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa if (bashRunning && !pendingBash) { return t("chatWindow.runningCommand"); } - if (isCompacting || (agentRunning && !streamState.streamingMessage && pendingToolHeaders.length === 0)) { + if (agentRunning || isCompacting) { return [ phaseLabel(agentPhase), + agentSilentMs != null && agentSilentMs >= AGENT_SILENT_NOTICE_MS + ? t("chatWindow.agentSilent", { minutes: Math.max(1, Math.floor(agentSilentMs / 60_000)) }) + : null, activeSubagentCount > 0 ? tn("chatWindow.subagentCount", activeSubagentCount) : null, isCompacting ? t("chatWindow.compactingContext") : null, currentTodoPhase @@ -1038,7 +1048,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa ].filter(Boolean).join(" · "); } return null; - }, [bashRunning, pendingBash, isCompacting, agentRunning, streamState.streamingMessage, pendingToolHeaders.length, agentPhase, activeSubagentCount, currentTodoPhase, t, tn]); + }, [bashRunning, pendingBash, isCompacting, agentRunning, agentPhase, agentSilentMs, activeSubagentCount, currentTodoPhase, t, tn]); const askOpen = extensionDialog?.method === "ask"; const hiddenComposerRef = useRef(null); diff --git a/components/SessionSidebar-rows.tsx b/components/SessionSidebar-rows.tsx index 326c5d991..361f2852b 100644 --- a/components/SessionSidebar-rows.tsx +++ b/components/SessionSidebar-rows.tsx @@ -3,6 +3,7 @@ import { memo, useCallback, useRef, useState } from "react"; import type { AgentMessage, ExitedRpcSession, ManagedProject, ProjectLaunchConfig, SessionInfo } from "@/lib/types"; import { formatExitedSessionNotice, useI18n } from "@/lib/i18n"; +import { formatApiError } from "@/lib/i18n/api-error"; import { ChevronDown, ChevronRight, Folder, GitBranch, MoreHorizontal, Pin } from "lucide-react"; import { Tooltip } from "./ui/primitives"; import { ConfirmDialog } from "./ui/field"; @@ -645,7 +646,15 @@ const SessionItem = memo(function SessionItem({ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }), }); - if (!response.ok) throw new Error("Session rename failed"); + if (!response.ok) { + // 503 means omp is busy and did not confirm the rename: the old title + // stays, so say "busy, try again" instead of failing silently. + if (response.status === 503) { + const payload = await response.json().catch(() => null) as { code?: string; error?: string } | null; + toast.error(formatApiError(payload)); + } + return; + } onRenamed?.(); } catch { // The next refresh remains authoritative if the rename fails. diff --git a/hooks/useAgentSession-stream.ts b/hooks/useAgentSession-stream.ts index 3ede5b416..fca8cc95f 100644 --- a/hooks/useAgentSession-stream.ts +++ b/hooks/useAgentSession-stream.ts @@ -196,6 +196,9 @@ export type AgentStateResponse = { isBashRunning?: boolean; isCompacting?: boolean; responseObserved?: boolean; + /** Milliseconds since the child's last frame while a run is marked (server + * frame clock; poll answers do not count). `null` when nothing runs. */ + silentForMs?: number | null; tokensPerSecond?: number | null; extensionStatuses?: ExtensionStatusItem[]; extensionWidgets?: ExtensionWidgetItem[]; @@ -262,6 +265,12 @@ export const PROMPT_SETTLE_INITIAL_DELAY_MS = 800; export const PROMPT_SETTLE_POLL_MS = 600; export const PROMPT_SETTLE_MAX_MS = 20_000; export const AGENT_STATE_RECONCILE_MS = 15_000; +// A 503 `session_slow` keeps the run marked so the next poll can settle it, but +// only while there is evidence the run exists: the answer itself carries the +// server's run state. A server that does not report it (older build) gets this +// bound — after this many consecutive slow answers the running list, the +// server's own run registry, decides instead of an "unknown" that never ends. +export const SLOW_STATE_MAX_ANSWERS = 3; // Stop waits at most this long to take queued messages back before aborting. export const WITHDRAW_BEFORE_ABORT_MS = 1_500; export const BASH_STATE_RECONCILE_MS = 1_000; diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index d6ab9f8e8..58fa1d964 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -106,6 +106,8 @@ const world = { wrappers: new Map(), nativeHistories: new Map(), // isolated, parent-linked native history fixtures btwHistory: new Map(), // sid -> BtwRecord[] served by get_btw_history + /** `runningSessionIds` of `GET /api/sessions` (the run registry fallback). */ + runningSessionIds: [], }; async function fetchStub(url, init = {}) { @@ -123,11 +125,25 @@ async function fetchStub(url, init = {}) { } let m; + if (u === "/api/sessions" && method === "GET") { + return jsonResponse(200, { + sessions: [], + runningSessionIds: world.runningSessionIds, + runningSessions: world.runningSessionIds.map((id) => ({ id, cwd: "/workspace" })), + exitedSessions: [], + }); + } if ((m = u.match(/\/api\/sessions\/([^/?#]+)\/state/))) { const wrapper = world.wrappers.get(decodeURIComponent(m[1])); - if (wrapper) return jsonResponse(200, { running: wrapper.isAlive(), state: await wrapper.send({ type: "get_state" }) }); - const a = world.agents.get(decodeURIComponent(m[1])) ?? { running: false, state: {} }; - return jsonResponse(200, { running: a.running, state: a.state }); + if (wrapper) return jsonResponse(200, { running: wrapper.isAlive(), alive: wrapper.isAlive(), state: await wrapper.send({ type: "get_state" }) }); + const a = world.agents.get(decodeURIComponent(m[1])); + // A fixture entry without `alive` keeps the pre-split meaning of `running` + // ("a child answers"); an idle-but-alive child sets `alive: true`. + return jsonResponse(200, { + running: a?.running ?? false, + alive: a?.alive ?? a?.running ?? false, + state: a?.state ?? {}, + }); } if (/\/api\/sessions\/[^/?#]+\/subagents/.test(u)) { return jsonResponse(200, { subagents: [] }); @@ -166,12 +182,18 @@ async function fetchStub(url, init = {}) { const sid = decodeURIComponent(m[1]); const wrapper = world.wrappers.get(sid); if (wrapper) { - if (method === "GET") return jsonResponse(200, { running: wrapper.isAlive(), state: await wrapper.send({ type: "get_state" }) }); + if (method === "GET") return jsonResponse(200, { running: wrapper.isAlive(), alive: wrapper.isAlive(), state: await wrapper.send({ type: "get_state" }) }); if (method === "POST") return jsonResponse(200, { success: true, data: await wrapper.send(safeParse(init.body)) }); } if (method === "GET") { - const a = world.agents.get(sid) ?? { running: false, state: {} }; - return jsonResponse(200, { running: a.running, state: a.state }); + const a = world.agents.get(sid); + // Same fixture rule as the state route: `running` stays the fallback for + // `alive` so pre-split fixtures keep their meaning. + return jsonResponse(200, { + running: a?.running ?? false, + alive: a?.alive ?? a?.running ?? false, + state: a?.state ?? {}, + }); } if (method === "POST") { const nativeHistory = world.nativeHistories.get(sid); @@ -361,6 +383,7 @@ function resetWorld() { world.nativeHistories.clear(); world.btwHistory.clear(); world.abortRestoreQueue = null; + world.runningSessionIds = []; } function primeSession(sid, messages) { @@ -1338,6 +1361,280 @@ for (const recovered of ["answer", "empty", "absent wrapper"]) { }); } +for (const code of ["session_slow", "session_state_timeout"]) { + test(`a 503 ${code} state read on open keeps the transcript, marks the run alive and settles via the poll`, async (t) => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question"), assistantMsg("a0", "old answer")]); + // omp blocks its event loop on a large session until it finishes the turn; + // the state route answers "still running, retry later". + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ status: 503, value: { error: "omp is busy", code, silentForMs: 30 * 60_000 } }), + }); + const consoleError = t.mock.method(console, "error", () => {}); + + const w = await mountSession("s1"); + + assert.equal(w.latest.loading, false, "hydration completes despite the busy child"); + assert.equal(w.latest.error, null, "a busy session must not paint a load error"); + assert.deepEqual(w.latest.messages.map((m) => m.role), ["user", "assistant"], "the transcript still comes from disk"); + assert.equal(w.latest.agentRunning, true, "the live run stays marked (state unknown, not ended)"); + assert.equal(w.latest.agentSilentMs, 30 * 60_000, "the busy answer carries how long omp has been silent"); + assert.equal(world.esInstances.length, 1, "the observer stream attaches so frames still arrive"); + assert.equal(consoleError.mock.callCount(), 0, "a busy child must not be a console error"); + + // The periodic reconcile poll answers once omp drains its loop: the run + // settles silently instead of staying a phantom forever. + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(w.latest.agentRunning, false, "the poll settles the run once omp answers again"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), [], "settling a slow session is not a failure"); + }); +} + +test("a busy reconcile poll keeps the run marked and reports how long omp has been silent", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "start it")]); + const { w } = await startRun("s1", "go on"); + // omp's event loop is blocked, so the poll answers 503 `session_slow`. That + // must neither end the run nor hide the frame clock the answer carries — + // a blocked child produces no other report at all. + // Every poll hits the blocked child (a one-shot hold would let the gauge + // sampler see a healthy answer instead), so the answer is re-armed each time. + const busyPoll = { status: 503, value: { error: "omp is busy", code: "session_slow", silentForMs: 2 * 60 * 60_000 } }; + const armBusyPoll = () => world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => { armBusyPoll(); return busyPoll; }, + }); + armBusyPoll(); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(w.latest.agentRunning, true, "a busy poll must not end the run"); + assert.equal(w.latest.agentSilentMs, 2 * 60 * 60_000, "the busy answer's frame clock reaches the status line"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), [], "a busy child is not an error"); + + // The 2 s gauge sampler hits the same 503 between two reconciles. A sample + // that carries no state must not clear the clock the reconcile delivered, or + // "silent since" flickers once per sampler tick. + await act(async () => { await sleep(2300); }); + assert.equal(w.latest.agentSilentMs, 2 * 60 * 60_000, "a stateless sample keeps the silence value"); + w.unmount(); +}); + +test("a 503 that reports no run in flight does not mark an idle child as working", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question"), assistantMsg("a0", "old answer")]); + // The fresh-spawn case from the report: omp is alive but still loading a + // large session, so `get_state` times out while nothing is running. `running` + // in the body is the server's run registry answering "no turn". + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true, silentForMs: 0 } }), + }); + + const w = await mountSession("s1"); + + assert.equal(w.latest.loading, false, "hydration completes despite the busy child"); + assert.deepEqual(w.latest.messages.map((m) => m.role), ["user", "assistant"], "the transcript still comes from disk"); + assert.equal(w.latest.agentRunning, false, "no run in flight is not a run"); + assert.equal(w.latest.agentSilentMs, null, "an idle child has no run whose silence could be reported"); + assert.equal(world.esInstances.length, 1, "the living child is observed, exactly as on the 200 mount path"); + assert.equal(world.esInstances[0].channel.sessionId, "s1"); + + // The observer is what turns a run another tab starts into this tab's state. + await act(async () => { + lastEs().open(); + lastEs().emit({ type: "agent_start" }); + }); + await settle(); + assert.equal(w.latest.agentRunning, true, "a run announced on the observer marks the session"); + w.unmount(); +}); + +test("an idle but living child still gets an observer stream on the mount", async () => { + resetWorld(); + // The idle wrapper a second client is looking at: no turn in flight, but the + // child exists and will broadcast the frames of a run another tab starts. + primeSession("s1", [userMsg("u0", "old question"), assistantMsg("a0", "old answer")]); + world.agents.set("s1", { running: false, alive: true, state: { slowModeSupported: true } }); + + const w = await mountSession("s1"); + + assert.equal(w.latest.agentRunning, false, "an idle child is not a run in flight"); + assert.equal(world.esInstances.length, 1, "a living child is observed even while it is idle"); + assert.equal(world.esInstances[0].channel.sessionId, "s1"); + assert.equal(w.latest.agentSilentMs, null, "an idle child has no run whose silence could be reported"); +}); + +test("a reconcile 503 that reports no run in flight settles the run", async () => { + resetWorld(); + // A live child with a turn this client sees through its stream: the mount + // marks it running without starting the post-send settlement loop. + primeSession("s1", [userMsg("u0", "go"), assistantMsg("a1", "answered while the frame was lost")]); + world.agents.set("s1", { running: true, alive: true, state: { isStreaming: true } }); + const w = await mountSession("s1"); + assert.equal(w.latest.agentRunning, true, "the mounted run is marked"); + + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true } }), + }); + // The blocked child answers no poll at all: the settlement's own state read + // fails too, so only the 503's `running:false` can end the run. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true } }), + }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(w.latest.agentRunning, false, "the authoritative answer ended the run"); + assert.equal(w.latest.agentSilentMs, null, "an ended run has no silence to report"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), [], "settling an idle child is not an error"); +}); + +test("an authoritative idle settles a run that produced nothing this client can read", async () => { + resetWorld(); + // A run the client sees through its stream, with no answer yet: the + // transcript holds only the prompt, so a failed reload proves nothing. + primeSession("s1", [userMsg("u0", "go")]); + world.agents.set("s1", { running: true, alive: true, state: { isStreaming: true } }); + const w = await mountSession("s1"); + assert.equal(w.latest.agentRunning, true, "the mounted run is marked"); + + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true } }), + }); + // Every read of the blocked child fails, including the settlement's own two. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true } }), + }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + + assert.equal(w.latest.agentRunning, false, "the server's no-run answer ends the run even with no readable transcript"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), [], "an unreadable empty run is never claimed as a failure"); + assert.deepEqual( + w.latest.notices.filter((n) => n.type === "warning").map((n) => n.message), + ["omp is busy — your message may still be running."], + "what stays unknown (whether the turn answered) is stated once", + ); +}); + +test("a 503 without a run state is bounded by the running list instead of staying working", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "go"), assistantMsg("a1", "answered long ago")]); + world.agents.set("s1", { running: true, alive: true, state: { isStreaming: true } }); + const w = await mountSession("s1"); + assert.equal(w.latest.agentRunning, true); + + const registryCalls = () => world.calls.filter((c) => c.method === "GET" && c.url === "/api/sessions").length; + const slowAnswer = () => { + // An older server answers without `running`: "unknown" is all the client gets. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", silentForMs: 4 * 60 * 60_000 } }), + }); + }; + const poll = async () => { + slowAnswer(); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + }; + // The registry says nothing runs: the run the client still shows is a ghost. + world.runningSessionIds = []; + + await poll(); + await poll(); + assert.equal(w.latest.agentRunning, true, "under the bound the run stays marked"); + assert.equal(registryCalls(), 0, "the registry is only consulted once the bound is exceeded"); + + // Every poll of the blocked child fails, including the settlement's state read. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", running: false, alive: true } }), + }); + await poll(); // third consecutive answer: the bound is exceeded + assert.equal(registryCalls(), 1, "the run registry is consulted at the bound"); + assert.equal(w.latest.agentRunning, false, "a session the registry does not run is not kept as working"); +}); + +test("the slow-answer bound keeps a run the running list still names", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "go"), assistantMsg("a1", "long answer")]); + world.agents.set("s1", { running: true, alive: true, state: { isStreaming: true } }); + const w = await mountSession("s1"); + + const registryCalls = () => world.calls.filter((c) => c.method === "GET" && c.url === "/api/sessions").length; + world.runningSessionIds = ["s1"]; + for (let i = 0; i < 3; i += 1) { + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", silentForMs: 90_000 } }), + }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + } + assert.equal(registryCalls(), 1, "the registry answered"); + assert.equal(w.latest.agentRunning, true, "a run the registry still reports keeps its working state"); + + // The bound restarts after the registry confirmed the run: no request per poll. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/agent/s1", + produce: async () => ({ status: 503, value: { error: "omp is busy", code: "session_slow", silentForMs: 91_000 } }), + }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(registryCalls(), 1, "a confirmed run does not re-ask on the next slow answer"); + assert.equal(w.latest.agentRunning, true); +}); + +test("a run omp keeps answering while it emits no frames shows how long it has been silent", { timeout: 10_000 }, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "start it")]); + const { w } = await startRun("s1", "go on"); + // The 2026-10-28 phantom: omp's RPC loop kept answering `get_state` (so the + // watchdog and every poll saw a live child) while the run itself emitted + // nothing for hours. The server's frame clock rides along as `silentForMs`; + // the status line needs it to say "no events for 30 min" instead of a bare + // "Thinking…". + world.agents.set("s1", { running: true, state: { isStreaming: true, silentForMs: 30 * 60_000 } }); + await act(async () => { + await sleep(2200); // the 2 s gauge sample + }); + assert.equal(w.latest.agentSilentMs, 30 * 60_000, "the server's frame silence reaches the status line"); + + // A run that reports nothing below the threshold keeps the phase alone. + world.agents.set("s1", { running: true, state: { isStreaming: true, silentForMs: null } }); + await act(async () => { + await sleep(2200); + }); + assert.equal(w.latest.agentSilentMs, null, "a null sample clears it again"); + w.unmount(); +}); + for (const result of ["visible answer", "provider failure"]) { test(`${result} still settles when the state request fails`, async () => { resetWorld(); @@ -1739,6 +2036,33 @@ test("ISSUE #187 the context ring fills mid-run while the agent is still streami assert.equal(w.latest.agentRunning, true, "applying usage must not finish a busy run"); }); +test("a 503 session_slow reconcile poll keeps the run alive instead of ending it", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + const { w, es } = await startRun("s1", "q1"); + await act(async () => { + es.emit({ type: "agent_start" }); + es.emit({ type: "message_update", message: assistantMsg("a1", "streaming") }); + await Promise.resolve(); + }); + await settle(90); + + // omp blocks its loop for tens of seconds on a large session, so the poll + // route answers 503 session_slow. That means "still running, retry later" — + // it must never finish the turn or show an error. + world.holds.push({ + match: (method, url) => method === "GET" && url.includes("/api/agent/s1"), + produce: () => ({ status: 503, value: { error: "omp is busy", code: "session_slow" } }), + }); + await act(async () => { + es.emit({ type: "todo_reminder" }); // triggers the mid-run reconcile poll + await sleep(30); + }); + await settle(); + assert.equal(w.latest.agentRunning, true, "a slow poll must not finish the run"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); +}); + test("fatal SSE error mid-run reconnects after 1s and the new stream delivers events", async () => { resetWorld(); primeSession("s1", [userMsg("u0", "q")]); @@ -4531,6 +4855,141 @@ test("overlapping Stops share one atomic withdrawal; an image-only entry does no clearDraft("abort-atomic-twice"); }); +test("an atomic Stop omp did not confirm warns instead of claiming the run stopped", async () => { + const { getDraft, clearDraft } = await jiti.import("@/lib/draft-store"); + const { translate } = await jiti.import("@/lib/i18n"); + resetWorld(); + clearDraft("abort-unconfirmed"); + primeSession("abort-unconfirmed", [userMsg("u0", "loaded question")]); + const { w } = await startRun("abort-unconfirmed", "hello agent"); + // omp is too busy to answer: neither the stop nor the state of its queue is known. + world.holds.push({ + match: isAtomicStop, + produce: async () => ({ + status: 400, + value: { + error: "omp is busy and did not answer the abort in time; the abort is not confirmed and the session keeps running.", + code: "session_slow", + abortUnconfirmed: true, + }, + }), + }); + + await act(async () => { await w.latest.handleAbort(); }); + + assert.deepEqual(w.latest.notices.map((n) => [n.type, n.message]), [ + ["warning", translate("agentSession.abortUnconfirmed")], + ]); + // Retrying a busy child would only keep the Stop pending; and a queue guess + // (per-entry withdrawal, a restored draft) would be wrong. + assert.equal(world.calls.filter((c) => c.body?.type === "abort_and_restore_queue").length, 1); + assert.equal(world.calls.some((c) => c.body?.type === "remove_queued_message"), false); + assert.equal(world.calls.some((c) => c.body?.type === "abort"), false); + assert.equal(getDraft("abort-unconfirmed"), null); + assert.equal(w.latest.agentRunning, true, "an unconfirmed stop never ends the run locally"); + clearDraft("abort-unconfirmed"); +}); + +test("a fallback Stop whose abort omp did not confirm warns as well", async () => { + const { translate } = await jiti.import("@/lib/i18n"); + resetWorld(); + primeSession("abort-unconfirmed-fallback", [userMsg("u0", "loaded question")]); + const { w } = await startRun("abort-unconfirmed-fallback", "hello agent"); + // omp without abort_and_restore_queue: the fallback aborts per entry, and + // that abort is the one omp never answered. + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "abort", + produce: async () => ({ + status: 400, + value: { + error: "omp is busy and did not answer the abort in time; the abort is not confirmed and the session keeps running.", + code: "session_slow", + abortUnconfirmed: true, + }, + }), + }); + + await act(async () => { await w.latest.handleAbort(); }); + + assert.deepEqual(w.latest.notices.map((n) => [n.type, n.message]), [ + ["warning", translate("agentSession.abortUnconfirmed")], + ]); + assert.equal(w.latest.agentRunning, true); +}); + +test("an interrupt-and-reply whose ack timed out keeps its bubble and its pending guard", async () => { + const { getDraft, clearDraft } = await jiti.import("@/lib/draft-store"); + const { translate } = await jiti.import("@/lib/i18n"); + resetWorld(); + clearDraft("interrupt-maybe-started"); + primeSession("interrupt-maybe-started", [userMsg("u0", "loaded question")]); + const { w } = await startRun("interrupt-maybe-started", "hello agent"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "abort_and_prompt", + produce: async () => ({ + status: 400, + value: { + error: "omp is busy and did not acknowledge the message in time; it may still be running.", + code: "session_slow", + maybeStarted: true, + }, + }), + }); + + let submission; + await act(async () => { + submission = w.latest.handleInterruptAndReply("replacement"); + await sleep(30); + }); + let accepted; + // The send opens its own event stream and waits for it before dispatching. + await act(async () => { + lastEs().open(); + accepted = await submission; + }); + + assert.equal(accepted, true, "a maybe-started interrupt is not a failed send"); + assert.equal(w.latest.messages.at(-1).content, "replacement", "the optimistic bubble stays"); + assert.equal(getDraft("interrupt-maybe-started"), null, "the text is not handed back to the composer"); + assert.deepEqual(w.latest.notices.map((n) => [n.type, n.message]), [ + ["warning", translate("agentSession.maybeStarted")], + ]); + assert.equal(w.latest.agentRunning, true); + + // The interrupt guard stays: the old turn's terminal end may still arrive + // and must not end the replacement run's lock early. + await act(async () => { lastEs().emit({ type: "agent_end", isTerminal: true }); }); + await settle(); + assert.equal(w.latest.agentRunning, true, "the pending-interrupt guard is kept"); + clearDraft("interrupt-maybe-started"); +}); + +test("a steer whose ack timed out is reported as maybe delivered, not as failed", async () => { + const { translate } = await jiti.import("@/lib/i18n"); + resetWorld(); + primeSession("steer-maybe", [userMsg("u0", "loaded question")]); + const { w } = await startRun("steer-maybe", "hello agent"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "steer", + produce: async () => ({ + status: 400, + value: { + error: "omp is busy and did not acknowledge the message in time; it may still be running.", + code: "session_slow", + maybeStarted: true, + }, + }), + }); + + let accepted; + await act(async () => { accepted = await w.latest.handleSteer("also check the tests"); }); + + assert.equal(accepted, true, "a maybe-delivered steer is not a failed send"); + assert.deepEqual(w.latest.notices.map((n) => [n.type, n.message]), [ + ["warning", translate("agentSession.maybeStarted")], + ]); +}); + function skillDiagnosticsSnapshot(showStartupDiagnostics, name = "review") { return { cwd: "/workspace", diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index a2f8aa6f6..2916ca0bd 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -15,7 +15,7 @@ import type { import { normalizeToolCalls } from "@/lib/normalize"; import { hasVisibleAssistantContent } from "@/lib/assistant-response"; import type { ThinkingModelMeta } from "@/lib/thinking-levels"; -import { sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; +import { AgentCommandError, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "@/lib/skill-diagnostics"; import { clearDraft, getDraft, mergeRecoveredText, recoverDraft, setDraft, toDraftImages, type ChatDraft, type ChatDraftImage } from "@/lib/draft-store"; import { formatExitedSessionNotice, translate } from "@/lib/i18n"; @@ -77,6 +77,7 @@ import { PROMPT_SETTLE_INITIAL_DELAY_MS, PROMPT_SETTLE_MAX_MS, PROMPT_SETTLE_POLL_MS, + SLOW_STATE_MAX_ANSWERS, SCROLL_KEYS, SUBAGENT_ACTIVITY_BUFFER_MAX, USER_SCROLL_INTENT_MS, @@ -174,6 +175,68 @@ function readTerminalAgentError(event: AgentEvent): string | null { return null; } +/** A state GET answers 503 when omp is alive but its event loop is blocked by + * a large session (`session_slow`, and 0.6.0's own `session_state_timeout`). + * That is "still running, retry later" — never a load failure — and the body + * carries the server's frame clock, which is the only silence report a client + * can get while the child answers no poll at all. It also carries the + * server's run state (`running`): an idle child that is merely loading a big + * session answers `session_slow` too, and `running: false` then means there is + * no run to keep marked. `alive` is the child itself: false when the request's + * own timeout disposed a stalled child, so an observer stream must not attach. + * `null` = not that answer; `running`/`alive: null` = an older server that does + * not report it (see `SLOW_STATE_MAX_ANSWERS`). */ +async function readBusySessionResponse(res: Response): Promise<{ silentForMs: number | null; running: boolean | null; alive: boolean | null } | null> { + if (res.status !== 503) return null; + try { + const body = await res.json() as { code?: unknown; silentForMs?: unknown; running?: unknown; alive?: unknown }; + if (body?.code !== "session_slow" && body?.code !== "session_state_timeout") return null; + const silent = body.silentForMs; + return { + silentForMs: typeof silent === "number" && Number.isFinite(silent) && silent >= 0 ? silent : null, + running: typeof body.running === "boolean" ? body.running : null, + alive: typeof body.alive === "boolean" ? body.alive : null, + }; + } catch { + return null; + } +} + +/** Consecutive 503 answers that carried no run state, per session. */ +interface SlowStateAnswers { + sessionId: string; + count: number; +} + +/** Counts a `session_slow` answer without a run state and reports whether the + * bound is exceeded: after `SLOW_STATE_MAX_ANSWERS` consecutive answers the + * "unknown" window is over and the caller must fall back to the authoritative + * running list. Only path for servers that do not report the run state; the + * answer itself decides whenever it does. */ +function noteSlowStateAnswer(answers: SlowStateAnswers | null, sid: string): { next: SlowStateAnswers; exceeded: boolean } { + if (!answers || answers.sessionId !== sid) { + return { next: { sessionId: sid, count: 1 }, exceeded: false }; + } + answers.count += 1; + return { next: answers, exceeded: answers.count >= SLOW_STATE_MAX_ANSWERS }; +} + +/** Last resort for a server whose 503 does not say whether a run exists: the + * running list is omp-web's own run registry (`getRunningRpcSessions`), the + * same source the sidebar badge is built from. `null` when it cannot be read — + * a failed lookup must never be read as "nothing is running". */ +async function fetchRunningSessionIds(): Promise | null> { + try { + const res = await fetch("/api/sessions"); + if (!res.ok) return null; + const body = await res.json() as { runningSessionIds?: unknown }; + if (!Array.isArray(body.runningSessionIds)) return null; + return new Set(body.runningSessionIds.filter((id): id is string => typeof id === "string")); + } catch { + return null; + } +} + export interface UseAgentSessionOptions { session: SessionInfo | null; newSessionCwd: string | null; @@ -273,6 +336,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // omp's own output throughput from get_state. omp reports a number only // when it has throughput data (typically around generation); null otherwise. const [tokensPerSecond, setTokensPerSecond] = useState(null); + // Milliseconds the child has been frame-silent while a run is marked. Served + // by the server (`silentForMs`, its own frame clock): omp can answer + // `get_state` for hours while the run waits in an advisor/auto-retry loop, so + // the phase label alone claimed "Thinking…" the whole time. `null` = idle. + const [agentSilentMs, setAgentSilentMs] = useState(null); const [compactError, setCompactError] = useState(null); const [compactResult, setCompactResult] = useState(null); const [agentPhase, setAgentPhase] = useState(null); @@ -455,6 +523,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const lastRunErrorRef = useRef(null); const lastShownExitRef = useRef(null); const runHadContentRef = useRef(false); + // Set when the prompt ack timed out but omp may already hold the frame + // (`session_slow` + `maybeStarted`). Suppresses the "stopped without a + // response" claim for this run and keeps the send lock until frames or a + // successful get_state settle it. + const maybeStartedRunRef = useRef(false); + // Consecutive 503 `session_slow` answers that carried no run state (older + // server), so an unknown state cannot be trusted forever. + const slowStateAnswersRef = useRef(null); // Native starts/epoch changes also fence recovery, even without a local send. const responseRunVersionRef = useRef(0); // Persisted entries preceding a locally submitted run cannot supply its answer. @@ -786,7 +862,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { const res = await fetch(`/api/sessions/${encodeURIComponent(sid)}/state`); if (!res.ok) return; - const agentState = await res.json() as { running: boolean; state?: AgentStateResponse }; + const agentState = await res.json() as { running: boolean; alive?: boolean; state?: AgentStateResponse }; if (!hookAliveRef.current || sessionIdRef.current !== sid) return; applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, agentState.state?.skillDiagnostics); const applied = applyAuthoritativeModel(toThinkingModelMeta(agentState.state?.model), token); @@ -802,7 +878,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } setFastModeActive(agentState.state?.fastModeActive); // No omp process: back to the catalog fallback. - setSlowModeSupported(agentState.running ? (agentState.state?.slowModeSupported ?? false) : undefined); + setSlowModeSupported(agentState.alive ? (agentState.state?.slowModeSupported ?? false) : undefined); setSlowModeEnabled(agentState.state?.slowModeEnabled ?? false); setSlowModeScope(agentState.state?.slowModeScope); setUsageLimit(agentState.state?.usageLimit); @@ -816,6 +892,29 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync]); + // omp answered a state read with 503 `session_slow`: the child is alive, but + // its event loop is blocked and `get_state` timed out. A run it still reports + // must stay marked so the periodic reconcile poll settles it, and the + // observer stream attaches (frames are the completion path once omp answers + // again). `running: false` is the server telling us there is no run at all — + // an idle child that is only busy loading a large session — and marking it + // would show "working" over a chat nobody asked anything; its observer still + // attaches, exactly like the 200 mount path does for an idle living child (a + // run another client starts must stream here). `alive: false` is the child + // gone (the same timeout disposed it): nothing to observe. The on-disk + // transcript is already loaded by the caller either way. + const markSessionAliveStateUnknown = useCallback((running: boolean | null, alive: boolean | null) => { + if (running === false) { + if (alive !== false) syncActionsRef.current?.subscribe(false); + return; + } + if (!agentRunningRef.current) { + agentRunningRef.current = true; + setAgentRunning(true); + } + syncActionsRef.current?.subscribe(false); + }, []); + const loadSession = useCallback(async (sid: string, showLoading = false, includeState = false, fenceRunId?: number) => { const requestSeq = ++contextRequestSeqRef.current; catchUp.invalidate(); @@ -881,8 +980,26 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const queueRevision = ++queueSeqRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; const stateRes = await fetch(`/api/sessions/${encodeURIComponent(sid)}/state`); - if (!stateRes.ok) throw new Error(`HTTP ${stateRes.status}`); - const agentState = await stateRes.json() as { running: boolean; state?: AgentStateResponse; exited?: ExitedRpcSession }; + if (!stateRes.ok) { + // A busy child (503 `session_slow` / `session_state_timeout`) is not + // a failed load: the transcript above is the on-disk copy, and the + // state is merely unknown right now. Its body says how long omp has + // been frame-silent and whether a run exists at all — an idle child + // that is only loading must not be marked as running. + const busy = await readBusySessionResponse(stateRes); + if (busy) { + if (!hookAliveRef.current || sessionIdRef.current !== sid + || contextRequestSeqRef.current !== requestSeq || promptRunIdRef.current !== requestRun) { + return null; + } + markSessionAliveStateUnknown(busy.running, busy.alive); + setAgentSilentMs(busy.running === false ? null : busy.silentForMs); + return { context: d.context, agentState: null }; + } + throw new Error(`HTTP ${stateRes.status}`); + } + slowStateAnswersRef.current = null; + const agentState = await stateRes.json() as { running: boolean; alive?: boolean; state?: AgentStateResponse; exited?: ExitedRpcSession }; if (!hookAliveRef.current) return null; if (sessionIdRef.current !== sid) { if (showLoading) setLoading(false); @@ -897,6 +1014,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } const liveState = agentState.state; + // Ownership is part of the live state: a session another omp process + // runs is never resumed by this tab, and the composer must say so. + // `alive` (the child exists), not `running` (a turn is in flight): an + // idle wrapper of ours still owns the session. applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, liveState?.skillDiagnostics); const modelApplied = applyAuthoritativeModel(toThinkingModelMeta(liveState?.model), token); if (liveState) { @@ -905,7 +1026,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (modelApplied && liveState.thinkingLevel !== undefined) setThinkingLevel(normalizeThinkingLevel(liveState.thinkingLevel)); if (liveState.fastModeEnabled !== undefined) setFastModeEnabled(liveState.fastModeEnabled); setFastModeActive(liveState.fastModeActive); - setSlowModeSupported(agentState.running ? (liveState.slowModeSupported ?? false) : undefined); + setSlowModeSupported(agentState.alive ? (liveState.slowModeSupported ?? false) : undefined); setSlowModeEnabled(liveState.slowModeEnabled ?? false); setSlowModeScope(liveState.slowModeScope); setUsageLimit(liveState.usageLimit); @@ -918,7 +1039,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (liveState.extensionWidgets !== undefined) setExtensionWidgets(liveState.extensionWidgets ?? []); if (liveState.todoPhases !== undefined) setTodoPhases(liveState.todoPhases ?? []); applyQueueStateSnapshot(queueRevision, liveState.queuedMessages); - } else if (!agentState.running) { + } else if (!agentState.alive) { setSlowModeSupported(undefined); applyQueueStateSnapshot(queueRevision, null); } @@ -945,7 +1066,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Ensure the flag is cleared even if the pre-state early-return path was taken if (showLoading && includeState && !messagesLoaded) initialHydrationPendingRef.current = false; } - }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); + }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, markSessionAliveStateUnknown]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1589,7 +1710,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [addNotice, opts.chatInputRef]); - const finishPromptWithoutStream = useCallback(async (sid: string | null = sessionIdRef.current, runId = promptRunIdRef.current) => { + /** + * Settles a run that no frame ended. `authoritativeIdle` is the caller's own + * proof that no run is in flight (a 503 body saying `running:false`, a run + * registry that does not name the session): the run ends even when the state + * read below fails, because that failure only leaves the *transcript* + * unknown, never the run. Without it, a file read that proves nothing keeps + * the recovery open (the run may still be answering). + */ + const finishPromptWithoutStream = useCallback(async (sid: string | null = sessionIdRef.current, runId = promptRunIdRef.current, authoritativeIdle = false) => { clearTerminalReconcileTimer(); // Bail out before loadSession too: a stale finish for a previous run // must not overwrite the messages of the run currently streaming. @@ -1636,8 +1765,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { hadContent ||= runHadContentRef.current; runError = lastRunErrorRef.current ?? runError; // File success alone cannot prove an empty answer when state failed. - // Keep recovery active unless visible content or an explicit error settled it. - if (!recoveryLoaded && !hadContent && !runError && !quotaMessage && !allowEmptyResponse) return; + // Keep recovery active unless visible content or an explicit error settled + // it — or the caller holds the server's own "no run" answer, which proves + // the run ended even though this client cannot read what it produced. + if (!recoveryLoaded && !hadContent && !runError && !quotaMessage && !allowEmptyResponse + && !authoritativeIdle) return; if (!agentRunningRef.current) return; if (runError) { addNotice({ type: "error", message: runError }); @@ -1650,14 +1782,24 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Silent stop: no assistant bubble to stamp — the shelf notice is the // in-chat message. Mid-run quota already toasted via the notice path. addNotice({ type: "error", message: quotaMessage }); + } else if (authoritativeIdle && !recoveryLoaded && !hadContent && !allowEmptyResponse) { + // The server ended the run while its state read stayed unreadable, so + // this client cannot tell whether the turn produced an answer. Claiming + // a failure would be a guess; the run still ends (the spinner is not + // left standing), and the send path's hint says what is uncertain. + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); } else if (!hadContent && !allowEmptyResponse) { // Fallback for silent stops with no visible content and no explicit // error — never leave the user with a disappeared spinner and no // explanation. Builtin slash commands are allowed to complete without // an assistant message, hence allowEmptyResponse above. - const message = translate("agentSession.responseFailed"); - addNotice({ type: "error", message }); - toast.error("Request failed", message, { timeout: 10000 }); + // A prompt whose ack timed out may have started late: do not claim it + // failed, repeat the localized hint instead (no error toast). + const message = maybeStartedRunRef.current + ? translate("agentSession.maybeStarted") + : translate("agentSession.responseFailed"); + addNotice({ type: maybeStartedRunRef.current ? "warning" : "error", message }); + if (!maybeStartedRunRef.current) toast.error("Request failed", message, { timeout: 10000 }); } catchUp.invalidate(); eventCoalescer.reset(); @@ -1680,7 +1822,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + maybeStartedRunRef.current = false; slashCommandRunRef.current = false; + slowStateAnswersRef.current = null; onAgentEnd?.(); } }, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, loadSession, onAgentEnd, refreshSubagentHistory, resetSubagentActivityState, surfaceQuotaOnStream]); @@ -1759,8 +1903,49 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const queueRevision = ++queueSeqRef.current; const skillDiagnosticsRevision = ++skillDiagnosticsSeqRef.current; const res = await fetch(`/api/agent/${encodeURIComponent(sid)}`); - if (!res.ok) return; - const data = await res.json() as { running?: boolean; state?: AgentStateResponse }; + if (!res.ok) { + // A busy child (503 `session_slow`) is alive; whether a run is in + // flight is in the body. `running: false` is the server saying the + // child is only blocked (a large transcript, a fresh spawn), so the run + // this client still shows is over — settle it instead of keeping a + // "working" state that no frame will ever end. + const busy = await readBusySessionResponse(res); + if (!busy || !hookAliveRef.current || sessionIdRef.current !== sid + || promptRunIdRef.current !== runId || responseRunVersionRef.current !== responseVersion) return; + if (busy.running === false) { + slowStateAnswersRef.current = null; + setAgentSilentMs(null); + // Authoritative: the settlement's own state read may fail on the same + // blocked child, and that must not keep the ended run marked. + await finishPromptWithoutStream(sid, runId, true); + return; + } + markSessionAliveStateUnknown(busy.running, busy.alive); + setAgentSilentMs(busy.silentForMs); + if (busy.running === null) { + // An older server does not report the run state on its 503. Bound + // the "unknown" window: a run that is never confirmed must not hold + // the UI in "working" for hours. The running list is the server's + // own registry, so it decides once the bound is exceeded. + const answers = noteSlowStateAnswer(slowStateAnswersRef.current, sid); + slowStateAnswersRef.current = answers.next; + if (answers.exceeded) { + const runningIds = await fetchRunningSessionIds(); + // Either way the window restarts, so the next slow answers cannot + // re-ask on every poll. Only a readable list that does not name + // this session ends the run; an unreadable one proves nothing. + slowStateAnswersRef.current = null; + if (runningIds && !runningIds.has(sid) && sessionIdRef.current === sid) { + // The registry is the server's own run state, so its "not + // running" ends the run even if the transcript read fails. + await finishPromptWithoutStream(sid, runId, true); + } + } + } + return; + } + slowStateAnswersRef.current = null; + const data = await res.json() as { running?: boolean; alive?: boolean; state?: AgentStateResponse }; // A slow response can straddle a run boundary (previous run finished // and the user already started the next one while this request was in // flight) — everything in it is stale, drop it. @@ -1807,7 +1992,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void reconcileAgentState(sid); } } - }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); + }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster, markSessionAliveStateUnknown]); // Recovery net for missed SSE events: while the agent is running, verify // against the server periodically and whenever the tab returns to the @@ -1864,6 +2049,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return () => clearInterval(timer); }, [externalRunActive, catchUp]); + // Sample omp's own tokensPerSecond (get_state) at a gauge-friendly cadence // while a run is active; the 15s reconcile above is too slow for a gauge. // On run end take one trailing sample: omp publishes its final throughput @@ -1882,6 +2068,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const tps = data?.state?.tokensPerSecond; setTokensPerSecond(typeof tps === "number" && Number.isFinite(tps) && tps > 0 ? tps : null); if (data?.state) setUsageLimit(data.state.usageLimit); + // The run is over: there is no silence to report over an idle chat. + setAgentSilentMs(null); }) .catch(() => {}); return () => { cancelled = true; }; @@ -1900,6 +2088,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // The usage-limit badge changes per provider response (lane entry, % left). if (data?.state) setUsageLimit(data.state.usageLimit); setTokensPerSecond(typeof tps === "number" && Number.isFinite(tps) && tps > 0 ? tps : null); + // Same sample carries the server's frame clock: a run omp keeps + // answering for while it emits nothing is a silent run, and the + // status line says since when instead of a bare "Thinking…". + // A 503 carries no state at all — keep the value the reconcile poll + // set rather than clearing it between two of its answers. + if (!data) return; + const silentForMs = data.state?.silentForMs; + setAgentSilentMs(typeof silentForMs === "number" && Number.isFinite(silentForMs) && silentForMs >= 0 ? silentForMs : null); }) .catch(() => {}); }, 2000); @@ -1911,6 +2107,18 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setTokensPerSecond(null); }, [data?.sessionId]); + // Same for the frame-silence report, but only on a real switch: the first + // hydration of a session must not wipe the number a busy state answer just + // delivered (that answer *is* the only report a blocked child produces). + const silenceSessionRef = useRef(null); + useEffect(() => { + const sid = data?.sessionId ?? null; + const previous = silenceSessionRef.current; + silenceSessionRef.current = sid; + if (!sid || !previous || previous === sid) return; + setAgentSilentMs(null); + }, [data?.sessionId]); + // Counts runs that ended (any client's), so a delayed Stop can tell that // the run it targeted is over and whatever runs now is not its to abort. // Bumped on each accepted terminal agent_end (before any recovery reload) @@ -2027,6 +2235,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + maybeStartedRunRef.current = false; break; case "agent_end": { // isTerminal === false means an async delivery resumes this run soon. @@ -2096,6 +2305,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + maybeStartedRunRef.current = false; slashCommandRunRef.current = false; if (endedSid) { void loadSession(endedSid, false, false, endedRunId); @@ -2733,6 +2943,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + maybeStartedRunRef.current = false; runPreviousEntryIdsRef.current = sessionIdRef.current ? null : []; agentRunningRef.current = true; slashCommandRunRef.current = isSlashCommandPrompt; @@ -2847,7 +3058,16 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (promptRunIdRef.current !== promptRunId) return { status: "superseded" }; promptDispatchPendingRef.current = false; console.error("Failed to send message:", e); - // Every failure here (stream connect, startup, set_model, or the prompt + // The prompt frame may already sit in omp's stdin (ack timed out while + // omp was busy). Not an undo: keep the optimistic turn, keep reporting + // the run, and keep sending locked until a frame or the next successful + // get_state settles it. A later rollback would contradict the hint. + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + maybeStartedRunRef.current = true; + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return { status: "accepted" }; + } + // Every other failure here (stream connect, startup, set_model, or the prompt // POST itself) means the prompt never started, so roll back the optimistic bubble. setOptimisticUserMessage(null); addNotice({ @@ -2926,6 +3146,17 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (promptRunIdRef.current !== promptRunId || sessionIdRef.current !== sid) return false; promptDispatchPendingRef.current = false; console.error("Failed to interrupt and reply:", e); + // The abort_and_prompt frame may already sit in omp's stdin (same rule as + // handleSend): it aborts the old turn and may already run the new prompt. + // Keep the optimistic bubble, keep the pending-interrupt guard so the old + // turn's agent_end cannot end the replacement, and keep the run reporting + // until a frame or a successful get_state settles it. Handing the text + // back would let the user send it a second time. + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + maybeStartedRunRef.current = true; + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return true; + } if (promptRunIdRef.current === promptRunId && sessionIdRef.current === sid) { runPreviousEntryIdsRef.current = previousRunEntryIds; } @@ -2990,16 +3221,33 @@ export function useAgentSession(opts: UseAgentSessionOptions) { let restoredQueue: RestoredQueue | null | undefined; let unsupported = false; let failures = 0; + let abortUnconfirmed = false; // A failure after omp already withdrew would lose the texts on the // per-entry path (the queue is empty by then). Retrying the same command // is safe instead: omp returns whatever is still queued. - for (let attempt = 0; attempt < 2 && restoredQueue === undefined && !unsupported && (attempt === 0 || sameRun()); attempt++) { + for (let attempt = 0; attempt < 2 && restoredQueue === undefined && !unsupported && !abortUnconfirmed && (attempt === 0 || sameRun()); attempt++) { try { restoredQueue = (await sendAgentCommand(sid, { type: "abort_and_restore_queue" })) ?? null; } catch (error) { unsupported = error instanceof Error && error.message.includes("Unknown command"); if (!unsupported) failures += 1; + // A stop omp never confirmed (too busy to answer) is not a stopped run: + // the frame may sit in its stdin and the run may still execute. Nothing + // is known about the queue either, so this attempt is not retried — + // a second 30-second window on a child that is still busy only keeps + // the Stop pending longer. + if (error instanceof AgentCommandError && error.code === "session_slow" && error.abortUnconfirmed) { + abortUnconfirmed = true; + } + } + } + if (abortUnconfirmed) { + // Nothing is known about the queue, so neither the composer nor the queue + // chips may be rewritten on a guess. + if (hookAliveRef.current && sessionIdRef.current === sid) { + addNotice({ type: "warning", message: translate("agentSession.abortUnconfirmed") }); } + return; } if (!unsupported) { const steering = Array.isArray(restoredQueue?.steering) ? restoredQueue.steering : []; @@ -3082,6 +3330,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "abort" }); } catch (e) { console.error("Failed to abort:", e); + if (e instanceof AgentCommandError && e.code === "session_slow" && e.abortUnconfirmed + && hookAliveRef.current && sessionIdRef.current === sid) { + addNotice({ type: "warning", message: translate("agentSession.abortUnconfirmed") }); + } } } // From here only late recovery remains: a new run's Stop must not wait on it. @@ -3237,6 +3489,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { onSessionForked?.(newSessionId); } } catch (e) { + // The fork spawns a resume child, so the ownership gate applies here too. console.error("Fork failed:", e); } finally { forkInFlightRef.current = false; @@ -3717,6 +3970,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return true; } catch (e) { console.error("Failed to steer:", e); + // The frame may already be in omp's stdin (see handleSend): the message + // may still be delivered, so do not claim it failed nor hand the text back. + // No run marker here: a steer does not start the run, and the marker + // classifies how *this turn* ends (see `finishPromptWithoutStream`). + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return true; + } addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); return false; } @@ -3743,6 +4004,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return true; } catch (e) { console.error("Failed to queue prompt:", e); + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + maybeStartedRunRef.current = true; + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return true; + } addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); return false; } @@ -3761,6 +4027,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return true; } catch (e) { console.error("Failed to follow up:", e); + // Delivered or not, this frame does not start the turn: the run-wide + // maybe-started marker would replace the turn's own `responseFailed` + // report, so it stays with the prompt acks (see handleSend). + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return true; + } addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); return false; } @@ -3875,7 +4148,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }); } } - if (agentState?.running && !eventSourceRef.current) { + // Attach for a living child, not only for a live run: `alive` (the omp + // process exists) is the fact that keeps frames coming — a run another + // client starts, roster/queue updates — so an idle wrapper is watched + // too. `running` is only the fallback for a server that predates the + // split (its `running:true` still meant "a child answers"); the run + // marking below stays gated on the state flags, never on attachment. + if ((agentState?.alive ?? agentState?.running) && !eventSourceRef.current) { void connectEvents(session.id); if (agentState.state?.isStreaming || agentState.state?.isPromptRunning) { agentRunningRef.current = true; @@ -4094,7 +4373,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { agentRunning, modelNames, modelList, modelsLoading, modelError, modelThinkingLevels, modelThinkingLevelMaps, newSessionModel, toolPreset, thinkingLevel, fastModeEnabled, fastModeActive, slowModeSupported, slowModeEnabled, slowModeScope, usageLimit, autoRetryEnabled, interruptMode, autoCompactionEnabled, steeringMode, followUpMode, liveModelMeta, retryInfo, contextUsage, systemPrompt, skillDiagnostics, forkingEntryId, editingEntryId, - isCompacting, compactError, compactResult, tokensPerSecond, currentModel, displayModel, isAutoModelSelection: !displayModel, sessionStats, agentPhase, + isCompacting, compactError, compactResult, tokensPerSecond, agentSilentMs, currentModel, displayModel, isAutoModelSelection: !displayModel, sessionStats, agentPhase, slashCommands, slashCommandsLoading, queuedMessages, notices: noticeState.visible, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput, advisorActive: advisorActiveAt > 0, advisorEnabled, handleAdvisorChange, diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 235561f8a..db0a45bec 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -72,9 +72,9 @@ export async function register(): Promise { // user is away leaves no trace in a terminal that no longer exists (CLI runs // 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 — except for client - // aborts, which are journaled and survived (see below). + // so the next incident explains itself. An uncaught exception keeps Node's + // crash semantics (journal + console record, then exit); client aborts and + // unhandled rejections are journaled and survived (see below). const logDir = getDiagnosticsDir(); const logPath = join(logDir, "diagnostics.log"); const appendDiag = (kind: string, detail: string) => { @@ -100,14 +100,40 @@ export async function register(): Promise { return; } appendDiag("crash", `uncaughtException ${describe(error)}`); + console.error(`[omp-web] uncaught exception — exiting: ${describe(error)}`); // An uncaughtException listener suppresses Node's default exit; keep the - // crash-visible semantics by exiting explicitly. + // crash-visible semantics by exiting explicitly. Unlike a rejection, the + // throw escaped a request handler or timer halfway through its work, so the + // process state (a half-written session file, a held mutex) is unknown and + // there is no safe resume point: staying up would serve corrupted state. process.exit(2); }); + // Rejections of fire-and-forget chains are logged and survived: nobody + // awaited that promise, so every request path is still intact, and killing + // the server for one would take down every chat it serves — the scheduled + // task does not restart a server that dies on its own. The journal always + // gets the record; the console copy is rate-limited so a tick that rejects + // once a second cannot bury it. + let rejectionWindowStart = Date.now(); + let rejectionsLogged = 0; + let rejectionsSuppressed = 0; process.on("unhandledRejection", (reason) => { - appendDiag("crash", `unhandledRejection ${describe(reason)}`); - // Same as above: preserve Node's crash-on-unhandled-rejection default. - process.exit(2); + appendDiag("rejection", `unhandledRejection ${describe(reason)}`); + const now = Date.now(); + if (now - rejectionWindowStart >= 60_000) { + if (rejectionsSuppressed > 0) { + console.error(`[omp-web] ${rejectionsSuppressed} further unhandled rejection(s) in the last minute were journaled only.`); + } + rejectionWindowStart = now; + rejectionsLogged = 0; + rejectionsSuppressed = 0; + } + if (rejectionsLogged < 10) { + rejectionsLogged += 1; + console.error(`[omp-web] unhandled rejection (server keeps running): ${describe(reason)}`); + } else { + rejectionsSuppressed += 1; + } }); let lastTick = Date.now(); let lastCpu = process.cpuUsage(); diff --git a/lib/agent-client.ts b/lib/agent-client.ts index 6686b5a6a..f639dcfe4 100644 --- a/lib/agent-client.ts +++ b/lib/agent-client.ts @@ -14,6 +14,31 @@ import { formatApiError } from "@/lib/i18n/api-error"; // decision happens inside the route, which only sees id + query string. const advisorSpawnSessions = new Set(); +/** A failed `POST /api/agent/[id]` carrying the route's stable code. Callers + * that must react differently from a plain error (a `session_slow` ack timeout + * with `maybeStarted` is not a rolled-back prompt; `abortUnconfirmed` is not a + * completed stop) branch on these fields. */ +export class AgentCommandError extends Error { + readonly code: string | undefined; + readonly maybeStarted: boolean; + /** The abort frame may have reached omp, but nothing confirmed it: the run + * may still be executing. */ + readonly abortUnconfirmed: boolean; + + constructor( + message: string, + code: string | undefined, + maybeStarted: boolean, + abortUnconfirmed: boolean, + ) { + super(message); + this.name = "AgentCommandError"; + this.code = code; + this.maybeStarted = maybeStarted; + this.abortUnconfirmed = abortUnconfirmed; + } +} + export function setSessionAdvisorSpawn(sessionId: string, enabled: boolean) { if (enabled) advisorSpawnSessions.add(sessionId); else advisorSpawnSessions.delete(sessionId); @@ -23,7 +48,9 @@ export async function sendAgentCommand( sessionId: string, command: Record, ): Promise { - const query = advisorSpawnSessions.has(sessionId) ? "?advisor=1" : ""; + const params = new URLSearchParams(); + if (advisorSpawnSessions.has(sessionId)) params.set("advisor", "1"); + const query = params.size > 0 ? `?${params.toString()}` : ""; const res = await fetch(`/api/agent/${encodeURIComponent(sessionId)}${query}`, { method: "POST", headers: { "Content-Type": "application/json" }, @@ -34,12 +61,17 @@ export async function sendAgentCommand( data?: T; error?: string; code?: string; + maybeStarted?: boolean; + abortUnconfirmed?: boolean; }; if (!res.ok || body.error) { // Routes attach a stable `code` for well-known failures; these messages are // surfaced to the user as notices, so localize before throwing. - throw new Error( + throw new AgentCommandError( body.error || body.code ? formatApiError(body) : `HTTP ${res.status}`, + body.code, + body.maybeStarted === true, + body.abortUnconfirmed === true, ); } return body.data as T; diff --git a/lib/agent-skill-diagnostics-route.test.mjs b/lib/agent-skill-diagnostics-route.test.mjs index 76fcb2591..b99440c15 100644 --- a/lib/agent-skill-diagnostics-route.test.mjs +++ b/lib/agent-skill-diagnostics-route.test.mjs @@ -82,6 +82,9 @@ function wrapper({ alive = true, running = false, advisorSpawned = false } = {}) destroyed: 0, isAlive: () => alive, isRunning: () => running, + // The 503 branch of the agent route reads the frame clock; a stand-in + // session with no run has nothing to report. + silentForMs: () => null, async send(command) { self.sent.push(command); return reply; @@ -150,3 +153,47 @@ test("an ordinary command for the same saved session still starts omp", async (t assert.equal(launches(), 1, `a session-owning command resumes omp (response ${response.status}: ${text})`); assert.notEqual(response.status, 409); }); + +test("GET answers 503 session_slow when omp does not answer the state poll in time", async (t) => { + // A busy child is not a dead one: the poll must tell clients to retry, never + // `{running:false}` (which ends the run in their UI). + // The routes import through the `@/` alias, which jiti instantiates separately + // from a relative path; the exact class identity is what the route checks. + const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + const slow = wrapper(); + slow.send = async () => { + throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + }; + useRegistry(t, { [SAVED_ID]: slow }); + + const response = await agentRoute.GET( + new Request(`http://localhost/api/agent/${SAVED_ID}`), + { params: Promise.resolve({ id: SAVED_ID }) }, + ); + const body = JSON.parse(await response.text()); + + assert.equal(response.status, 503); + assert.equal(body.code, "session_slow"); + assert.match(body.error, /keeps running/i); + assert.equal(body.running, false, "the slow answer carries the wrapper's run state"); + assert.equal(body.alive, true, "the child itself is alive"); + assert.equal(launches(), 0, "the busy child is not replaced"); +}); + +test("GET reports an idle live child as not running but alive", async (t) => { + // The fresh-spawn case from the report: omp is alive and answers get_state + // with nothing running, so the answer must not claim a run. + const idle = wrapper({ alive: true, running: false }); + useRegistry(t, { [SAVED_ID]: idle }); + + const response = await agentRoute.GET( + new Request(`http://localhost/api/agent/${SAVED_ID}`), + { params: Promise.resolve({ id: SAVED_ID }) }, + ); + const body = JSON.parse(await response.text()); + + assert.equal(response.status, 200); + assert.equal(body.running, false, "no run in flight"); + assert.equal(body.alive, true, "the child is still there"); + assert.equal(launches(), 0, "reading the state never spawns"); +}); diff --git a/lib/i18n-exit-notice.test.mjs b/lib/i18n-exit-notice.test.mjs new file mode 100644 index 000000000..d972724d1 --- /dev/null +++ b/lib/i18n-exit-notice.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tryNative: false, tsconfigPaths: true }); +const { formatExitedSessionNotice, setLocale } = await jiti.import("./i18n/index.tsx"); + +// getLocale() falls back to "en" during SSR; a minimal document lets the test +// switch locales the same way the settings dialog does in the browser. +globalThis.document = { documentElement: {} }; + +const exit = (detail) => ({ id: "s1", cwd: "/tmp", at: 0, code: null, signal: null, detail }); + +test("a stalled exit gets its own localized sentence instead of the sentinel", () => { + try { + setLocale("en"); + assert.equal( + formatExitedSessionNotice(exit("stalled")), + "The agent stopped responding and was stopped.", + ); + assert.doesNotMatch(formatExitedSessionNotice(exit("stalled")), /stalled/); + + // Every other detail keeps the normal exit explanation. + assert.equal( + formatExitedSessionNotice(exit("signal 9")), + "Agent process exited unexpectedly (code unknown: signal 9)", + ); + + setLocale("ja"); + assert.equal( + formatExitedSessionNotice(exit("stalled")), + "エージェントが応答しなくなったため停止しました。", + ); + + setLocale("zh-CN"); + assert.equal( + formatExitedSessionNotice(exit("stalled")), + "智能体停止响应,已被停止。", + ); + } finally { + setLocale("en"); + delete globalThis.document; + } +}); diff --git a/lib/i18n/index.tsx b/lib/i18n/index.tsx index f38589499..0e71b2774 100644 --- a/lib/i18n/index.tsx +++ b/lib/i18n/index.tsx @@ -94,6 +94,9 @@ export function translate(key: string, vars?: Record): /** Localized user-facing explanation for a retained unexpected process exit. */ export function formatExitedSessionNotice(exit: ExitedRpcSession): string { + // `detail: "stalled"` is the liveness watchdog's internal sentinel, not an + // exit reason: never show it as plain text next to "code unknown". + if (exit.detail === "stalled") return translate("sessionSidebar.agentStalled"); const status = exit.signal ? translate("sessionSidebar.exitSignal", { signal: exit.signal }) : translate("sessionSidebar.exitCode", { diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 1ad043f14..3a563c34c 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "Reloaded session resources", "agentSession.responseFailed": "The agent stopped without returning a response. Please retry and check the provider configuration if this continues.", "agentSession.sendFailed": "Failed to send message: {detail}", + "agentSession.maybeStarted": "omp is busy — your message may still be running.", + "agentSession.abortUnconfirmed": "The stop is not confirmed yet — omp is busy and the run may still be going. The session keeps running.", "agentSession.sessionRenamed": "Session renamed to {name}", "agentSession.shellSessionFailed": "Unable to create a session for the shell command", "agentSession.queuedPromotionUnavailable": "The queued follow-up is no longer available to steer.", @@ -583,6 +585,7 @@ "chatWindow.scrollToBottom": "Return to latest message", "chatWindow.submit": "Submit", "chatWindow.next": "Next", + "chatWindow.agentSilent": "no events for {minutes} min", "chatWindow.askTitle": "Questions from the agent", "chatWindow.askRecommended": "Recommended", "chatWindow.askOther": "Other: type your own answer", @@ -734,6 +737,7 @@ "errors.session_no_messages_to_name": "The session has no user messages to name", "errors.session_not_found": "Session not found", "errors.session_restarting": "This session is restarting — retry in a moment.", + "errors.session_slow": "The agent is busy and did not answer in time. It is still running — try again in a moment.", "errors.skill_install_failed": "Install failed", "errors.skill_not_installed": "Installed skill not found", "errors.skill_update_unsupported": "This skill cannot be updated automatically", @@ -1145,6 +1149,7 @@ "projects.showMoreSessions": "Show {count} more", "projects.unread": "Unread", "sessionSidebar.agentExited": "Agent process exited unexpectedly ({reason})", + "sessionSidebar.agentStalled": "The agent stopped responding and was stopped.", "sessionSidebar.exitCode": "code {code}", "sessionSidebar.exitSignal": "signal {signal}", "sessionSidebar.exitUnknown": "unknown", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..d8670869d 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "セッションリソースを再読み込みしました", "agentSession.responseFailed": "エージェントが応答を返さずに停止しました。もう一度お試しください。続く場合はプロバイダー設定を確認してください。", "agentSession.sendFailed": "メッセージの送信に失敗しました: {detail}", + "agentSession.maybeStarted": "omp は処理中です。メッセージはまだ実行されている可能性があります。", + "agentSession.abortUnconfirmed": "停止はまだ確認されていません。omp は処理中で、実行が続いている可能性があります。セッションは動作を続けます。", "agentSession.sessionRenamed": "セッション名を {name} に変更しました", "agentSession.shellSessionFailed": "シェルコマンド用のセッションを作成できませんでした", "agentSession.queuedPromotionUnavailable": "このフォローアップはキューに存在しないため、ステアリングに変更できません。", @@ -566,6 +568,7 @@ "chatWindow.scrollToBottom": "最新メッセージに戻る", "chatWindow.submit": "送信", "chatWindow.next": "次へ", + "chatWindow.agentSilent": "{minutes} 分間イベントなし", "chatWindow.askTitle": "エージェントからの質問", "chatWindow.askRecommended": "推奨", "chatWindow.askOther": "その他:自由に回答を入力", @@ -717,6 +720,7 @@ "errors.session_no_messages_to_name": "セッションに名前を付けるためのユーザーメッセージがありません", "errors.session_not_found": "セッションが見つかりません", "errors.session_restarting": "このセッションは再起動中です。しばらくしてから再試行してください。", + "errors.session_slow": "エージェントは処理中で時間内に応答しませんでした。実行は続いています。しばらくしてから再試行してください。", "errors.skill_install_failed": "インストールに失敗しました", "errors.skill_not_installed": "インストール済みのスキルが見つかりません", "errors.skill_update_unsupported": "このスキルは自動更新できません", @@ -1106,6 +1110,7 @@ "projects.showMoreSessions": "さらに{count}件を表示", "projects.unread": "未読", "sessionSidebar.agentExited": "エージェントプロセスが異常終了しました({reason})", + "sessionSidebar.agentStalled": "エージェントが応答しなくなったため停止しました。", "sessionSidebar.exitCode": "終了コード {code}", "sessionSidebar.exitSignal": "シグナル {signal}", "sessionSidebar.exitUnknown": "不明", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..451b509b9 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "已重新加载会话资源", "agentSession.responseFailed": "智能体在未返回响应的情况下停止了。请重试;如果问题持续,请检查提供商配置。", "agentSession.sendFailed": "发送消息失败:{detail}", + "agentSession.maybeStarted": "omp 正忙——你的消息可能仍在运行中。", + "agentSession.abortUnconfirmed": "停止尚未确认——omp 正忙,运行可能仍在继续。会话仍在运行。", "agentSession.sessionRenamed": "会话已重命名为 {name}", "agentSession.shellSessionFailed": "无法为 shell 命令创建会话", "agentSession.queuedPromotionUnavailable": "该后续消息已不在队列中,无法转为引导消息。", @@ -566,6 +568,7 @@ "chatWindow.scrollToBottom": "返回最新消息", "chatWindow.submit": "提交", "chatWindow.next": "下一题", + "chatWindow.agentSilent": "已 {minutes} 分钟无事件", "chatWindow.askTitle": "来自智能体的问题", "chatWindow.askRecommended": "推荐", "chatWindow.askOther": "其他:输入你自己的答案", @@ -717,6 +720,7 @@ "errors.session_no_messages_to_name": "会话没有可用于命名的用户消息", "errors.session_not_found": "未找到会话", "errors.session_restarting": "该会话正在重启,请稍后重试。", + "errors.session_slow": "代理正忙,未能及时响应。它仍在运行,请稍后重试。", "errors.skill_install_failed": "安装失败", "errors.skill_not_installed": "未找到已安装的技能", "errors.skill_update_unsupported": "此技能无法自动更新", @@ -1106,6 +1110,7 @@ "projects.showMoreSessions": "再显示 {count} 个", "projects.unread": "未读", "sessionSidebar.agentExited": "智能体进程异常退出({reason})", + "sessionSidebar.agentStalled": "智能体停止响应,已被停止。", "sessionSidebar.exitCode": "退出代码 {code}", "sessionSidebar.exitSignal": "信号 {signal}", "sessionSidebar.exitUnknown": "未知", diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index 39f566e7e..96013730a 100644 --- a/lib/instrumentation-crash-policy.test.mjs +++ b/lib/instrumentation-crash-policy.test.mjs @@ -16,10 +16,10 @@ const readOrEmpty = (file) => { } }; -// 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" } = {}) { +// Runs instrumentation.node.ts's register() in a child, then executes [body]. +// Returns the exit status (0 = kept serving) plus the journals under the agent +// dir and under ~/.omp (the default, un-isolated location). +function runAfterRegister(body, { agentDir = "agent", keepAliveMs = 300 } = {}) { const home = mkdtempSync(join(tmpdir(), "omp-web-crash-policy-")); try { const script = ` @@ -27,8 +27,8 @@ function throwAfterRegister(errorExpr, { agentDir = "agent" } = {}) { 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); + ${body} + setTimeout(() => process.exit(0), ${keepAliveMs}); `; const result = spawnSync(process.execPath, ["--input-type=module", "-e", script], { cwd: root, @@ -53,6 +53,16 @@ function throwAfterRegister(errorExpr, { agentDir = "agent" } = {}) { } } +/** register(), then throw [errorExpr] uncaught. */ +function throwAfterRegister(errorExpr, options = {}) { + return runAfterRegister(`setTimeout(() => { throw ${errorExpr}; }, 0);`, options); +} + +/** register(), then reject a promise nobody awaits (a fire-and-forget chain). */ +function rejectAfterRegister(errorExpr, options = {}) { + return runAfterRegister(`Promise.reject(${errorExpr});`, options); +} + 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); @@ -69,7 +79,7 @@ test("the journal follows an isolated agent dir and keeps ~/.omp/omp-web by defa assert.match(byDefault.homeJournal, /\[crash\] uncaughtException Error: boom/); }); -test("any other uncaught exception still exits with code 2", () => { +test("any other uncaught exception still exits with code 2 and says so on stderr", () => { for (const errorExpr of [ `new Error("boom")`, `Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" })`, @@ -81,5 +91,30 @@ test("any other uncaught exception still exits with code 2", () => { const { status, journal, stderr } = throwAfterRegister(errorExpr); assert.equal(status, 2, `${errorExpr}\n${stderr}`); assert.match(journal, /\[crash\] uncaughtException/, errorExpr); + assert.match(stderr, /uncaught exception — exiting/, `${errorExpr} must be readable in the autostart log`); + } +}); + +test("an unhandled rejection is journaled and logged, and the server keeps serving", () => { + // A fire-and-forget chain (a background tick, an unawaited route helper) + // rejects: nobody awaited it, so every request path is still intact and the + // process must not die — the scheduled task does not restart a server that + // exits on its own. + for (const errorExpr of [`new Error("tick failed")`, `"plain string reason"`, `undefined`]) { + const { status, journal, stderr } = rejectAfterRegister(errorExpr); + assert.equal(status, 0, `${errorExpr} must not end the process\n${stderr}`); + assert.match(journal, /\[rejection\] unhandledRejection/, errorExpr); + assert.doesNotMatch(journal, /\[crash\]/, `${errorExpr} is not an uncaught exception`); + assert.match(stderr, /unhandled rejection \(server keeps running\)/, `${errorExpr} must be readable in the autostart log`); } }); + +test("repeated rejections stay rate-limited in the console but always reach the journal", () => { + // A tick that rejects once a second must not bury the record: the journal + // keeps every rejection, the console at most ten a minute. + const body = `for (let i = 0; i < 14; i += 1) Promise.reject(new Error("tick " + i));`; + const { status, journal, stderr } = runAfterRegister(body); + assert.equal(status, 0, stderr); + assert.equal(journal.match(/\[rejection\] unhandledRejection/g)?.length, 14, "every rejection is journaled"); + assert.equal(stderr.match(/unhandled rejection \(server keeps running\)/g)?.length, 10, "the console copy is capped"); +}); diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 47c5be6ff..2915655cb 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -193,8 +193,8 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { t.mock.timers.tick(5_000); await new Promise((resolve) => setImmediate(resolve)); - assert.equal(mutationError?.name, "RpcCommandTimeoutError", "a hung queue mutation must reject within five seconds"); - assert.equal(mutationError.command, type); + assert.equal(mutationError?.name, "WebRpcError", "a hung queue mutation must reject within five seconds"); + assert.equal(mutationError?.code, "session_slow", "the wrapper reports a busy session, not a raw 500"); assert.equal(wrapper.isAlive(), true, "queue timeout must not kill unrelated work"); assert.equal(loginSettled, false); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 5c4c545bf..cc810e619 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -212,6 +212,11 @@ export class RpcProcess { return !this.exited; } + /** The omp child's OS pid; undefined before spawn resolved or after exit. */ + get pid(): number | undefined { + return this.child.pid; + } + get exitDetails(): { code: number | null; signal: NodeJS.Signals | null; stderrTail: string } | null { return this.exitInfo ? { ...this.exitInfo, stderrTail: this.stderrTail } : null; } @@ -244,10 +249,12 @@ export class RpcProcess { /** Send a command and await its response `data`. A failed response rejects * with RpcCommandError. No timeout by default — some commands (login, - * long prompts via bash) legitimately take minutes, and the session wrapper - * reclaims wedged children via idle-kill and dispose(). Callers that want a - * cap pass `timeoutMs` (>0); when set, the timer is unref'd so it never - * keeps the event loop alive on its own. */ + * long prompts via bash) legitimately take minutes. A timeout never disposes + * the child: the caller's wrapper turns it into `session_slow`, and a child + * only dies on process exit, the disconnect reaper (abandoned sessions) or + * the stall watchdog for a child with no evidence of life for minutes. + * Callers that want a cap pass `timeoutMs` (>0); when set, the timer is + * unref'd so it never keeps the event loop alive on its own. */ sendCommand(command: { type: string; [key: string]: unknown }, timeoutMs?: number): Promise { if (this.exited) { return Promise.reject(new Error("omp RPC process has exited")); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index f3a7dca25..c76ae55d9 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -116,6 +116,12 @@ export interface WebSessionState { isPromptRunning: boolean; isBashRunning: boolean; isCompacting: boolean; + /** Milliseconds since the child's last frame while a run is marked; `null` + * when nothing runs (or before the first frame). `get_state` answers come + * from omp's event loop, so a wedged run can keep answering polls for hours + * without emitting a single frame — this is what clients show next to the + * phase instead of an unqualified "Thinking…". */ + silentForMs?: number | null; /** Web-observed current-run response; not a persisted-history cursor. */ responseObserved?: boolean; autoCompactionEnabled: boolean; diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index a153e829d..b439077f5 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -298,6 +298,38 @@ test("a prompt or steer during a `!!` shell command degrades into the follow-up assert.equal(commands.at(-1).type, "prompt"); }); +test("a queue-while-shell-running ack timeout reports maybeStarted instead of a lost message", async (t) => { + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + let releaseBash; + const bashGate = new Promise((resolve) => { releaseBash = resolve; }); + const { wrapper } = snapshotSession(t, async (command, timeoutMs) => { + if (command.type === "bash") { + await bashGate; + return {}; + } + if (command.type === "follow_up") throw new RpcCommandTimeoutError(command.type, timeoutMs); + return {}; + }); + + const bash = wrapper.send({ type: "bash", command: "npm run build" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(wrapper.isRunning(), true, "the shell command owns the session"); + + // The follow_up frame is written before the ack: reporting "not sent" made + // the client restore the text and send the same instruction twice. + await assert.rejects(wrapper.send({ type: "prompt", message: "run the tests" }), (err) => { + assert.equal(err.code, "session_slow"); + assert.deepEqual(err.details, { maybeStarted: true }); + return true; + }); + assert.equal(wrapper.isAlive(), true, "a slow ack never disposes the shell session"); + + releaseBash(); + await bash; + assert.equal(wrapper.isRunning(), false); +}); + test("auto-compaction results carry the same estimatedTokensAfter as manual compact", async () => { const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); const autoCase = source.slice( @@ -311,15 +343,14 @@ test("auto-compaction results carry the same estimatedTokensAfter as manual comp }); -test("resolveSpawnCwd uses the recorded directory when it exists, falls back otherwise", async () => { +test("resolveSpawnCwdResult uses the recorded directory when it exists, falls back otherwise", async () => { const { createJiti } = await import("jiti"); const jiti = createJiti(import.meta.url); - const { resolveSpawnCwd, resolveSpawnCwdResult } = jiti("./rpc-manager.ts"); + const { resolveSpawnCwdResult } = jiti("./rpc-manager.ts"); const { existsSync } = await import("node:fs"); // A live recorded cwd is used verbatim — no fallback. const live = process.cwd(); - assert.equal(resolveSpawnCwd(live), live); assert.deepEqual(resolveSpawnCwdResult(live), { cwd: live, fellBack: false }); // A missing recorded cwd falls back to a live directory and reports it. @@ -328,14 +359,44 @@ test("resolveSpawnCwd uses the recorded directory when it exists, falls back oth assert.equal(result.fellBack, true); assert.ok(existsSync(result.cwd), "fallback cwd must exist on disk"); - // The second-tier fallback is process.cwd() (which exists in normal environments); - // resolveSpawnCwd (string return) matches the result's cwd. + // The second-tier fallback is process.cwd() (which exists in normal environments). assert.equal(result.cwd, process.cwd()); - assert.equal(resolveSpawnCwd(missing), process.cwd()); // undefined/empty also falls back. assert.equal(resolveSpawnCwdResult(undefined).fellBack, true); - assert.equal(resolveSpawnCwd(undefined), process.cwd()); + assert.equal(resolveSpawnCwdResult(undefined).cwd, process.cwd()); +}); + +test("invalid millisecond env values keep the default instead of disabling the watchdog", async () => { + const { readNonNegativeMs } = await runtimeJiti.import("./rpc-manager.ts"); + const name = "OMP_WEB_READ_NON_NEGATIVE_MS_TEST"; + const previous = process.env[name]; + const warnings = []; + const originalWarn = console.warn; + console.warn = (...args) => warnings.push(args.join(" ")); + try { + delete process.env[name]; + assert.equal(readNonNegativeMs(name, 120_000), 120_000, "unset keeps the default"); + + process.env[name] = "0"; + assert.equal(readNonNegativeMs(name, 120_000), 0, "0 still means off"); + + process.env[name] = "2500"; + assert.equal(readNonNegativeMs(name, 120_000), 2500); + + // A typo or a human unit used to evaluate to 0 via `Number(...) || 0`, + // which silently disabled the stall watchdog. + for (const invalid of ["5m", "-1", "", " ", "Infinity", "abc"]) { + process.env[name] = invalid; + assert.equal(readNonNegativeMs(name, 120_000), 120_000, `"${invalid}" keeps the default`); + } + assert.equal(warnings.length, 6, "every rejected value is reported once"); + assert.match(warnings[0], /OMP_WEB_READ_NON_NEGATIVE_MS_TEST/); + } finally { + console.warn = originalWarn; + if (previous === undefined) delete process.env[name]; + else process.env[name] = previous; + } }); test("missing terminal agent_end clears isPromptRunning on raw idle get_state", async () => { @@ -498,7 +559,7 @@ test("abort_and_prompt images go through the same server-side validation as prom await wrapper.destroyAndWait(); }); -test("get_state timeout preserves the process and reports a transient status error", async () => { +test("get_state timeout keeps the child alive and produces a session_slow WebRpcError", async () => { const { createJiti } = await import("jiti"); const jiti = createJiti(import.meta.url); const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); @@ -526,13 +587,16 @@ test("get_state timeout preserves the process and reports a transient status err wrapper.send({ type: "get_state" }), (err) => { assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_state_timeout"); + // Busy, not dead: omp blocks its event loop for tens of seconds on big + // sessions, so a slow answer must never recycle a live child. + assert.equal(err.code, "session_slow"); return true; }, ); - assert.equal(disposed, false); - assert.equal(wrapper.isAlive(), true); + assert.equal(disposed, false, "a slow get_state never disposes the child"); + assert.equal(wrapper.isAlive(), true, "the child (and its run) keeps living"); + assert.equal(wrapper.isRunning(), false, "the timed-out poll leaves no busy flag behind"); await wrapper.destroyAndWait(); }); @@ -549,7 +613,7 @@ test("a running task survives a slow status query and later state reads recover" const dispose = wrapper.proc.dispose; wrapper.proc.dispose = async () => { disposed = true; return dispose(); }; emit({ type: "agent_start" }); - await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_state_timeout" }); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); assert.equal(disposed, false, "a read-only poll must never stop generation"); assert.equal(wrapper.isRunning(), true); const state = await wrapper.send({ type: "get_state" }); @@ -560,36 +624,354 @@ test("a running task survives a slow status query and later state reads recover" assert.equal(wrapper.isAlive(), true); }); -test("prompt ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); +test("a command timeout before STALL_DESTROY_MS never disposes the child", async () => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); - t.mock.timers.enable({ apis: ["setTimeout"] }); - let acceptedPrompt = null; - let disposed = false; - let removedFromRegistry = false; + let disposed = 0; const fakeProc = { isAlive: true, onFrame: () => () => {}, - sendCommand: (command, timeoutMs) => { - if (command.type !== "prompt") return Promise.resolve({}); - acceptedPrompt = command; - // Model execution is not timed here. This promise represents only the - // transport response to the accepted prompt frame. - assert.equal(timeoutMs, 30000); - return new Promise((_, reject) => { - setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); - }); + sendCommand: async (command, timeoutMs) => { + throw new RpcCommandTimeoutError(command.type, timeoutMs); }, sendFrame: () => {}, - dispose: async () => { disposed = true; }, + dispose: async () => { disposed += 1; }, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "fresh-timeout"); + wrapper.start(); + const realNow = Date.now; + const offset = 4 * 60_000; // under the 5 min stall window + Date.now = () => realNow() + offset; + try { + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.equal(disposed, 0, "four silent minutes are still just a busy child"); + assert.equal(wrapper.isAlive(), true); + } finally { + Date.now = realNow; + await wrapper.destroyAndWait(); + } +}); + +test("a child that stays silent past STALL_DESTROY_MS is disposed as stalled on the next timeout", async (t) => { + const { AgentSessionWrapper, getExitedRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + globalThis.__ompExitedSessions = new Map(); + t.after(() => { delete globalThis.__ompExitedSessions; }); + + let disposed = 0; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: async (command, timeoutMs) => { + throw new RpcCommandTimeoutError(command.type, timeoutMs); + }, + sendFrame: () => {}, + dispose: async () => { disposed += 1; }, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "stalled-session"); + wrapper.start(); + const realNow = Date.now; + let offset = 0; + Date.now = () => realNow() + offset; + try { + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.equal(disposed, 0, "the first timeout alone is not evidence of a wedge"); + + // No frame, no successful answer for the whole stall window. + offset = 5 * 60_000; + await assert.rejects(wrapper.send({ type: "get_state" }), (err) => { + assert.equal(err.code, "session_slow", "the request still reports omp as busy"); + return true; + }); + assert.equal(disposed, 1, "the stalled child is disposed through the regular exit path"); + assert.equal(wrapper.isAlive(), false); + const exited = getExitedRpcSession("stalled-session"); + assert.equal(exited?.detail, "stalled"); + assert.equal(exited?.code, null); + assert.equal(exited?.signal, null); + } finally { + Date.now = realNow; + } +}); + +test("a stalled child's prompt timeout is a definite failure, not maybeStarted", async () => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + let disposed = 0; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: async (command, timeoutMs) => { + throw new RpcCommandTimeoutError(command.type, timeoutMs); + }, + sendFrame: () => {}, + dispose: async () => { disposed += 1; }, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "stalled-prompt"); + wrapper.start(); + const realNow = Date.now; + Date.now = () => realNow() + 5 * 60_000; + try { + // The watchdog disposes the child, which drops the queued frame: the prompt + // never ran, so the client must roll back and recover its text instead of + // showing "may still be running" for a dead session. + await assert.rejects(wrapper.send({ type: "prompt", message: "Hello" }), (err) => { + assert.equal(err.code, "session_slow"); + assert.equal(err.details, undefined, "a disposed child cannot have started the prompt"); + return true; + }); + assert.equal(disposed, 1); + assert.equal(wrapper.isAlive(), false); + assert.equal(wrapper.isRunning(), false, "no run flag survives the disposal"); + } finally { + Date.now = realNow; + } +}); + +test("a run that keeps answering polls but sends no frames reports how long it has been silent", async (t) => { + // The 2026-10-28 nmapkiller incident: omp ended its turn at 12:40 and then + // kept answering `get_state` while nothing ran any more — no frames for + // hours. Every answer moved `lastEvidenceAt`, so the stall watchdog never + // fired and neither the sidebar nor the composer had a reason to doubt + // "working". `silentForMs` is the *frame* clock clients can show instead. + // What the child itself reports; a wedged run keeps claiming streaming. + let childStreaming = true; + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type !== "get_state") return {}; + return { sessionId: "silent-run", sessionFile: "", isStreaming: childStreaming, isCompacting: false }; + }, SnapshotWrapper, "silent-run"); + + assert.equal((await wrapper.send({ type: "get_state" })).silentForMs, null, "an idle session reports no silence"); + + emit({ type: "agent_start" }); + const realNow = Date.now; + let offset = 0; + Date.now = () => realNow() + offset; + try { + const started = (await wrapper.send({ type: "get_state" })).silentForMs; + assert.ok(started !== null && started < 100, `the frame that marked the run is the clock's zero, got ${started}`); + + // Two hours 44 minutes of silence — the observed phantom — while polls keep + // answering. A poll answer is not a frame and must not move the clock. + offset = 164 * 60_000; + const silent = (await wrapper.send({ type: "get_state" })).silentForMs; + assert.ok(silent !== null && Math.abs(silent - offset) < 100, `silence must keep counting, got ${silent}`); + const exposure = wrapper.silentForMs(); + assert.ok(exposure !== null && Math.abs(exposure - offset) < 100, `the accessor the 503 routes serve must match, got ${exposure}`); + + emit({ type: "message_update", message: { id: "m1", content: "again" } }); + const reset = (await wrapper.send({ type: "get_state" })).silentForMs; + assert.ok(reset !== null && reset < 100, `a frame resets the clock, got ${reset}`); + } finally { + Date.now = realNow; + } + + // The run ends: omp reports not streaming, no run is marked, no silence. + childStreaming = false; + emit({ type: "agent_end", isTerminal: true }); + assert.equal((await wrapper.send({ type: "get_state" })).silentForMs, null, "an ended run reports no silence"); +}); + +test("a fresh run after a long idle does not inherit the previous run's silence", async (t) => { + // After a run ends its last frame stays in `lastFrameAt`. The next prompt is + // marked immediately, but its first frame arrives later; without a clamp the + // first state sample would report the old run's hours as this one's silence. + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type !== "get_state") return {}; + return { sessionId: "idle-gap", sessionFile: "", isStreaming: false, isCompacting: false }; + }, SnapshotWrapper, "idle-gap"); + + await wrapper.send({ type: "get_state" }); + emit({ type: "agent_start" }); + emit({ type: "agent_end", isTerminal: true }); + + const realNow = Date.now; + let offset = 0; + Date.now = () => realNow() + offset; + try { + offset = 120 * 60_000; + await wrapper.send({ type: "prompt", message: "Hello" }); + const silent = (await wrapper.send({ type: "get_state" })).silentForMs; + assert.ok(silent !== null && silent < 100, `the new run starts its own clock, got ${silent}`); + } finally { + Date.now = realNow; + } +}); + +test("a child that answers just under each timeout is never disposed as stalled", async () => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + + let disposed = 0; + let offset = 0; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: async (_command, timeoutMs) => { + assert.equal(timeoutMs, 5000); + // Each answer lands 4s into the 5s window: slow, but alive. + offset += 4000; + return { sessionId: "alive-session", isStreaming: false, isCompacting: false }; + }, + sendFrame: () => {}, + dispose: async () => { disposed += 1; }, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "alive-session"); + wrapper.start(); + const realNow = Date.now; + Date.now = () => realNow() + offset; + try { + for (let i = 0; i < 100; i += 1) { + const state = await wrapper.send({ type: "get_state" }); + assert.equal(state.isPromptRunning, false); + } + assert.ok(offset > 5 * 60_000, "the whole test outlives the stall window"); + assert.equal(disposed, 0, "successful answers keep the child demonstrably alive"); + assert.equal(wrapper.isAlive(), true); + } finally { + Date.now = realNow; + await wrapper.destroyAndWait(); + } +}); + +test("control and passthrough commands time out as session_slow without disposing", async () => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + let disposed = 0; + const timeouts = {}; + const details = {}; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: async (command, timeoutMs) => { + timeouts[command.type] = timeoutMs; + throw new RpcCommandTimeoutError(command.type, timeoutMs); + }, + sendFrame: () => {}, + dispose: async () => { disposed += 1; }, }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + wrapper.start(); + try { + // Every command that used to wait forever is bounded and reports "busy". + for (const command of [ + { type: "steer", message: "focus" }, + { type: "follow_up", message: "later" }, + { type: "set_session_name", name: "name" }, + { type: "set_host_tools", tools: [] }, + { type: "set_host_uri_schemes", schemes: [] }, + { type: "remove_queued_message", id: "q1" }, + { type: "promote_queued_message", id: "q1" }, + { type: "get_skill_diagnostics" }, + { type: "set_skill_startup_diagnostics", enabled: false }, + { type: "set_thinking_level", level: "high" }, + { type: "set_model", provider: "prov", modelId: "model" }, + { type: "set_fast_mode", enabled: true }, + { type: "set_slow_mode", enabled: true }, + { type: "get_session_stats" }, + { type: "get_last_assistant_text" }, + { type: "get_commands" }, + { type: "new_session" }, + { type: "switch_session", sessionId: "other" }, + { type: "abort_and_prompt", message: "next" }, + ]) { + await assert.rejects(wrapper.send(command), (err) => { + assert.equal(err.code, "session_slow", `${command.type} is bounded`); + details[command.type] = err.details; + return true; + }); + } + + // The frames are written before the ack: steer/follow-up/abort_and_prompt + // say "may already be in omp", the abort says "unconfirmed", and a poll or + // a setter says nothing it cannot know. + for (const type of ["steer", "follow_up", "abort_and_prompt"]) { + assert.deepEqual(details[type], { maybeStarted: true }, `${type} keeps the message`); + } + await assert.rejects(wrapper.send({ type: "abort" }), (err) => { + assert.equal(err.code, "session_slow"); + assert.equal(err.details?.abortUnconfirmed, true); + return true; + }); + await assert.rejects(wrapper.send({ type: "get_state" }), (err) => { + assert.equal(err.details, undefined, "a poll carries no delivery claim"); + return true; + }); + assert.equal(timeouts.steer, 30000); + assert.equal(timeouts.follow_up, 30000); + assert.equal(timeouts.set_session_name, 5000); + assert.equal(timeouts.set_host_tools, 5000); + assert.equal(timeouts.set_host_uri_schemes, 5000); + assert.equal(timeouts.remove_queued_message, 5000); + assert.equal(timeouts.promote_queued_message, 5000); + assert.equal(timeouts.get_skill_diagnostics, 5000); + assert.equal(timeouts.set_skill_startup_diagnostics, 5000); + assert.equal(timeouts.set_thinking_level, 5000); + assert.equal(timeouts.set_model, 5000); + assert.equal(timeouts.set_fast_mode, 5000); + assert.equal(timeouts.set_slow_mode, 5000); + assert.equal(timeouts.get_session_stats, 5000); + assert.equal(timeouts.get_last_assistant_text, 5000); + assert.equal(timeouts.get_available_commands, 5000); + assert.equal(timeouts.new_session, 30000); + assert.equal(timeouts.switch_session, 30000); + assert.equal(timeouts.abort_and_prompt, 30000); + assert.equal(timeouts.get_state, 5000); + assert.equal(timeouts.abort, 30000); + assert.equal(disposed, 0, "bounded timeouts never dispose a live child"); + assert.equal(wrapper.isAlive(), true); + assert.equal(wrapper.isRunning(), false, "no command leaves a busy flag behind"); + } finally { + await wrapper.destroyAndWait(); + } +}); + +test("more than 32 in-flight commands are refused as session_busy", async () => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + + const pending = []; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: (command) => command.type === "abort" ? Promise.resolve({}) : new Promise((resolve) => pending.push(resolve)), + sendFrame: () => {}, + dispose: async () => {}, + }; const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); - wrapper.onDestroy(() => { removedFromRegistry = true; }); wrapper.start(); + try { + const inflight = []; + for (let i = 0; i < 32; i += 1) inflight.push(wrapper.send({ type: "get_state" })); + await Promise.resolve(); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_busy" }); + // Stop is the only way out of a full queue, so the cap must not swallow it. + assert.equal(await wrapper.send({ type: "abort" }), null, "cancellation still reaches the child at the cap"); + for (const resolve of pending) resolve({ sessionId: "cap", isStreaming: false, isCompacting: false }); + await Promise.all(inflight); + } finally { + await wrapper.destroyAndWait(); + } +}); + +test("prompt ack timeout keeps the child and the optimistic run for maybeStarted", async (t) => { + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + let acceptedPrompt = null; + const { wrapper, emit } = snapshotSession(t, (command, timeoutMs) => { + if (command.type !== "prompt") return Promise.resolve({}); + acceptedPrompt = command; + // Model execution is not timed here. This promise represents only the + // transport response to the accepted prompt frame. + assert.equal(timeoutMs, 30000); + return new Promise((_, reject) => { + setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); + }); + }); const pending = wrapper.send({ type: "prompt", message: "Hello" }); await Promise.resolve(); @@ -599,16 +981,67 @@ test("prompt ack timeout recycles a child that accepts the frame but withholds i await assert.rejects( pending, (err) => { - assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_unresponsive"); + assert.equal(err.code, "session_slow"); + // The frame may already sit in omp's stdin: the client must not treat + // the message as definitely unsent. + assert.deepEqual(err.details, { maybeStarted: true }); return true; }, ); - assert.equal(disposed, true); - assert.equal(removedFromRegistry, true); - assert.equal(wrapper.isAlive(), false); - assert.equal(wrapper.isRunning(), false); + // Busy, not dead: recycling here aborted the run ("Generation stopped by + // user") whenever omp blocked its loop on a large session. + assert.equal(wrapper.isAlive(), true, "the child survives a slow ack"); + assert.equal(wrapper.isRunning(), true, "the run keeps reporting as running (maybe started)"); + assert.equal(wrapper.getStreamSnapshot().isPromptRunning, true); + + // The prompt was accepted, so the run reports through frames — and a frame + // that arrives after the ack timed out must still own the state. + emit({ type: "agent_start" }); + assert.equal(wrapper.isRunning(), true, "a later agent_start still starts the run"); + assert.equal(wrapper.getStreamSnapshot().isStreaming, true); +}); + +test("prompt ack timeout settles only after the awaiting-start deadline", async (t) => { + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + const { wrapper } = snapshotSession(t, (command, timeoutMs) => { + if (command.type === "prompt") { + return new Promise((_, reject) => { + setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); + }); + } + return Promise.resolve({ sessionId: "ack-deadline", isStreaming: false, isCompacting: false }); + }); + + const pending = wrapper.send({ type: "prompt", message: "Hello" }); + await Promise.resolve(); + t.mock.timers.tick(30000); + await assert.rejects(pending, { code: "session_slow" }); + assert.equal(wrapper.isRunning(), true); + + const realNow = Date.now; + try { + // Before the deadline the wrapper keeps claiming the run: a late + // agent_start may still arrive. + Date.now = () => realNow() + 9000; + const early = await wrapper.send({ type: "get_state" }); + assert.equal(early.isPromptRunning, true); + assert.equal(wrapper.isRunning(), true); + + // Past the deadline an idle snapshot settles it. + Date.now = () => realNow() + 11000; + // Without any frame and without this poll: the expired start deadline must + // already clear the gate, or the disconnect reaper can never collect a + // child that acked nothing after a prompt timeout. + assert.equal(wrapper.isRunning(), false, "an overdue agent_start no longer counts as a run"); + const late = await wrapper.send({ type: "get_state" }); + assert.equal(late.isPromptRunning, false); + assert.equal(wrapper.isRunning(), false); + } finally { + Date.now = realNow; + } }); test("getRunningRpcSessions and getRunningRpcSessionIds export running sessions with their originating cwd", async () => { @@ -893,40 +1326,34 @@ test("fresh spawns force a new session when omp resumes the cwd's latest session /if \(!sessionFile && created\.sessionFile && existsSync\(created\.sessionFile\)\) \{\s*\n\s*await created\.send\(\{ type: "new_session" \}\);/, ); // restart(): a sessionless wrapper restarts bare and needs the same guard. + // The handshake command is bounded: an omp that swallows new_session must + // not leave the wrapper `restarting` (and un-reapable) forever. assert.match( source, - /if \(!resumable && this\._sessionFile && existsSync\(this\._sessionFile\)\) \{\s*\n\s*await proc\.sendCommand\(\{ type: "new_session" \}\);/, + /if \(!resumable && this\._sessionFile && existsSync\(this\._sessionFile\)\) \{\s*\n\s*await proc\.sendCommand\(\{ type: "new_session" \}, PROMPT_ACK_TIMEOUT_MS\);/, ); + // The replacement is discarded on any handshake failure, timeout included. + const restartStart = source.indexOf("private async restart()"); + const restartEnd = source.indexOf("notifyRunningChange();", restartStart); + const restartBody = source.slice(restartStart, restartEnd); + assert.match(restartBody, /catch \(error\) \{[\s\S]*?void proc\.dispose\(\);[\s\S]*?this\.destroy\(\);/); }); -test("mcp list ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); +test("mcp list ack timeout keeps the child alive and reports session_slow", async (t) => { + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout"] }); let acceptedFrame = null; - let disposed = false; - const fakeProc = { - isAlive: true, - onFrame: () => () => {}, - sendCommand: (command, timeoutMs) => { - if (command.type !== "prompt") return Promise.resolve({}); - acceptedFrame = command; - // The transport ack of the accepted /mcp list frame — the child takes - // the frame and never answers. - assert.equal(timeoutMs, 30000); - return new Promise((_, reject) => { - setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); - }); - }, - sendFrame: () => {}, - dispose: async () => { disposed = true; }, - }; - - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); - wrapper.start(); + const { wrapper } = snapshotSession(t, (command, timeoutMs) => { + if (command.type !== "prompt") return Promise.resolve({}); + acceptedFrame = command; + // The transport ack of the accepted /mcp list frame — the child takes + // the frame and never answers. + assert.equal(timeoutMs, 30000); + return new Promise((_, reject) => { + setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); + }); + }); const pending = wrapper.getMcpList(); await Promise.resolve(); @@ -936,54 +1363,41 @@ test("mcp list ack timeout recycles a child that accepts the frame but withholds await assert.rejects( pending, (err) => { - assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_unresponsive"); + assert.equal(err.code, "session_slow"); return true; }, ); - assert.equal(disposed, true); - assert.equal(wrapper.isAlive(), false); - assert.equal(wrapper.isRunning(), false); + assert.equal(wrapper.isAlive(), true, "a slow /mcp list never disposes the child"); + assert.equal(wrapper.isRunning(), false, "the waiter is released, the wrapper is not busy"); }); test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout"] }); - const fakeProc = { - isAlive: true, - onFrame: () => () => {}, - sendCommand: (command, timeoutMs) => - command.type === "prompt" - ? new Promise((_, reject) => { - setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); - }) - : Promise.resolve({}), - sendFrame: () => {}, - dispose: async () => {}, - }; - - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); - wrapper.start(); + const { wrapper } = snapshotSession(t, (command, timeoutMs) => + command.type === "prompt" + ? new Promise((_, reject) => { + setTimeout(() => reject(new RpcCommandTimeoutError("prompt", timeoutMs)), timeoutMs); + }) + : Promise.resolve({}), + ); const first = wrapper.getMcpList(); await Promise.resolve(); t.mock.timers.tick(30000); - await assert.rejects(first, { code: "session_unresponsive" }); + await assert.rejects(first, { code: "session_slow" }); - // The wedged wrapper must not report itself busy: without the bounded ack - // the finally block never ran and this second call failed with session_busy. - await assert.rejects( - () => wrapper.getMcpList(), - (err) => { - assert.equal(err.message, "Session is no longer running"); - return true; - }, - ); + // The wrapper must not report itself busy: without the bounded ack the + // finally block never ran and this second call failed with session_busy. + // The child is still alive, so the retry reaches omp again (and times out + // once more) instead of being refused. + const retry = wrapper.getMcpList(); + await Promise.resolve(); + t.mock.timers.tick(30000); + await assert.rejects(retry, { code: "session_slow" }); + assert.equal(wrapper.isAlive(), true); }); test("live snapshots restore quiet partial messages and tools, with ordered event metadata", async (t) => { @@ -1120,6 +1534,34 @@ test("session identity changes invalidate the stream epoch and all prior partial assert.equal(after.responseObserved, false); }); +test("a switch whose ack timed out still rekeys the wrapper when it completes later", async (t) => { + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + let sessionId = "switch-from"; + let acked = false; + const { wrapper } = snapshotSession(t, async (command, timeoutMs) => { + if (command.type === "switch_session" && !acked) { + // omp is blocked writing the session file: the frame is in its stdin, the + // ack does not arrive inside the prompt-ack bound. + throw new RpcCommandTimeoutError("switch_session", timeoutMs); + } + return { sessionId, sessionFile: `/tmp/${sessionId}.jsonl`, isStreaming: false, isCompacting: false }; + }, SnapshotWrapper, "switch-from"); + const changes = []; + wrapper.onIdentityChange((oldId, newId) => changes.push([oldId, newId])); + + await assert.rejects( + wrapper.send({ type: "switch_session", sessionPath: "/tmp/switch-to.jsonl" }), + { code: "session_slow" }, + ); + assert.deepEqual(changes, [], "a missing ack proves nothing about the identity yet"); + + // omp finished the switch after the ack expired: the next state read is the + // first evidence, and the registry must stop routing the old id to it. + sessionId = "switch-to"; + await wrapper.send({ type: "get_state" }); + assert.deepEqual(changes, [["switch-from", "switch-to"]]); +}); + test("reload replaces the native stream epoch and subscribes to replacement events", async (t) => { const previousBin = process.env.OMP_WEB_OMP_BIN; process.env.OMP_WEB_OMP_BIN = process.execPath; @@ -1488,6 +1930,36 @@ test("the reaper never disposes the child under an in-flight command", async (t) assert.equal(disposed.length, 1, "the reap resumes once the command settles"); }); +test("an unacknowledged prompt keeps the child until the stall window expires", async (t) => { + // The ack timed out, so the prompt frame may already sit in omp's stdin and + // run later. `isRunning()` stops counting it after the awaiting-start + // deadline; the disconnect reaper must not destroy the child that early. + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + const { wrapper, disposed } = reapedSession(t, async (command, timeoutMs) => { + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", timeoutMs); + return {}; + }); + const realNow = Date.now; + const sentAt = realNow(); + try { + await assert.rejects(wrapper.send({ type: "prompt", message: "blocked child" }), { code: "session_slow" }); + // Past the 10 s awaiting-start deadline, but only 30 s into the 5 min + // stall window: the prompt may still run. + Date.now = () => sentAt + 30_000; + assert.equal(wrapper.isRunning(), false, "precondition: the awaiting-start deadline has passed"); + await afterWindow(); + assert.deepEqual(disposed, [], "the frame may still run; the reaper waits for the stall window"); + + // No evidence of life for longer than the stall window: the child is wedged + // and the reap resumes. + Date.now = () => sentAt + 6 * 60_000; + await afterWindow(); + assert.equal(disposed.length, 1, "the stall bound still ends a wedged child"); + } finally { + Date.now = realNow; + } +}); + test("a running session is not reaped and is reaped once the run ends", async (t) => { const { wrapper, emit, disposed } = reapedSession(t); emit({ type: "agent_start" }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8e23cee8..d4fa66848 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -69,6 +69,22 @@ interface CompactionResultLike { tokensAfter?: number; } +/** + * Read a millisecond setting without turning a typo into "off": only a finite, + * non-negative number is accepted (`0` keeps its documented "disabled" meaning + * in both consumers). `5m`, `-1` or an empty value used to evaluate to 0 via + * `Number(...) || 0`, which silently disabled the very watchdog that rescues a + * wedged child. Such a value now keeps the default and warns once at startup. + */ +export function readNonNegativeMs(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw === undefined) return fallback; + const parsed = raw.trim() === "" ? Number.NaN : Number(raw); + if (Number.isFinite(parsed) && parsed >= 0) return parsed; + console.warn(`[omp-web] ignoring invalid ${name}="${raw}" (expected milliseconds >= 0); using ${fallback}.`); + return fallback; +} + const IDLE_DESTROY_MS = 10 * 60 * 1000; /** * How long a session may sit with **no web UI attached** before its omp child is @@ -85,19 +101,46 @@ const IDLE_DESTROY_MS = 10 * 60 * 1000; * the idle backstop. Set `OMP_WEB_DISCONNECT_DESTROY_MS=0` to disable reaping * and fall back to IDLE_DESTROY_MS alone. */ -const DISCONNECT_DESTROY_MS = process.env.OMP_WEB_DISCONNECT_DESTROY_MS !== undefined - ? Math.max(0, Number(process.env.OMP_WEB_DISCONNECT_DESTROY_MS) || 0) - : 120_000; +const DISCONNECT_DESTROY_MS = readNonNegativeMs("OMP_WEB_DISCONNECT_DESTROY_MS", 120_000); +/** + * How long a child may go without any positive evidence of life (a frame or a + * successful command answer) before a *timed-out* command is allowed to + * dispose it. omp blocks its event loop for tens of seconds on large sessions, + * so a timeout alone only means "busy"; five minutes of complete silence on a + * child that then misses another answer means wedged. Set + * `OMP_WEB_STALL_DESTROY_MS=0` to disable the watchdog (a stalled child then + * lives until the disconnect reaper or process exit). + */ +const STALL_DESTROY_MS = readNonNegativeMs("OMP_WEB_STALL_DESTROY_MS", 5 * 60_000); +/** Refuse a new command while this many are already awaiting omp. Requests + * cannot pin the wrapper (and the child's stdin) without bound. */ +const MAX_PENDING_COMMANDS = 32; +/** Cancellation must reach the child even at that cap: a full queue is the one + * state from which Stop is the only way out, and `abort`/`abort_bash` settle + * within their own bounds (UNBOUNDED_PASSTHROUGH_COMMANDS never holds these + * slots forever). They still count toward the cap while in flight. */ +const CANCELLATION_COMMANDS = new Set([ + "abort", "abort_and_restore_queue", "abort_bash", "abort_compaction", "abort_retry", +]); const READY_TIMEOUT_MS = 120_000; const MCP_LIST_TIMEOUT_MS = 15_000; +/** Bounds one request's wait for an answer. It says nothing about the child: + * omp blocks its event loop for tens of seconds on large sessions (a 2.8 MB + * transcript answered `get_state` after 49 s), so an expired wait means "busy", + * never "dead" — see `slowSessionError()`. */ const GET_STATE_TIMEOUT_MS = 5_000; /** Cap on the *acknowledgement* of a prompt frame — not on model execution. * omp acks a prompt as soon as it accepts it and the run then reports through - * events (agent_start/agent_end), so an ack that never arrives means the child - * is wedged: without this the API request (and the UI spinner behind it) would - * stay pending forever. Generous enough to cover slow local startup work the - * child does before acking. */ + * events (agent_start/agent_end), so without this bound the API request (and + * the UI spinner behind it) would stay pending for as long as omp is blocked. + * Generous enough to cover slow local startup work the child does before + * acking. */ const PROMPT_ACK_TIMEOUT_MS = 30_000; +/** Stable code for "omp did not answer this command in time". The session keeps + * running; clients answer with HTTP 503 and retry instead of treating the run + * as ended. */ +const SESSION_SLOW_CODE = "session_slow"; +const SESSION_SLOW_MESSAGE = "omp is busy and did not answer in time; the session keeps running."; /** Title generation is an LLM call on omp's side. */ const GENERATE_TITLE_TIMEOUT_MS = 60_000; const RENAME_POLL_INTERVAL_MS = 500; @@ -120,14 +163,42 @@ const BASH_EXCLUDE_MESSAGE = */ export class WebRpcError extends Error { readonly code: string; + /** Extra machine-readable facts the agent route forwards next to `code` + * (`maybeStarted`, `abortUnconfirmed`). */ + readonly details: Record | undefined; - constructor(message: string, code: string) { + constructor(message: string, code: string, details?: Record) { super(message); this.name = "WebRpcError"; this.code = code; + this.details = details; } } +const SESSION_SLOW_MAYBE_STARTED_MESSAGE = + "omp is busy and did not acknowledge the message in time; it may still be running. The session keeps running."; +const SESSION_SLOW_ABORT_UNCONFIRMED_MESSAGE = + "omp is busy and did not answer the abort in time; the abort is not confirmed and the session keeps running."; + +/** A command timeout means omp is busy, not dead. omp blocks its event loop + * for tens of seconds on large sessions, so a missing answer only ends this + * request's wait — the child, and any run it is executing, keeps going and + * keeps reporting through frames. Only the liveness watchdog + * (`destroyIfStalled`) may dispose a child with no evidence of life for + * `STALL_DESTROY_MS`; a mere timeout never does. Recycling a child here killed + * live runs and made omp record a `dispose` ("Generation stopped by user"). */ +function slowSessionError(details?: Record): WebRpcError { + return new WebRpcError( + details?.abortUnconfirmed + ? SESSION_SLOW_ABORT_UNCONFIRMED_MESSAGE + : details?.maybeStarted + ? SESSION_SLOW_MAYBE_STARTED_MESSAGE + : SESSION_SLOW_MESSAGE, + SESSION_SLOW_CODE, + details, + ); +} + /** Shape check for an ask-dialog `answers` payload; omp validates the content. */ function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => @@ -176,6 +247,21 @@ const PASSTHROUGH_COMMANDS = new Set([ // cannot pin the request forever. const PREDICT_WORD_TIMEOUT_MS = 125_000; +// Passthrough commands whose answer legitimately takes minutes and therefore +// stays uncapped, mirroring the explicit switch cases (compact, bash, +// branch/fork). `predict_word` has its own (generous) PREDICT_WORD_TIMEOUT_MS. +// Every other command — including the control commands that used to call +// `sendRpc` without a bound (set_model, set_fast_mode, set_slow_mode, +// get_session_stats, get_last_assistant_text, get_commands, +// new_session/switch_session) — goes through `sendControl`, so a wedged child +// answers `session_slow` instead of pinning the request forever. +const UNBOUNDED_PASSTHROUGH_COMMANDS = new Set([ + "login", // interactive login flow (browser/device code) + "btw", // LLM side question + "handoff", // starts a new session and may run model work + "export_html", // walks the whole transcript +]); + // Commands that can carry user-attached images to the model. All of them must // pass the same server-side per-image/count/aggregate validation before the // payload reaches omp — a client is free to POST any of them directly. @@ -209,7 +295,7 @@ const TOOL_NAME_ALIASES: Record = { find: "glob", search: "grep" const DROPPED_TOOL_NAMES = new Set(["ls"]); /** Translate pi-web preset tool names into omp builtin tool names. */ -export function mapPresetToolNames(toolNames: string[]): string[] { +function mapPresetToolNames(toolNames: string[]): string[] { const out: string[] = []; for (const raw of toolNames) { const lower = raw.toLowerCase(); @@ -265,23 +351,17 @@ function toImageContents(value: unknown): Array<{ type: "image"; data: string; m return images?.length ? images : undefined; } -/** - * Pick a spawn cwd that actually exists. A session records the directory it was - * created in, but that directory may have been deleted since: spawn() would - * fail with ENOENT and `omp --cwd ` throws in setProjectDir. omp's own - * resume path skips the chdir when the recorded project dir is gone and keeps - * the launch cwd (main.ts), so hand it a live directory and let it decide. - */ -export function resolveSpawnCwd(recordedCwd?: string | null): string { - return resolveSpawnCwdResult(recordedCwd).cwd; -} - /** * Resolve a spawn cwd and report whether it differs from the session's recorded - * directory. Callers that surface a UI (the SSE resume paths) use the result to - * emit a notice so the user knows the agent is running somewhere other than the - * directory the sidebar/header still advertises — a silent wrong-tree fallback - * would let file tool calls edit an unexpected repo with no signal. + * directory. A session records the directory it was created in, but that + * directory may have been deleted since: spawn() would fail with ENOENT and + * `omp --cwd ` throws in setProjectDir. omp's own resume path skips + * the chdir when the recorded project dir is gone and keeps the launch cwd + * (main.ts), so hand it a live directory and let it decide. Callers that + * surface a UI (the SSE resume paths) use `fellBack` to emit a notice so the + * user knows the agent is running somewhere other than the directory the + * sidebar/header still advertises — a silent wrong-tree fallback would let + * file tool calls edit an unexpected repo with no signal. */ export function resolveSpawnCwdResult(recordedCwd?: string | null): { cwd: string; fellBack: boolean } { if (recordedCwd && existsSync(recordedCwd)) return { cwd: recordedCwd, fellBack: false }; @@ -356,6 +436,24 @@ export class AgentSessionWrapper { private reapTimer: ReturnType | null = null; private reapDeadline = 0; private lastActivityAt = 0; + /** Last positive evidence that the child's event loop is alive: a frame or a + * successful command answer (an `RpcCommandError` counts too — omp replied). + * Timed-out answers, polls and `send()` writes deliberately do not move it: + * `send()` only feeds the disconnect reaper. Read exclusively by the stall + * watchdog in the command-timeout branches. */ + private lastEvidenceAt = 0; + /** Wall clock of the last *frame* from the child (`handleFrame`, plus the + * handshake and a restart that count as a fresh start). Deliberately not + * `lastEvidenceAt`: a run omp has wedged in an advisor/auto-retry loop keeps + * answering `get_state`, so answers would mask a stream that went silent + * hours ago. Served as `silentForMs` while a run is marked. */ + private lastFrameAt = 0; + /** When the current run was marked locally (prompt dispatch). `silentForMs` + * clamps its base to this: after a long idle the previous run's last frame + * can be hours old, and the new run must not report that inherited silence + * before its own first frame arrives. Frames that mark a run set + * `lastFrameAt` themselves, so this only matters in the start window. */ + private runStartedAt = 0; /** In-flight `send()` calls: the reaper must never dispose the child out from * under a command that is still awaiting its response. */ private pendingCommands = 0; @@ -367,6 +465,10 @@ export class AgentSessionWrapper { /** omp reported a `session-persistence` notice: its next identity change is * the same conversation moving to a sibling file, not a session switch. */ private sessionMovePending = false; + /** A `new_session`/`switch_session` frame was sent but its ack has not + * arrived. It can still switch the child after the ack times out, so the next + * identity change belongs to it and must rekey the registry. */ + private sessionSwitchPending = false; private unsubscribeFrames: (() => void) | null = null; private readonly detectNotification = createNotificationDetector(); /** Agent activity since the last `session_settled`: background work may still run after the turn ended. */ @@ -426,6 +528,7 @@ export class AgentSessionWrapper { this.advisorSpawned = advisorSpawned; this._sessionId = expectedSessionId; this.disconnectDestroyMs = disconnectDestroyMs; + this.lastEvidenceAt = Date.now(); } get sessionId(): string { @@ -436,15 +539,43 @@ export class AgentSessionWrapper { return this._sessionFile; } + /** The omp child's OS pid (undefined if it never spawned or already exited). */ + get pid(): number | undefined { + return this.proc.pid; + } + isAlive(): boolean { return this._alive && this.proc.isAlive; } + /** Milliseconds since the child's last frame while a run is marked; `null` + * when nothing is marked (or before the first frame). The same clock + * `WebSessionState.silentForMs` serves, exposed so a *timed-out* state read + * (503 `session_slow`) can carry it too: a child whose event loop is blocked + * answers no poll, so the 503 is the only moment a client can learn that the + * run it still shows as live has been silent for hours. */ + silentForMs(): number | null { + if (!this.isRunning() || this.lastFrameAt <= 0) return null; + // A fresh run starts its own clock: the previous run's last frame may be + // hours old, and until this run's first frame arrives `lastFrameAt` still + // names that old run. Never report silence older than the run itself. + return Math.max(0, Date.now() - Math.max(this.lastFrameAt, this.runStartedAt)); + } + isRunning(): boolean { + // A prompt waiting for `agent_start` only proves a live run until its + // deadline: a child that acked nothing and sent no frame must become + // reapable again instead of looking busy forever (same deadline + // buildWebState applies, but without needing a get_state). Dispatch-pending + // prompts and real frames keep counting regardless. + const awaitingStartExpired = this.awaitingAgentStart + && Date.now() >= this.awaitingAgentStartDeadline; // A human/host response can outlive the current streaming turn. Reaping it // closes stdin and OMP records "Request was aborted", even without a Stop. - return this.isAlive() && (this.promptRunning || this.streaming || this.compacting || this.bashRunning - || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0 || this.pendingHostUris.size > 0); + return this.isAlive() && (this.streaming || this.compacting || this.bashRunning + || this.promptDispatchPendingCount > 0 + || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0 || this.pendingHostUris.size > 0 + || (this.promptRunning && !awaitingStartExpired)); } /** Local history navigation is busy control work, not an interruptible model turn. */ @@ -452,6 +583,15 @@ export class AgentSessionWrapper { return this.historyEditInFlight; } + /** A prompt this client sent whose ack timed out may still sit in the child's + * stdin. `isRunning()` drops it after the awaiting-start deadline; the + * disconnect reaper must keep the child until the liveness watchdog's own + * silence bound expires, or a message omp would have executed is lost. */ + private promptMayStillRun(): boolean { + if (!this.promptRunning) return false; + return STALL_DESTROY_MS > 0 && Date.now() - this.lastEvidenceAt < STALL_DESTROY_MS; + } + /** A web UI (SSE stream) is currently attached to this session. */ hasSubscribers(): boolean { return this.listeners.length > 0; @@ -492,6 +632,11 @@ export class AgentSessionWrapper { * half-open (the route holds its own detach + heartbeat), so the run would * vanish silently and the tab would only notice via a later 409; * - isRunning() covers an in-flight turn that no listener is watching; + * - an unacknowledged prompt covers the frame that may already sit in the + * child's stdin: `isRunning()` stops counting it after the awaiting-start + * deadline, but destroying the child inside the larger stall window would + * drop a message omp may still execute. `STALL_DESTROY_MS` bounds this, so + * a wedged child is still reaped; * - handshaking covers a spawn that has not finished its startup handshake; * - pendingCommands covers a route command (predict_word, mcp list, export) * whose response the child still owes us; @@ -500,7 +645,7 @@ export class AgentSessionWrapper { */ private reapIfDisconnected(): void { if (!this.isAlive() || this.hasSubscribers() || this.isRunning() - || this.handshaking || this.pendingCommands > 0) { + || this.promptMayStillRun() || this.handshaking || this.pendingCommands > 0) { // A paused human dialog produces no frames. Do not spin a zero-delay // timer once the old deadline has passed while protected work remains. this.reapDeadline = Math.max(this.reapDeadline, Date.now() + this.disconnectDestroyMs); @@ -545,6 +690,7 @@ export class AgentSessionWrapper { start(): void { this.unsubscribeFrames = this.proc.onFrame((frame) => this.handleFrame(frame)); + this.lastEvidenceAt = Date.now(); this.resetIdleTimer(); notifyRunningChange(); } @@ -566,17 +712,18 @@ export class AgentSessionWrapper { await this.proc.negotiateProtocol(ready); // Subscribe to subagent lifecycle/progress/event frames so the UI can show // a live subagent roster. Older omp builds may not know the command — - // degrade silently (the UI falls back to no subagent info). - await this.proc.sendCommand({ type: "set_subagent_subscription", level: "events" }).catch(() => {}); + // degrade silently (the UI falls back to no subagent info). Bounded like + // get_state so a child that never answers cannot stall startup. + await this.sendRpc({ type: "set_subagent_subscription", level: "events" }, GET_STATE_TIMEOUT_MS).catch(() => {}); // Opt into omp's all-questions ask dialog; older omp rejects the command // and keeps the per-question select/editor fallback. // Bounded like get_state so a child that never answers cannot stall startup. - await this.proc.sendCommand({ type: "set_ask_dialog", enabled: true }, GET_STATE_TIMEOUT_MS).catch(() => {}); + await this.sendRpc({ type: "set_ask_dialog", enabled: true }, GET_STATE_TIMEOUT_MS).catch(() => {}); const state = await this.getStateWithTimeout(); this.applyIdentity(state); // Warn when the spawn cwd differs from the session's recorded directory. // This happens when the recorded cwd was deleted (removed worktree, moved - // repo, different machine): resolveSpawnCwd silently substituted a live + // repo, different machine): resolveSpawnCwdResult substituted a live // directory so omp can spawn, but without a notice the user would see the // sidebar/header still advertise the (gone) recorded path while file tool // calls operate on a different tree. @@ -592,6 +739,9 @@ export class AgentSessionWrapper { // The handshake is real activity, so the reap clock restarts from here // rather than from spawn (a slow start must not eat the whole window). this.noteActivity(); + // The child answered ready + get_state: the stall watchdog starts here. + this.lastEvidenceAt = Date.now(); + this.lastFrameAt = this.lastEvidenceAt; } } @@ -628,6 +778,14 @@ export class AgentSessionWrapper { this.onIdentityChangeCallback?.(oldId, this._sessionId, { keepOldId: true }); this.invalidateSessionLists(); } + } else if (identityChanged && this.sessionSwitchPending) { + // The switch frame reached the child after its ack had timed out, and this + // state read is the first evidence. Rekey now, exactly as + // refreshIdentityAfterSessionChange would have: the old id must stop + // routing to the conversation this child now serves. + this.sessionSwitchPending = false; + this.onIdentityChangeCallback?.(oldId, this._sessionId); + this.invalidateSessionLists(); } } @@ -664,7 +822,7 @@ export class AgentSessionWrapper { private async generateSessionTitle(quiet = false): Promise { if (!this.generateTitleUnsupported) { try { - const result = await this.proc.sendCommand({ type: "generate_title" }, GENERATE_TITLE_TIMEOUT_MS); + const result = await this.sendRpc({ type: "generate_title" }, GENERATE_TITLE_TIMEOUT_MS); const title = titleFromResult(result) ?? (await this.readSessionName()); if (title) this.adoptSessionName(title); return title; @@ -736,7 +894,9 @@ export class AgentSessionWrapper { this.sessionMovePending = true; try { const state = await this.getStateWithTimeout(); - if (this._alive) this.applyIdentity(state); + if (this._alive) { + this.applyIdentity(state); + } } catch { // The next get_state-driven refresh still applies the pending move. } finally { @@ -787,6 +947,12 @@ export class AgentSessionWrapper { // even when they arrive after a failed/timed-out edit. if (isSessionEditReply(frame)) return; this.resetIdleTimer(); + // Any frame proves the child's event loop is running (a `ready` frame is + // consumed by waitReady, so this covers runtime frames only). + this.lastEvidenceAt = Date.now(); + // A frame is also the only proof that the *run* is still reporting: the + // stall clock for `silentForMs` starts here, never from a poll answer. + this.lastFrameAt = this.lastEvidenceAt; const event = frame.type === "available_commands_update" && Array.isArray(frame.commands) ? { ...frame, commands: (frame.commands as RpcAvailableSlashCommand[]).filter((command) => command.name !== SESSION_EDIT_COMMAND) } : frame; @@ -1460,8 +1626,10 @@ export class AgentSessionWrapper { // acks it would otherwise suspend this call forever — the `finally` below // would never run and the wrapper would keep reporting itself as busy // (later calls fail with session_busy) until unrelated traffic cleared - // the wedge. The 15s output wait above stays a separate concern. - await this.proc.sendCommand({ type: "prompt", message: action === "list" ? "/mcp list" : `/mcp ${action}${name ? ` ${name}` : ""}` }, PROMPT_ACK_TIMEOUT_MS); + // the wedge. The 15s output wait above stays a separate concern. An + // expired ack leaves the child alone: it is busy, and the run it may be + // executing keeps reporting through frames. + await this.sendRpc({ type: "prompt", message: action === "list" ? "/mcp list" : `/mcp ${action}${name ? ` ${name}` : ""}` }, PROMPT_ACK_TIMEOUT_MS); const result = await output; if (action !== "list" && /^(?:Failed|Usage:|Server .* not found|Unknown)/m.test(result)) { throw new WebRpcError("OMP could not update this MCP server. Check its source configuration.", "mcp_change_failed"); @@ -1478,17 +1646,20 @@ export class AgentSessionWrapper { this.mcpListWaiter = null; waiter.reject( expired - ? new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive") + ? slowSessionError() : error instanceof Error ? error : new Error(String(error)), ); } if (expired) { - // Nothing on this child will ever resolve the waiter; recycle it like - // the prompt-ack timeout path so the next request gets a fresh child. - await this.destroyAndWait(); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); + // Nothing on this child will resolve the waiter; the `finally` releases + // the in-flight flag so the next attempt is not reported as busy. The + // child itself stays unless it has been silent past STALL_DESTROY_MS — + // then the liveness watchdog disposes it; otherwise a later `/mcp list` + // simply retries. + this.destroyIfStalled(); + throw slowSessionError(); } throw error; } finally { @@ -1543,6 +1714,14 @@ export class AgentSessionWrapper { isPromptRunning: this.promptRunning, isBashRunning: this.bashRunning, responseObserved: this.responseObserved, + // How long the child has been without a frame while a run is marked. + // `get_state` is answered from omp's event loop, which keeps turning + // while a wedged run waits in an advisor/auto-retry loop, so the polls + // alone cannot tell a live run from a silent one: this is the only + // signal that can, and clients render it next to the phase so a chat + // that shows "Thinking…" for hours at least says since when. `null` when + // nothing is marked (or before the first child frame). + silentForMs: this.silentForMs(), isCompacting: state.isCompacting, autoCompactionEnabled: state.autoCompactionEnabled, autoRetryEnabled: state.autoRetryEnabled, @@ -1594,13 +1773,17 @@ export class AgentSessionWrapper { } private async getStateWithTimeout(): Promise { - return this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + return this.sendRpc({ type: "get_state" }, GET_STATE_TIMEOUT_MS); } /** After branch/new_session/switch_session the child is on a different * session file — re-read identity and re-register in the registry. */ private async refreshIdentityAfterSessionChange(): Promise { const oldId = this._sessionId; + // This path notifies below for the change it was called for; clear the + // pending switch before the await so a concurrent state read cannot also + // treat it as a late completion. + this.sessionSwitchPending = false; const state = await this.getStateWithTimeout(); this.applyIdentity(state); if (oldId && oldId !== this._sessionId) { @@ -1680,6 +1863,11 @@ export class AgentSessionWrapper { // later mutation race it once the web-side fence is released. await this.destroyAndWait(); if (persistenceError) throw persistenceError; + // Answered to the POST caller (`commandErrorResponse`, 400 + code). The + // state GETs never observe it: the child is already gone here, so they + // answer from the exited/ownership path, and their own `get_state` + // timeout is `session_slow` (503). Upstream 0.6.0 had a `recovered:true` + // branch in both GETs that no producer could reach either. throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); } if (error instanceof SessionEditAgentInvocationError && !error.agentStarted) { @@ -1748,7 +1936,7 @@ export class AgentSessionWrapper { await proc.negotiateProtocol(ready); // The replacement process starts with subscriptions disabled; restore // the live roster/transcript event stream before reading its state. - await proc.sendCommand({ type: "set_subagent_subscription", level: "events" }).catch(() => {}); + await proc.sendCommand({ type: "set_subagent_subscription", level: "events" }, GET_STATE_TIMEOUT_MS).catch(() => {}); await proc.sendCommand({ type: "set_ask_dialog", enabled: true }, GET_STATE_TIMEOUT_MS).catch(() => {}); const state = await proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); this.applyIdentity(state); @@ -1757,7 +1945,7 @@ export class AgentSessionWrapper { // cwd's most recent session. An on-disk session file is the resume // signal (fresh children report a not-yet-created path). if (!resumable && this._sessionFile && existsSync(this._sessionFile)) { - await proc.sendCommand({ type: "new_session" }); + await proc.sendCommand({ type: "new_session" }, PROMPT_ACK_TIMEOUT_MS); this.applyIdentity(await proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS)); } } catch (error) { @@ -1772,15 +1960,109 @@ export class AgentSessionWrapper { } } finally { this.restarting = false; + // The replacement answered its handshake: the stall clock starts here, so + // the disposed old child's silence never counts against the new one. + this.lastEvidenceAt = Date.now(); + this.lastFrameAt = this.lastEvidenceAt; } notifyRunningChange(); } + /** + * Single command choke point for the wrapper. Every successful answer — and + * every `RpcCommandError`, because omp answered — is positive evidence that + * the child's event loop is alive, which is exactly what the stall watchdog + * needs. Timeouts are not evidence and deliberately do not touch the clock. + */ + private async sendRpc( + command: { type: string; [key: string]: unknown }, + timeoutMs?: number, + ): Promise { + try { + const result = await this.proc.sendCommand(command, timeoutMs); + this.lastEvidenceAt = Date.now(); + return result; + } catch (error) { + if (error instanceof RpcCommandError) this.lastEvidenceAt = Date.now(); + throw error; + } + } + + /** + * Bounded command for the control paths: a timeout answers `session_slow` + * instead of pinning the request forever, and only the liveness watchdog may + * dispose the child. A child the watchdog *did* dispose never ran the frame, + * so the error then carries no `details` and clients fall back to their + * normal rollback (the text stays recoverable). + */ + private async sendControl( + command: { type: string; [key: string]: unknown }, + timeoutMs: number, + timeoutDetails?: Record, + ): Promise { + try { + return await this.sendRpc(command, timeoutMs); + } catch (error) { + if (!(error instanceof RpcCommandTimeoutError)) throw error; + if (this.destroyIfStalled()) throw slowSessionError(); + throw slowSessionError(timeoutDetails); + } + } + + /** + * Liveness watchdog, called only from a command-timeout branch. A timeout + * normally means "busy" (omp blocks its loop for tens of seconds); it means + * "wedged" only when the child has produced no frame and answered no command + * for `STALL_DESTROY_MS`. That child is disposed through the regular exit + * path: the exited-session map gets a `detail: "stalled"` record which + * `GET /api/sessions/[id]/state` serves, while `GET /api/agent/[id]` only + * sees `{running:false}` — exactly like a process crash. + * + * Returns whether the child was disposed. + */ + private destroyIfStalled(): boolean { + if (STALL_DESTROY_MS <= 0 || !this.isAlive()) return false; + if (Date.now() - this.lastEvidenceAt < STALL_DESTROY_MS) return false; + const minutes = Math.round(STALL_DESTROY_MS / 60_000); + const idleFor = Math.round((Date.now() - this.lastEvidenceAt) / 1000); + console.warn(`[omp-web] omp child for session ${this._sessionId || "(new)"} produced no evidence of life for ${idleFor}s (>= ${minutes} min); disposing the stalled child.`); + if (this._sessionId) { + // Same record shape as handleProcessExit so every exited-session consumer + // (badges, resume prompts) treats it as the child being gone. + getExitedMap().set(this._sessionId, { + id: this._sessionId, + cwd: this.cwd, + at: Date.now(), + code: null, + signal: null, + detail: "stalled", + }); + } + this.emit({ + type: "notice", + level: "error", + message: "The omp process for this session stopped responding and was stopped; the next message starts it again. The run may have been interrupted.", + }); + // Let a client mid-stream stop spinning now, like a process exit would. + if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); + if (this.streaming || this.promptRunning || this.unsettled) { + this.publishNotifications({ type: "process_exit", detail: "stalled" }); + } + this.destroy(); + return true; + } + async send(command: Record): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); if (this.mcpListInFlight) throw new WebRpcError("MCP management is in progress. Try again when it finishes.", "session_busy"); if (!this.isAlive()) throw new Error("Session is no longer running"); - if (typeof command.type === "string" && command.type.startsWith("abort")) { + // Stop must always reach the child: at the cap every other command is + // refused, and refusing an abort would leave the user with no way out. + const isCancellation = CANCELLATION_COMMANDS.has(command.type as string); + if (!isCancellation && this.pendingCommands >= MAX_PENDING_COMMANDS) { + throw new WebRpcError("Too many commands are in flight for this session", "session_busy"); + } + if (isCancellation) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); } const mutatesHistory = HISTORY_MUTATING_COMMANDS.has(command.type as string); @@ -1827,6 +2109,7 @@ export class AgentSessionWrapper { if (!this.isRunning()) this.clearLiveSnapshots(); this.streamSequence += 1; this.promptRunning = true; + this.runStartedAt = Date.now(); this.promptDispatchPendingCount += 1; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; @@ -1836,7 +2119,7 @@ export class AgentSessionWrapper { try { // omp acks immediately; agent output streams as events, completion is // agent_end (agent runs) or prompt_result (local-only slash commands). - const ack = await this.proc.sendCommand<{ agentInvoked?: boolean } | undefined>({ + const ack = await this.sendRpc<{ agentInvoked?: boolean } | undefined>({ type: "prompt", message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), @@ -1857,19 +2140,37 @@ export class AgentSessionWrapper { this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; } } catch (error) { + if (error instanceof RpcCommandTimeoutError) { + // Busy, not dead: omp may simply be blocked inside the run this + // frame started, and the frame may already sit in its stdin. Never + // recycle the child (that killed the run and made omp record a + // `dispose`) and never declare the prompt "not started": keep the + // optimistic run state and let agent_start/agent_end — or the + // deadline checked in buildWebState — settle it. The client gets + // `maybeStarted` and keeps its send lock until a frame or a + // successful get_state arrives. A child with no evidence of life + // for STALL_DESTROY_MS is the one exception (see watchdog). + const stalled = this.destroyIfStalled(); + if (!streamingBehavior) { + if (!stalled) { + this.awaitingAgentStart = true; + this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; + } + notifyRunningChange(); + } + // A child the watchdog disposed never ran the frame: report a + // definite failure so the client rolls back and recovers the text + // instead of waiting for a run that cannot exist. Otherwise the + // frame sits in omp's stdin and the message may still run. + throw stalled ? slowSessionError() : slowSessionError({ maybeStarted: true }); + } this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.streaming = false; this.clearLiveSnapshots(); notifyRunningChange(); - if (error instanceof RpcCommandTimeoutError) { - // The child took the frame but never acked it, so nothing will ever - // report this run: recycle the unacknowledged prompt. A read-only - // get_state timeout deliberately does not take this destructive path. - await this.destroyAndWait(); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); - } + throw error; } finally { if (!streamingBehavior) { @@ -1885,11 +2186,14 @@ export class AgentSessionWrapper { // there is no live turn to steer anyway, so it joins the follow-up // queue like a prompt would. if (type === "steer" && this.bashRunning) return await this.queueWhileShellRunning(command); - await this.proc.sendCommand({ + // The frame is written before the ack is awaited: a timeout means it + // may already be in omp's stdin, so the message may still be delivered. + // Reporting "not sent" made clients roll back and resend it twice. + await this.sendControl({ type, message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), - }); + }, PROMPT_ACK_TIMEOUT_MS, { maybeStarted: true }); return null; } @@ -1897,7 +2201,7 @@ export class AgentSessionWrapper { case "promote_queued_message": { // Queue mutations are synchronous control operations, like get_state. // Expiry must not abort unrelated work or replay a possibly applied mutation. - const result = await this.proc.sendCommand(command as { type: string }, GET_STATE_TIMEOUT_MS); + const result = await this.sendControl(command as { type: string }, GET_STATE_TIMEOUT_MS); return result ?? null; } @@ -1908,7 +2212,10 @@ export class AgentSessionWrapper { this.responseObserved = false; this.responseRunActive = false; const result = await this.withFinalRunningNotification(async () => { - const response: unknown = await this.proc.sendCommand({ type }); + // The abort frame may already have reached omp without omp managing + // to confirm it: never report this as done, and keep the run flags + // (the run may still be live and reporting frames). + const response = await this.sendControl({ type }, PROMPT_ACK_TIMEOUT_MS, { abortUnconfirmed: true }); // If the prompt was aborted before the agent loop started, no // agent_end will arrive to clear the flag; the streaming flag still // tracks a live turn that ends with its own agent_end. @@ -1927,22 +2234,17 @@ export class AgentSessionWrapper { } case "get_state": { - try { - const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); - return this.buildWebState(state); - } catch (error) { - if (error instanceof RpcCommandTimeoutError) { - // This is only an observer poll. A busy event loop or delayed RPC - // response is not authority to stop generation or a pending tool. - console.warn("[omp-web] status-query-timeout", JSON.stringify({ sessionId: this._sessionId, timeoutMs: GET_STATE_TIMEOUT_MS, running: this.isRunning(), action: "preserved", at: new Date().toISOString() })); - throw new WebRpcError("The OMP status query timed out. The session was left running; retry shortly.", "session_state_timeout"); - } - throw error; - } + // The 5 s bound belongs to this request only. A busy child (omp blocks + // its loop for tens of seconds on big sessions) must keep running and + // keep the run it is executing; clients get `session_slow` and retry + // the poll. Only the liveness watchdog may dispose a child that has + // been silent past STALL_DESTROY_MS. + const state = await this.sendControl({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + return this.buildWebState(state); } case "get_skill_diagnostics": { - const result = await this.proc.sendCommand({ type: "get_skill_diagnostics" }, GET_STATE_TIMEOUT_MS); + const result = await this.sendControl({ type: "get_skill_diagnostics" }, GET_STATE_TIMEOUT_MS); return this.requireSkillDiagnostics(result); } @@ -1950,7 +2252,7 @@ export class AgentSessionWrapper { if (typeof command.enabled !== "boolean") { throw new WebRpcError("enabled must be a boolean", "invalid_skill_startup_diagnostics"); } - const result = await this.proc.sendCommand({ + const result = await this.sendControl({ type: "set_skill_startup_diagnostics", enabled: command.enabled, }, GET_STATE_TIMEOUT_MS); @@ -1959,7 +2261,7 @@ export class AgentSessionWrapper { case "set_model": { const { provider, modelId } = command as { provider: string; modelId: string }; - const model = await this.proc.sendCommand({ type: "set_model", provider, modelId }); + const model = await this.sendControl({ type: "set_model", provider, modelId }, GET_STATE_TIMEOUT_MS); invalidateModelsCache(); this.invalidateSessionLists(); return { id: model.id, provider: model.provider }; @@ -1967,14 +2269,14 @@ export class AgentSessionWrapper { case "set_fast_mode": { const enabled = command.enabled === true; - const result = await this.proc.sendCommand<{ enabled?: boolean; active?: boolean }>({ type: "set_fast_mode", enabled }); + const result = await this.sendControl<{ enabled?: boolean; active?: boolean }>({ type: "set_fast_mode", enabled }, GET_STATE_TIMEOUT_MS); this.fastModeEnabled = result?.enabled ?? enabled; return { enabled: this.fastModeEnabled, active: result?.active ?? false }; } case "set_slow_mode": { const enabled = command.enabled === true; - const result = await this.proc.sendCommand<{ enabled?: boolean }>({ type: "set_slow_mode", enabled }); + const result = await this.sendControl<{ enabled?: boolean }>({ type: "set_slow_mode", enabled }, GET_STATE_TIMEOUT_MS); return { enabled: result?.enabled ?? enabled }; } @@ -1988,7 +2290,7 @@ export class AgentSessionWrapper { if (this.bashRunning) { throw new Error("Cannot fork while a shell command is running"); } - const result = await this.proc.sendCommand<{ text: string; cancelled: boolean }>({ + const result = await this.sendRpc<{ text: string; cancelled: boolean }>({ type: "branch", entryId: command.entryId as string, }); @@ -2000,11 +2302,27 @@ export class AgentSessionWrapper { case "new_session": case "switch_session": { - const result = await this.proc.sendCommand<{ cancelled: boolean }>(command as { type: string }); + // Switching writes a session file before answering, so it gets the + // generous prompt-ack bound instead of the 5 s poll bound — but it is + // still bounded: a wedged child must not pin the request forever. The + // frame can still switch the child after that bound expires, so the + // switch stays pending and the identity a later state read reports is + // rekeyed then (see applyIdentity). + this.sessionSwitchPending = true; + let result: { cancelled: boolean }; + try { + result = await this.sendControl<{ cancelled: boolean }>(command as { type: string }, PROMPT_ACK_TIMEOUT_MS); + } catch (error) { + // A timeout leaves the frame in the child's stdin, so the switch may + // still happen; anything else never reached it. + if (!(error instanceof WebRpcError && error.code === SESSION_SLOW_CODE)) this.sessionSwitchPending = false; + throw error; + } if (!result.cancelled) { const newSessionId = await this.refreshIdentityAfterSessionChange(); return { cancelled: false, newSessionId }; } + this.sessionSwitchPending = false; return result; } @@ -2015,7 +2333,7 @@ export class AgentSessionWrapper { this.streamSequence += 1; notifyRunningChange(); try { - const result = await this.proc.sendCommand({ + const result = await this.sendRpc({ type: "compact", ...(command.customInstructions ? { customInstructions: command.customInstructions } : {}), }); @@ -2034,32 +2352,32 @@ export class AgentSessionWrapper { case "abort_compaction": // No dedicated RPC command; a plain abort cancels the in-flight turn // including compaction work. - await this.withFinalRunningNotification(() => this.proc.sendCommand({ type: "abort" })); + await this.withFinalRunningNotification(() => this.sendControl({ type: "abort" }, PROMPT_ACK_TIMEOUT_MS, { abortUnconfirmed: true })); return null; case "set_session_name": { const name = (command.name as string | undefined)?.trim(); if (!name) throw new Error("Session name cannot be empty"); - await this.proc.sendCommand({ type: "set_session_name", name }); + await this.sendControl({ type: "set_session_name", name }, GET_STATE_TIMEOUT_MS); this._sessionName = name; this.invalidateSessionLists(); return null; } case "get_session_stats": { - const stats = await this.proc.sendCommand>({ type: "get_session_stats" }); + const stats = await this.sendControl>({ type: "get_session_stats" }, GET_STATE_TIMEOUT_MS); return { ...stats, sessionName: this._sessionName }; } case "get_last_assistant_text": { - const data = await this.proc.sendCommand<{ text: string | null }>({ type: "get_last_assistant_text" }); + const data = await this.sendControl<{ text: string | null }>({ type: "get_last_assistant_text" }, GET_STATE_TIMEOUT_MS); return { text: data.text ?? "" }; } case "get_commands": { - const data = await this.proc.sendCommand<{ commands: RpcAvailableSlashCommand[] }>({ + const data = await this.sendControl<{ commands: RpcAvailableSlashCommand[] }>({ type: "get_available_commands", - }); + }, GET_STATE_TIMEOUT_MS); return { ...data, commands: data.commands.filter((command) => command.name !== SESSION_EDIT_COMMAND) }; } @@ -2099,7 +2417,7 @@ export class AgentSessionWrapper { this.bashRunning = true; notifyRunningChange(); try { - return await this.proc.sendCommand({ type: "bash", command: command.command as string }); + return await this.sendRpc({ type: "bash", command: command.command as string }); } finally { this.bashRunning = false; this.invalidateSessionLists(); @@ -2119,7 +2437,7 @@ export class AgentSessionWrapper { ? [...valid, ...AGENT_TOOL_DEFINITIONS.filter((t) => !valid.some((v) => v.name === t.name))] : valid; this.hostToolNames = new Set(merged.map((t) => t.name as string)); - await this.proc.sendCommand({ type: "set_host_tools", tools: merged }); + await this.sendControl({ type: "set_host_tools", tools: merged }, GET_STATE_TIMEOUT_MS); return null; } @@ -2137,7 +2455,7 @@ export class AgentSessionWrapper { this.hostUriSchemes.set(entry.scheme, { writable: entry.writable === true }); } } - await this.proc.sendCommand({ type: "set_host_uri_schemes", schemes }); + await this.sendControl({ type: "set_host_uri_schemes", schemes }, GET_STATE_TIMEOUT_MS); return null; } @@ -2154,10 +2472,20 @@ export class AgentSessionWrapper { this.responseRunActive = false; this.streamSequence += 1; } - const result: unknown = await this.proc.sendCommand( - command as { type: string }, - type === "predict_word" ? PREDICT_WORD_TIMEOUT_MS : undefined, - ); + const timeoutMs = type === "predict_word" + ? PREDICT_WORD_TIMEOUT_MS + : UNBOUNDED_PASSTHROUGH_COMMANDS.has(type) + ? undefined + : type.startsWith("abort") + ? PROMPT_ACK_TIMEOUT_MS + : GET_STATE_TIMEOUT_MS; + // `abort_and_prompt` writes the frame before the ack: a timeout means + // the abort may already have landed and the new prompt may already be + // running, so it must not be reported as "not sent". + const timeoutDetails = type === "abort_and_prompt" ? { maybeStarted: true } : undefined; + const result = timeoutMs === undefined + ? await this.sendRpc(command as { type: string }) + : await this.sendControl(command as { type: string }, timeoutMs, timeoutDetails); if (type === "set_thinking_level") this.invalidateSessionLists(); return result ?? null; } @@ -2179,11 +2507,13 @@ export class AgentSessionWrapper { */ private async queueWhileShellRunning(command: Record): Promise { const images = toImageContents(command.images); - await this.proc.sendCommand({ + // Same rule as `steer`: the follow_up frame reaches omp's stdin before the + // ack does, so a timeout may mean the message is already queued. + await this.sendControl({ type: "follow_up", message: command.message as string, ...(images ? { images } : {}), - }); + }, PROMPT_ACK_TIMEOUT_MS, { maybeStarted: true }); return { queued: true, queue: "followUp", reason: "shellRunning" }; } @@ -2376,7 +2706,7 @@ export function subscribeHostToolCalls(listener: (call: CrossSessionHostToolCall } // Starts at the empty state so an idle server never broadcasts "nothing changed". -let lastRunningSnapshot = "[[],[]]"; +let lastRunningSnapshot = "[[],[],[]]"; /** * Recompute the running-session-id set and, when it changes, broadcast it. @@ -2388,7 +2718,10 @@ export function notifyRunningChange({ refreshSessionList = false }: { refreshSes const exitedSessions = getExitedRpcSessions(); const ids = runningSessions.map((s) => s.id); const byId = (a: { id: string }, b: { id: string }) => a.id.localeCompare(b.id); - const snapshot = JSON.stringify([runningSessions.slice().sort(byId), exitedSessions.slice().sort(byId)]); + const snapshot = JSON.stringify([ + runningSessions.slice().sort(byId), + exitedSessions.slice().sort(byId), + ]); if (snapshot === lastRunningSnapshot && !refreshSessionList) return; lastRunningSnapshot = snapshot; syncInterruptibleSessions(); @@ -2663,7 +2996,9 @@ export async function startRpcSession( clearExitedRpcSession(sessionId); if (realSessionId !== sessionId) clearExitedRpcSession(realSessionId); return { session: created, realSessionId }; - })().finally(() => locks.delete(sessionId)); + })().finally(() => { + locks.delete(sessionId); + }); locks.set(sessionId, starting); return starting; diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5d966ed28..54cb19e63 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -21,6 +21,10 @@ const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/rout const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await jiti.import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await jiti.import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await jiti.import("./rpc-manager.ts"); +// The route bundle imports through the "@/" alias. jiti keys modules by their +// resolved specifier, so only this import hands out the exact `WebRpcError` +// class the route checks with `instanceof`. +const { WebRpcError: RouteWebRpcError } = await jiti.import("@/lib/rpc-manager"); const getContext = (id, query = "") => contextRoute.GET( new Request(`http://localhost/api/sessions/${id}/context${query ? `?${query}` : ""}`), @@ -73,10 +77,96 @@ test("state reports a retained exit before the session file exists", async (t) = assert.equal(response.status, 200); assert.deepEqual(await response.json(), { running: false, + // The child is gone: `alive` is the process, `running` the turn. + alive: false, exited: { id, cwd: "/tmp/project", at: 123, code: 1, signal: null, detail: "startup failed" }, }); }); +test("state answers 503 session_slow for a busy live session instead of claiming the run ended", async (t) => { + const id = "slow-live-session"; + // The routes import through the `@/` alias, which jiti instantiates separately + // from a relative path; the exact class identity is what the route checks. + const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + const previousSessions = globalThis.__ompSessions; + const wrapper = { + isAlive: () => true, + isRunning: () => true, + // The frame clock the route forwards so a client can say how long a + // blocked omp has been silent — a 503 is the only answer it will get. + silentForMs: () => 9_900_000, + send: async () => { + throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + }, + }; + globalThis.__ompSessions = new Map([[id, wrapper]]); + t.after(() => { + globalThis.__ompSessions = previousSessions; + }); + + const response = await getState(id); + const body = await response.json(); + + assert.equal(response.status, 503); + assert.equal(body.code, "session_slow"); + assert.equal(body.silentForMs, 9_900_000, "the busy answer carries the frame clock"); + assert.equal(body.running, true, "the slow answer carries the wrapper's run state"); + assert.equal(body.alive, true, "and that the child exists"); +}); + +test("state reports an idle live child as not running but alive", async (t) => { + const id = "idle-live-session"; + const previousSessions = globalThis.__ompSessions; + // The fresh-spawn case from the report: omp answers `get_state` with + // `isStreaming:false` and no queue, yet the session was shown as working. + globalThis.__ompSessions = new Map([[id, { + isAlive: () => true, + isRunning: () => false, + silentForMs: () => null, + send: async () => ({ isStreaming: false, isPromptRunning: false, isCompacting: false }), + }]]); + t.after(() => { + globalThis.__ompSessions = previousSessions; + }); + + const response = await getState(id); + const body = await response.json(); + + assert.equal(response.status, 200); + assert.equal(body.running, false, "no run in flight is not a run"); + assert.equal(body.alive, true, "the child is still there for the next prompt"); + assert.equal(body.state.isStreaming, false); +}); + +test("state reports the child as gone when the timed-out poll disposed it", async (t) => { + const id = "stalled-live-session"; + const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + const previousSessions = globalThis.__ompSessions; + // The stall watchdog disposes a wedged child inside the request that times + // out: the 503 must report what is left, not the state from before the catch. + let alive = true; + globalThis.__ompSessions = new Map([[id, { + isAlive: () => alive, + isRunning: () => false, + silentForMs: () => null, + send: async () => { + alive = false; + throw new WebRpcError("The OMP session stopped responding and was reset.", "session_slow"); + }, + }]]); + t.after(() => { + globalThis.__ompSessions = previousSessions; + }); + + const response = await getState(id); + const body = await response.json(); + + assert.equal(response.status, 503); + assert.equal(body.code, "session_slow"); + assert.equal(body.alive, false, "a disposed child is not alive"); + assert.equal(body.running, false, "and nothing is running"); +}); + function writeSessionFile(dir, name, header, entries = []) { const filePath = join(dir, name); const lines = [JSON.stringify({ type: "session", version: 3, ...header })]; @@ -667,6 +757,56 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn }); }); +test("a slow rename answers 503 and never writes behind the live child", async () => { + await withAgentDir(async (dir) => { + const id = "rename-slow"; + const filePath = writeSessionFile(dir, "rename-slow.jsonl", { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const originalFile = readFileSync(filePath); + const previousSessions = globalThis.__ompSessions; + let code = "session_slow"; + const slowWrapper = () => ({ + isAlive: () => true, + isEditingHistory: () => false, + async send() { + throw new RouteWebRpcError("The agent is busy and did not answer in time. It is still running.", code); + }, + }); + globalThis.__ompSessions = new Map([[id, slowWrapper()]]); + const rename = () => sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + try { + // Both "still busy" codes mean the command was never confirmed: omp keeps + // the old name in memory and would clobber a file write on its next flush. + for (const slowCode of ["session_slow", "session_state_timeout"]) { + code = slowCode; + const response = await rename(); + assert.equal(response.status, 503, `${slowCode} must not report success`); + assert.equal((await response.json()).code, "session_slow"); + assert.deepEqual(readFileSync(filePath), originalFile, `${slowCode} must not rewrite the title slot`); + } + // The child answered an immediate error: it rejected the command, so + // nothing was applied and the on-disk title is the only writer left. + globalThis.__ompSessions = new Map([[id, { + isAlive: () => true, + isEditingHistory: () => false, + async send() { + throw new Error("Unknown command: set_session_name"); + }, + }]]); + const accepted = await rename(); + assert.equal(accepted.status, 200); + assert.match(readFileSync(filePath, "utf8"), /"title":"Renamed"/); + } finally { + globalThis.__ompSessions = previousSessions; + } + }); +}); + test("automatic title fallback cannot write after Edit takes over", async () => { await withAgentDir(async (dir) => { const id = "auto-name-during-edit";