diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index c7ee93199..0ff1972af 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -45,14 +45,34 @@ export async function GET( try { const session = getRpcSession(id); if (!session || !session.isAlive()) { - return Response.json({ running: false }); + return Response.json({ running: false, alive: false }); } try { const state = await session.send({ type: "get_state" }); - return Response.json({ running: true, state }); + return Response.json({ running: session.isRunning(), alive: true, state }); } catch (error) { + // omp being slow is not the run ending: answer 503 so clients retry the + // poll 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")) { + // The liveness watchdog disposes a child that stayed silent past its + // threshold; that child is gone, so the busy answer would be a lie. + if (!session.isAlive()) return Response.json({ running: false, alive: false }); + return Response.json( + { + error: error.message, + code: "session_slow", + ...error.details, + running: session.isRunning(), + alive: true, + silentForMs: session.silentForMs(), + }, + { status: 503 }, + ); + } if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return Response.json({ running: false, recovered: true }); + return Response.json({ running: false, alive: false, recovered: true }); } throw error; } diff --git a/app/api/agent/new/route.ts b/app/api/agent/new/route.ts index dc62d98f1..671b01ab2 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -14,7 +14,13 @@ function newSessionErrorResponse(error: unknown) { // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if ((error instanceof WebRpcError && error.code !== "host_offline") || error instanceof RpcCommandError) { return Response.json( - { error: error.message, code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed") }, + { + error: error.message, + code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed"), + // `maybeStarted`/`abortUnconfirmed` must reach the client, exactly as on + // POST /api/agent/[id]: without them a timeout looks like "not sent". + ...(error instanceof WebRpcError ? error.details : undefined), + }, { status: 400 }, ); } @@ -70,6 +76,22 @@ export async function POST(req: Request) { }; return await (preparing ? session.withPendingCommand(run, true) : run()); } catch (error) { + // A command timeout means omp is busy, not dead: the frame may already sit + // in the child's stdin and a run it started must survive. Same contract as + // POST /api/agent/[id]; the liveness watchdog alone may dispose the child. + // The body carries the real session id so a client that posted the prompt + // directly here can still poll and adopt the run `maybeStarted` announced. + if (error instanceof WebRpcError && error.code === "session_slow") { + return Response.json( + { + error: error.message, + code: error.code, + sessionId: realSessionId, + ...error.details, + }, + { status: 400 }, + ); + } // The child was spawned but the prompt never ran: without this cleanup a // failed set_model/set_thinking_level/prompt leaves an orphaned omp // process and a registry entry nobody will ever use. diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index 8467e3c95..772ecab66 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -27,22 +27,47 @@ async function sessionState(id: string): Promise { if (rpc?.isAlive()) { try { const state = await rpc.send({ type: "get_state" }); - return Response.json({ running: true, state }); + return Response.json({ running: rpc.isRunning(), alive: true, state }); } catch (error) { + // 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")) { + // The liveness watchdog disposes a child that stayed silent past its + // threshold; that child is gone, so the busy answer would be a lie. + // Its `detail: "stalled"` record answers like any other exit. + if (!rpc.isAlive()) { + const exited = getExitedRpcSession(id); + return Response.json({ running: false, alive: false, ...(exited ? { exited } : {}) }); + } + return Response.json( + { + error: error.message, + code: "session_slow", + ...error.details, + running: rpc.isRunning(), + alive: true, + silentForMs: rpc.silentForMs(), + }, + { status: 503 }, + ); + } if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return Response.json({ running: false, recovered: true }); + return Response.json({ running: false, alive: false, recovered: true }); } throw error; } } const exited = getExitedRpcSession(id); - if (exited) return Response.json({ running: false, exited }); + if (exited) return Response.json({ running: false, alive: false, exited }); const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.readSessionState(id); - return result.ok ? Response.json(result.value) : opErrorResponse(result); + if (!result.ok) return opErrorResponse(result); + return Response.json({ ...(result.value as Record), alive: false }); } catch (error) { return apiErrorResponse(error); } diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index f961fba14..db7a35c72 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -190,7 +190,10 @@ async function fetchStub(url, init = {}) { for (let i = 0; i < world.holds.length; i++) { if (world.holds[i].match(method, u, body)) { const h = world.holds.splice(i, 1)[0]; - const { status = 200, value } = await h.produce(); + const produced = await h.produce(); + // A hold may hand back a real Response (a body that can be read once). + if (produced.response) return produced.response; + const { status = 200, value } = produced; return jsonResponse(status, value); } } @@ -1481,6 +1484,41 @@ test("a failed transcript reload is retried instead of being classified as an em assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); }); +test("opening a chat whose state read answers 503 session_slow keeps the transcript and shows the run, not a load failure", async () => { + resetWorld(); + const sid = "busy-open"; + primeSession(sid, [userMsg("u0", "saved history")]); + // A real Response: its body can be read exactly once, so a second read (the + // bug that turned this path into an HTTP 503 load failure) throws here. + world.holds.push({ + match: (method, url) => method === "GET" && url === `/api/sessions/${sid}/state`, + produce: async () => ({ + response: Response.json( + { running: true, alive: true, code: "session_slow", error: "omp is busy", silentForMs: 12_000 }, + { status: 503 }, + ), + }), + }); + const w = await mountSession(sid); + assert.equal(w.latest.loading, false); + assert.equal(w.latest.error, null, "a busy child is not a failed load"); + assert.ok(w.latest.messages.some((m) => m.role === "user" && m.content === "saved history"), "the on-disk transcript stays"); + assert.equal(w.latest.agentRunning, true, "the run stays marked so the reconcile poll settles it"); + assert.ok(lastEs(), "the observer stream attaches to receive the completion frames"); +}); + +test("a 503 state answer without a busy code stays a load failure", async () => { + resetWorld(); + const sid = "broken-open"; + primeSession(sid, [userMsg("u0", "saved history")]); + world.holds.push({ + match: (method, url) => method === "GET" && url === `/api/sessions/${sid}/state`, + produce: async () => ({ status: 503, value: { error: "Host is offline", hostOffline: true } }), + }); + const w = await mountSession(sid); + assert.equal(w.latest.agentRunning, false); +}); + for (const recovered of ["answer", "empty", "absent wrapper"]) { test(`a failed state read stays retryable until recovery confirms ${recovered}`, async () => { resetWorld(); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index c85ad9715..ef7044adc 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -18,7 +18,7 @@ import type { import { normalizeToolCalls } from "@/lib/normalize"; import { hasVisibleAssistantContent } from "@/lib/assistant-response"; import type { ThinkingModelMeta } from "@/lib/thinking-levels"; -import { HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxScope, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; +import { AgentCommandError, HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxScope, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; import type { HostStatus } from "@/lib/hosts/host"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { newChatDraftKey, remoteHostId } from "@/lib/project-ordering"; @@ -602,6 +602,11 @@ 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); // 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. @@ -936,7 +941,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); @@ -951,8 +956,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setFastModeEnabled(agentState.state.fastModeEnabled); } setFastModeActive(agentState.state?.fastModeActive); - // No omp process: back to the catalog fallback. - setSlowModeSupported(agentState.running ? (agentState.state?.slowModeSupported ?? false) : undefined); + // No omp process: back to the catalog fallback. `alive`, not `running`: + // an idle live child still knows whether this session's model supports + // Slow mode, and reading it as absent showed an enabled setting as + // disabled and sent the wrong toggle value. An older server/daemon + // answers without `alive`, where `running` is the only liveness signal. + setSlowModeSupported((agentState.alive ?? agentState.running) ? (agentState.state?.slowModeSupported ?? false) : undefined); setSlowModeEnabled(agentState.state?.slowModeEnabled ?? false); setSlowModeScope(agentState.state?.slowModeScope); setUsageLimit(agentState.state?.usageLimit); @@ -966,6 +975,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync]); + // omp answered a state read with 503 `session_slow`: the child is alive and + // a run is under way, but its event loop is blocked and `get_state` timed + // out. The run must stay marked so the periodic reconcile poll settles it, + // and the observer stream attaches (frames are the completion path once omp + // answers again). The on-disk transcript is already loaded by the caller. + const markSessionAliveStateUnknown = useCallback(() => { + 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(); @@ -982,7 +1004,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { queueRevision: ++queueSeqRef.current, skillDiagnosticsRevision: ++skillDiagnosticsSeqRef.current, response: fetch(`/api/sessions/${encodeURIComponent(sid)}/state`).then(async (stateRes) => { - const agentState = await stateRes.json().catch(() => ({})) as { running: boolean; state?: AgentStateResponse; exited?: ExitedRpcSession; outbox?: OutboxEntry[]; outboxScope?: string; outboxSettledIds?: string[] }; + const agentState = await stateRes.json().catch(() => ({})) as { running: boolean; alive?: boolean; state?: AgentStateResponse; code?: unknown; exited?: ExitedRpcSession; outbox?: OutboxEntry[]; outboxScope?: string; outboxSettledIds?: string[] }; if (hookAliveRef.current && sessionIdRef.current === sid && contextRequestSeqRef.current === requestSeq && promptRunIdRef.current === requestRun && (fenceRunId === undefined || promptRunIdRef.current === fenceRunId)) { if (typeof agentState.outboxScope === "string") rememberOutboxScope(agentState.outboxScope); @@ -1048,7 +1070,23 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return { context: d.context, agentState: null }; } const { stateRes, agentState } = reply; - if (!stateRes.ok) throw new Error(`HTTP ${stateRes.status}`); + 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, the run + // keeps going and the state is merely unknown right now. The code + // comes from the body already parsed above — a Response body can be + // read only once, and re-reading it threw, turning the busy path into + // an HTTP 503 load failure. + if (stateRes.status === 503 && (agentState.code === "session_slow" || agentState.code === "session_state_timeout")) { + if (!hookAliveRef.current || sessionIdRef.current !== sid + || contextRequestSeqRef.current !== requestSeq || promptRunIdRef.current !== requestRun) { + return null; + } + markSessionAliveStateUnknown(); + return { context: d.context, agentState: null }; + } + throw new Error(`HTTP ${stateRes.status}`); + } if (!hookAliveRef.current) return null; if (sessionIdRef.current !== sid) { if (showLoading) setLoading(false); @@ -1071,7 +1109,8 @@ 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); + // `alive`, not `running`: an idle live child still knows its model's Slow support. + setSlowModeSupported((agentState.alive ?? agentState.running) ? (liveState.slowModeSupported ?? false) : undefined); setSlowModeEnabled(liveState.slowModeEnabled ?? false); setSlowModeScope(liveState.slowModeScope); setUsageLimit(liveState.usageLimit); @@ -1084,7 +1123,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 ?? agentState.running)) { setSlowModeSupported(undefined); applyQueueStateSnapshot(queueRevision, null); } @@ -1111,7 +1150,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; @@ -1206,14 +1245,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { ...(advisorEnabled ? { advisor: true } : {}), }), }); - const body = await res.json().catch(() => ({})) as { sessionId?: unknown; error?: string; code?: string; hostOffline?: boolean; delivery?: string }; + const body = await res.json().catch(() => ({})) as { sessionId?: unknown; error?: string; code?: string; hostOffline?: boolean; delivery?: string; maybeStarted?: boolean }; const offline = res.status === 503 && body.hostOffline === true; - if (!res.ok && !offline) throw new Error(body.error || body.code ? formatApiError(body) : `HTTP ${res.status}`); + // A command timeout keeps the spawned child (HTTP 400 `session_slow` with + // its id): the preset may already be applied and a prompt it carried may + // already run, so a retry must adopt it instead of spawning a second one. + const slow = body.code === "session_slow"; + if (!res.ok && !offline && !slow) throw new Error(body.error || body.code ? formatApiError(body) : `HTTP ${res.status}`); // A host that dropped after the spawn keeps the session (503 with its id): // adopt it, so a retry sends there instead of starting a second session. const realId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : null; if (!realId) { if (offline) throw new HostOfflineError(formatApiError(body), body.delivery === "unknown"); + if (slow) throw new Error(formatApiError(body)); return null; } sessionIdRef.current = realId; @@ -1233,6 +1277,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { observeCreatedSessionRef.current?.(realId); } if (offline) throw new HostOfflineError(formatApiError(body), body.delivery === "unknown"); + // Adopted above: the id is kept, so the caller's retry targets this child. + if (slow) throw new Error(formatApiError(body)); return realId; })(); @@ -1894,9 +1940,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // 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(); @@ -1919,6 +1969,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + maybeStartedRunRef.current = false; slashCommandRunRef.current = false; onAgentEnd?.(); } @@ -2289,6 +2340,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. @@ -2358,6 +2410,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); @@ -3068,6 +3121,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; @@ -3168,6 +3222,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (promptRunIdRef.current !== promptRunId) return { status: "superseded" }; promptDispatchPendingRef.current = false; console.error("Failed to send message:", e); + // 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 failure here (stream connect, startup, set_model, or the prompt // POST itself) leaves no run to show, so roll back the optimistic bubble. setOptimisticUserMessage(null); @@ -3336,16 +3399,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 : []; @@ -3428,6 +3508,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. diff --git a/lib/agent-client.ts b/lib/agent-client.ts index 451976396..032af89b4 100644 --- a/lib/agent-client.ts +++ b/lib/agent-client.ts @@ -11,6 +11,30 @@ import { recordTransportSample, sendSessionCommand, type CommandReply } from "@/lib/event-stream"; import { formatApiError } from "@/lib/i18n/api-error"; +/** 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; + } +} + // Sessions whose per-chat advisor toggle is on: their lazily spawned omp // process must start with --advisor. Keyed by session id because the spawn // decision happens inside the route, which only sees id + query string. @@ -99,6 +123,8 @@ export async function sendAgentCommand( code?: string; hostOffline?: boolean; delivery?: string; + maybeStarted?: boolean; + abortUnconfirmed?: boolean; }; const failed = reply.status < 200 || reply.status >= 300 || Boolean(body.error); let outcome = failed ? "error" : "ok"; @@ -126,7 +152,12 @@ export async function sendAgentCommand( const message = body.error || body.code ? formatApiError(body) : `HTTP ${reply.status}`; if (reply.status === 503 && body.hostOffline) throw new HostOfflineError(message, body.delivery === "unknown"); if (reply.status === 503 && body.code === "transport_lost") throw new TransportLostError(message); - throw new Error(message); + throw new AgentCommandError( + message, + body.code, + body.maybeStarted === true, + body.abortUnconfirmed === true, + ); } return body.data as T; } diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index 4eed36c7f..cd7be7ec2 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -179,7 +179,7 @@ test("POST answers carry received/replied times", async (t) => { test("GET returns the agent state without command transport timing headers", async (t) => { useRegistry(t, { s2: fake() }); const res = await route.GET(new Request("http://omp.test/api/agent/s2"), ctx("s2")); - assert.deepEqual(await jsonOf(res), { running: true, state: { ok: true } }); + assert.deepEqual(await jsonOf(res), { running: false, alive: true, state: { ok: true } }); assert.equal(res.headers.get("x-omp-received-at"), null); assert.equal(res.headers.get("x-omp-replied-at"), null); }); diff --git a/lib/agent-command.ts b/lib/agent-command.ts index e362a22df..775449b1e 100644 --- a/lib/agent-command.ts +++ b/lib/agent-command.ts @@ -36,7 +36,9 @@ export function commandErrorResponse(error: unknown): Response { } // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if (error instanceof WebRpcError && error.code !== "host_offline") { - return Response.json({ error: error.message, code: error.code }, { status: 400 }); + // `maybeStarted`/`abortUnconfirmed` must reach the client: without them a + // timeout looks like "not sent". + return Response.json({ error: error.message, code: error.code, ...error.details }, { status: 400 }); } if (error instanceof RpcCommandError) { return Response.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 }); diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index ddfdb2abf..b64ed4b5b 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.", @@ -680,6 +682,7 @@ "directoryPicker.cloneInterrupted": "The clone connection ended unexpectedly. Check the destination before retrying.", "directoryPicker.cloneOutputLabel": "git clone output", "errors.session_state_timeout": "OMP status query timed out. The session was kept running. Try again shortly.", + "errors.session_slow": "The agent is busy and did not answer in time. It is still running — try again in a moment.", "errors.access_denied": "Access denied", "errors.outbox_dispatched": "This message is already being delivered.", "errors.outbox_scope_changed": "This message belongs to another omp-web installation or sign-in configuration.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 7411bc7cd..515ab5b4c 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": "このフォローアップはキューに存在しないため、ステアリングに変更できません。", @@ -663,6 +665,7 @@ "directoryPicker.cloneInterrupted": "クローンの接続が予期せず終了しました。再試行する前に保存先を確認してください。", "directoryPicker.cloneOutputLabel": "git clone の出力", "errors.session_state_timeout": "OMPの状態取得がタイムアウトしました。セッションは停止せず維持しています。しばらくしてから再試行してください。", + "errors.session_slow": "エージェントは処理中で時間内に応答しませんでした。実行は続いています。しばらくしてから再試行してください。", "errors.access_denied": "アクセスが拒否されました", "errors.outbox_dispatched": "このメッセージはすでに配信中です。", "errors.outbox_scope_changed": "このメッセージは別の omp-web インストールまたはサインイン設定に属しています。", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 7599b575c..415b5d1b0 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": "该后续消息已不在队列中,无法转为引导消息。", @@ -663,6 +665,7 @@ "directoryPicker.cloneInterrupted": "克隆连接意外结束。请先检查目标目录,再重试。", "directoryPicker.cloneOutputLabel": "git clone 输出", "errors.session_state_timeout": "OMP 状态查询超时。会话仍在运行,未被停止。请稍后重试。", + "errors.session_slow": "代理正忙,未能及时响应。它仍在运行,请稍后重试。", "errors.access_denied": "访问被拒绝", "errors.outbox_dispatched": "这条消息正在投递中。", "errors.outbox_scope_changed": "这条消息属于另一个 omp-web 安装或登录配置。", diff --git a/lib/message-outbox.test.mjs b/lib/message-outbox.test.mjs index 396485c74..2668f4848 100644 --- a/lib/message-outbox.test.mjs +++ b/lib/message-outbox.test.mjs @@ -300,6 +300,35 @@ test("a lost reply fails as may-have-been-sent and is never resent, even on a ho assert.equal((await (await command(sid, { type: "outbox_remove", id: "x2" })).json()).data.removed, true); }); +test("a session_slow ack timeout after the write fails as may-have-been-sent, not as not-sent", async () => { + hostStatus = "online"; + const sid = "s-slow-ack"; + // The wrapper wrote the frame and omp never acked within the bound: HTTP 400 + // `session_slow` with `maybeStarted`, exactly as commandErrorResponse serves it. + const w = wrapper(sid, { + running: true, + reply: () => { throw new WebRpcError("omp is busy and did not acknowledge the message in time; it may still be running.", "session_slow", undefined, { maybeStarted: true }); }, + }); + await add(sid, "slow-ack-1", "may already run", "followUp"); + await until(() => states(sid)[0] === "may already run:failed", "the uncertain delivery"); + const [entry] = outbox.outboxEntries(sid); + assert.equal(entry.state, "failed"); + assert.equal(entry.mayHaveBeenSent, true, "the UI must say 'possibly sent', not 'not sent'"); + assert.equal(w.sent.length, 1); +}); + +test("a definite session_slow (the watchdog stopped the child) stays not-sent so the text is recoverable", async () => { + hostStatus = "online"; + const sid = "s-slow-definite"; + wrapper(sid, { + running: true, + reply: () => { throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); }, + }); + await add(sid, "slow-def-1", "never ran", "followUp"); + await until(() => states(sid)[0] === "never ran:failed", "the definite failure"); + assert.equal(outbox.outboxEntries(sid)[0].mayHaveBeenSent, undefined); +}); + test("uncertain failures never disappear on same-text snapshots, new echoes, or empty upload-only text", async () => { hostStatus = "online"; const sid = "s-late"; diff --git a/lib/message-outbox.ts b/lib/message-outbox.ts index 4f5dcc86b..2560ef9a7 100644 --- a/lib/message-outbox.ts +++ b/lib/message-outbox.ts @@ -783,7 +783,7 @@ function retry(entry: Row): Outcome { /** A non-2xx answer to the start (`sent` false) or to the message itself (spec O6). */ async function refused(entry: Row, response: Response, sent: boolean): Promise { - const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown; hostOffline?: unknown; delivery?: unknown }; + const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown; hostOffline?: unknown; delivery?: unknown; maybeStarted?: unknown }; const current = row(entry.id); if (!current || current.state === "delivered" || current.state === "failed") return "next"; const error = typeof body.error === "string" ? body.error : `HTTP ${response.status}`; @@ -820,7 +820,10 @@ async function refused(entry: Row, response: Response, sent: boolean): Promise= 500 || body.code === "session_unresponsive")); + // `maybeStarted` is the same statement from the wrapper itself: a `session_slow` ack timeout (HTTP 400) means the + // frame is already in omp's stdin, so the run may exist even though this request failed. Without it the UI called + // the message "Not sent" and offered a resend while omp was already executing it. + return fail(entry, error, sent && (response.status >= 500 || body.code === "session_unresponsive" || body.maybeStarted === true)); } /** `archived`/`absent`: every source answered. Otherwise the archive could not be read: `hello` while only a host's diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c58bac61b..05e4ce2f3 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -469,7 +469,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 preserves the process and reports session_slow", async () => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -495,7 +495,7 @@ 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"); + assert.equal(err.code, "session_slow"); return true; }, ); @@ -517,7 +517,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" }); @@ -528,7 +528,7 @@ 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) => { +test("prompt ack timeout keeps the child and reports session_slow with maybeStarted", async (t) => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -566,15 +566,19 @@ test("prompt ack timeout recycles a child that accepts the frame but withholds i 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 the child's stdin: the client must not + // treat this as "not sent" and resend the text. + assert.equal(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 killed the run the prompt may have started. + assert.equal(disposed, false); + assert.equal(removedFromRegistry, false); + assert.equal(wrapper.isAlive(), true); + assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame settles it"); }); test("getRunningRpcSessions and getRunningRpcSessionIds export running sessions with their originating cwd", async () => { @@ -835,7 +839,7 @@ test("buildSessionSpawnArgs binds an explicit model on resume only (#277)", asyn -test("mcp list ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { +test("mcp list ack timeout keeps the child and reports session_slow", async (t) => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -871,14 +875,15 @@ test("mcp list ack timeout recycles a child that accepts the frame but withholds 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); + // Busy, not dead: only the stall watchdog may dispose a silent child. + assert.equal(disposed, false); + assert.equal(wrapper.isAlive(), true); + assert.equal(wrapper.isRunning(), false, "the in-flight flag was released for the next attempt"); }); test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", async (t) => { @@ -905,17 +910,16 @@ test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", 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 busy wrapper must not report itself busy forever: without the bounded + // ack the finally block never ran and this second call failed with + // session_busy. It now retries and answers the same busy code. + 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) => { @@ -3279,7 +3283,7 @@ test("an edit that times out with no uplink since dispatch answers host_offline assert.equal(session.isAlive(), true); }); -test("a prompt that times out after the host sent uplink traffic is recycled as before", async (t) => { +test("a prompt that times out after the host sent uplink traffic keeps the child and says maybeStarted", async (t) => { const { startRpcSession } = await import("./rpc-manager.ts"); const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); @@ -3311,10 +3315,12 @@ test("a prompt that times out after the host sent uplink traffic is recycled as // A pong after dispatch: the link is alive, so omp itself is what went quiet. await link.post(); t.mock.timers.tick(29_000); - await assert.rejects(sending, (error) => error.code === "session_unresponsive"); + await assert.rejects(sending, (error) => error.code === "session_slow" && error.details?.maybeStarted === true); t.mock.timers.reset(); - assert.equal(kills.length > 0, true, "the wedged child is recycled"); - assert.equal(session.isAlive(), false); + // The link answered a pong, so the child is alive and the prompt may run: + // only a child silent for STALL_DESTROY_MS (5 min) is disposed. + assert.deepEqual(kills, [], "the busy child is not recycled"); + assert.equal(session.isAlive(), true); }); /** A wrapper whose host link starts down; `linkReturns()` brings it back. */ @@ -4096,3 +4102,112 @@ test("a delta for a message that already ended has no base", async (t) => { assert.equal(events.length, before); assert.deepEqual(filters().map((filter) => filter.messageUpdates), ["delta", "full"]); }); + +// ---------------------------------------------------------------- #325: timeouts keep the child + +test("a prompt ack timeout keeps the child alive and answers session_slow with maybeStarted", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const sent = []; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30_000); + return {}; + }, SnapshotWrapper, "slow-prompt"); + await assert.rejects( + wrapper.send({ type: "prompt", message: "hi" }), + (error) => error.code === "session_slow" && error.details?.maybeStarted === true, + ); + assert.deepEqual(sent, ["prompt"]); + assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); + assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame or a successful get_state settles it"); +}); + +test("a get_state timeout keeps the child alive and reports session_slow without details", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async () => { + throw new RpcCommandTimeoutError("get_state", 5_000); + }, SnapshotWrapper, "slow-state"); + await assert.rejects(wrapper.send({ type: "get_state" }), (error) => error.code === "session_slow" && error.details === undefined); + assert.equal(wrapper.isAlive(), true); +}); + +test("steer, follow-up and abort timeouts name what may already have happened", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async (command) => { + throw new RpcCommandTimeoutError(command.type, 30_000); + }, SnapshotWrapper, "slow-controls"); + for (const type of ["steer", "follow_up"]) { + await assert.rejects(wrapper.send({ type, message: "x" }), (error) => error.details?.maybeStarted === true, type); + } + await assert.rejects(wrapper.send({ type: "abort" }), (error) => error.details?.abortUnconfirmed === true); + assert.equal(wrapper.isAlive(), true); +}); + +test("the stall watchdog stops the child instead of only dropping membership, and reports it stopped", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { wrapper } = snapshotSession(t, async (command) => { + throw new RpcCommandTimeoutError(command.type, 5_000); + }, SnapshotWrapper, "stalled-child", 0); + const disposeCalls = []; + wrapper.proc.dispose = async (_grace, stopShared) => { disposeCalls.push(stopShared); }; + // No frame, no answer for longer than the 5-minute threshold: this child is wedged. + t.mock.timers.tick(5 * 60_000 + 1_000); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.deepEqual(disposeCalls, [true], "a daemon-owned child is only stopped with stopShared"); + assert.equal(wrapper.isAlive(), false, "the wrapper is gone synchronously"); + const exited = (await import("./rpc-manager.ts")).getExitedRpcSession("stalled-child"); + assert.equal(exited?.detail, "stalled"); +}); + +test("a timed-out session switch fences commands until a state read reconciles the identity", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const sent = []; + let switched = false; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "switch_session") throw new RpcCommandTimeoutError("switch_session", 30_000); + if (command.type === "get_state") { + // The switch landed after the request gave up: the child now serves another conversation. + return switched + ? { sessionId: "new-conversation", sessionFile: "/tmp/new.jsonl", isStreaming: false, isCompacting: false, messageCount: 0, queuedMessageCount: 0, todoPhases: [], autoCompactionEnabled: true } + : { sessionId: "old-conversation", sessionFile: "/tmp/old.jsonl", isStreaming: false, isCompacting: false, messageCount: 0, queuedMessageCount: 0, todoPhases: [], autoCompactionEnabled: true }; + } + return {}; + }, SnapshotWrapper, "old-conversation"); + await assert.rejects(wrapper.send({ type: "switch_session", sessionId: "new-conversation" }), { code: "session_slow" }); + switched = true; + // The next command must not act on the stale identity: it reconciles first. + await wrapper.send({ type: "get_session_stats" }); + assert.deepEqual(sent, ["switch_session", "get_state", "get_session_stats"]); + assert.equal(wrapper.sessionId, "new-conversation", "the wrapper now serves the reconciled identity"); +}); + +test("control commands carry a deadline to the transport; unbounded passthrough commands carry none", async (t) => { + // The timeout is observable at the transport boundary: `sendCommand` receives + // it as its second argument. A command without a deadline pins the request. + const deadlines = new Map(); + const { wrapper } = snapshotSession(t, async (command, timeoutMs) => { + deadlines.set(command.type, timeoutMs); + return {}; + }, SnapshotWrapper, "bounded"); + await wrapper.send({ type: "set_session_name", name: "Renamed" }); + await wrapper.send({ type: "get_session_stats" }); + await wrapper.send({ type: "login" }); + await wrapper.send({ type: "export_html" }); + assert.equal(typeof deadlines.get("set_session_name"), "number", "a control command is bounded"); + assert.ok(deadlines.get("set_session_name") > 0); + assert.equal(typeof deadlines.get("get_session_stats"), "number"); + // `login` and `export_html` legitimately take minutes: no deadline at all. + assert.equal(deadlines.get("login"), undefined); + assert.equal(deadlines.get("export_html"), undefined); +}); + +test("no more than 32 commands may wait on one child", async (t) => { + const resolvers = []; + const { wrapper } = snapshotSession(t, () => new Promise((resolve) => resolvers.push(resolve)), SnapshotWrapper, "pending-cap"); + const pending = Array.from({ length: 32 }, () => wrapper.send({ type: "get_state" })); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_busy" }); + for (const resolve of resolvers) resolve({}); + await Promise.all(pending); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 9436d4df2..b7551bcb1 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -63,6 +63,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. + */ +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 @@ -79,19 +95,39 @@ 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; 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; @@ -119,15 +155,44 @@ export class WebRpcError extends Error { /** `host_offline` only: "refused" when nothing was sent, "unknown" when the * link dropped after the command left, so it may still run on the host. */ readonly delivery?: "refused" | "unknown"; + /** Extra machine-readable facts the agent route forwards next to `code` + * (`maybeStarted`, `abortUnconfirmed`). */ + readonly details: Record | undefined; - constructor(message: string, code: string, delivery?: "refused" | "unknown") { + constructor(message: string, code: string, delivery?: "refused" | "unknown", details?: Record) { super(message); this.name = "WebRpcError"; this.code = code; if (delivery) this.delivery = delivery; + 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, + undefined, + 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 +241,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. @@ -443,6 +523,15 @@ export class AgentSessionWrapper { private reapTimer: ReturnType | null = null; private reapDeadline = 0; private lastActivityAt = 0; + /** Last frame the child sent. `silentForMs` reports from here: a command + * answer is not a frame, so polls never move this clock. */ + private lastFrameAt = 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; /** 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; @@ -462,6 +551,10 @@ export class AgentSessionWrapper { private readonly movedFromIds: string[] = []; private initPromise: Promise | null = null; private restarting = false; + /** A session switch whose answer never arrived: commands stay fenced until a + * state read reconciles which conversation the child now serves. */ + private identityStale = false; + private identityReconcile: Promise | null = null; private mcpListWaiter: { resolve: (text: string) => void; reject: (error: Error) => void; timer: ReturnType } | null = null; /** Synchronous mutex for getMcpList: checked+set before any await, so two * concurrent callers can never both enter (the waiter/promptRunning @@ -547,6 +640,8 @@ export class AgentSessionWrapper { this.host = host; this.launchAdvisor = launchAdvisor; this.fellBack = fellBack; + this.lastFrameAt = Date.now(); + this.lastEvidenceAt = this.lastFrameAt; } get sessionId(): string { @@ -576,6 +671,11 @@ export class AgentSessionWrapper { || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0 || this.pendingHostUris.size > 0); } + /** Time since the child's last frame (epoch-ms clock started at spawn). */ + silentForMs(): number { + return Math.max(0, Date.now() - this.lastFrameAt); + } + /** Local history navigation is busy control work, not an interruptible model turn. */ isEditingHistory(): boolean { return this.historyEditInFlight; @@ -1160,6 +1260,10 @@ 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.lastFrameAt = Date.now(); + this.lastEvidenceAt = this.lastFrameAt; 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; @@ -2006,7 +2110,9 @@ 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. + // 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.sendNativeMessageCommand({ 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)) { @@ -2024,7 +2130,7 @@ 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)), @@ -2032,10 +2138,13 @@ export class AgentSessionWrapper { } if (expired) { if (error instanceof RpcCommandTimeoutError && this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); - // 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("session-unresponsive", true); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); + // Nothing on this child will ever 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. + await this.destroyIfStalled(); + throw slowSessionError(); } throw error; } finally { @@ -2141,7 +2250,100 @@ 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); + } + + /** + * 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, + onReply?: (success: boolean, id: string) => void, + ): Promise { + try { + const result = await this.proc.sendCommand(command, timeoutMs, onReply); + 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, + onReply?: (success: boolean, id: string) => void, + ): Promise { + try { + return await this.sendRpc(command, timeoutMs, onReply); + } 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. + * + * `stopShared` is essential for a daemon-owned child: without it `dispose()` + * only drops this web app's membership and the wedged child keeps running on + * the host, so claiming it was stopped would be false. + * + * 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, + ...(this.host.id === LOCAL_HOST_ID ? {} : { hostId: this.host.id }), + 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" }); + } + // `_alive` turns false synchronously, so the wrapper is gone before this + // returns; the child itself is stopped by the same call (shared or not). + void this.destroyAndWait("stalled", true); + return true; } /** After branch/new_session/switch_session the child is on a different @@ -2157,6 +2359,33 @@ export class AgentSessionWrapper { return this._sessionId; } + /** + * A session switch timed out: the child may still be writing a new session + * file and may answer the switch after this request gave up. Until a state + * read names the conversation the child now serves, every command stays + * fenced — a command sent for the old id would otherwise act on the new + * conversation while the registry still maps the old id to this child. + * + * The flag outlives a failed read: the next command retries the reconcile + * instead of acting on a stale identity. + */ + /** One reconcile attempt for a fenced identity; throws `session_slow` when the child still cannot say. */ + private async reconcileFencedIdentity(): Promise { + this.identityReconcile ??= (async () => { + const oldId = this._sessionId; + // Generous: the child is busy by definition here, and `get_state` is the + // only read that names the new identity. + const state = await this.sendRpc({ type: "get_state" }, PROMPT_ACK_TIMEOUT_MS); + this.applyIdentity(state); + if (oldId && oldId !== this._sessionId) this.onIdentityChangeCallback?.(oldId, this._sessionId); + this.invalidateSessionLists(); + this.identityStale = false; + })().finally(() => { + this.identityReconcile = null; + }); + await this.identityReconcile; + } + private async editMessage(entryId: unknown): Promise { if (typeof entryId !== "string" || !entryId.trim()) { throw new WebRpcError("The edit target must be a user message", "invalid_edit_target"); @@ -2391,6 +2620,9 @@ 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(); } notifyRunningChange(); } @@ -2466,8 +2698,15 @@ export class AgentSessionWrapper { }; } - /** `origin`: the command a caller submitted through `send`; marked once its native message write begins. */ - private async sendNativeMessageCommand(command: { type: string; [key: string]: unknown }, timeoutMs?: number, origin?: object): Promise { + /** `origin`: the command a caller submitted through `send`; marked once its native message write begins. + * `timeoutDetails`: a timeout means the frame may already be in omp's stdin, so the error names what may + * already have happened instead of leaving clients to roll back and resend. */ + private async sendNativeMessageCommand( + command: { type: string; [key: string]: unknown }, + timeoutMs?: number, + origin?: object, + timeoutDetails?: Record, + ): Promise { const message = IMAGE_BEARING_COMMANDS.has(command.type); const proof = message && !this.messageReplacement && !this.hasPendingMessageCommands() ? watchReplacement(this, command, this.nativeQueuedMessages, this.messageCommandGeneration, false, @@ -2481,7 +2720,7 @@ export class AgentSessionWrapper { const generation = this.messageCommandGeneration; try { const replacement = proof ?? this.messageReplacement; - const result = await this.proc.sendCommand(command, timeoutMs, message && replacement + const result = await this.sendRpc(command, timeoutMs, message && replacement ? (_ok, id) => replacement.replied(proof ? command : origin ?? command, id) : undefined); if (message && isRecord(result) && result.agentInvoked === false) { @@ -2496,6 +2735,15 @@ export class AgentSessionWrapper { } catch (error) { proof?.stop(); if (message && error instanceof RpcCommandError) this.confirmMessageCommandGeneration(generation); + // Only callers that name the uncertainty translate the timeout here; the + // prompt path keeps the raw error because its own catch owns the run flags. + if (timeoutDetails && error instanceof RpcCommandTimeoutError) { + if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); + // A child the watchdog disposed never ran the frame: report a definite + // failure so the client recovers the text. Otherwise the frame sits in + // omp's stdin and the message may still be delivered. + throw this.destroyIfStalled() ? slowSessionError() : slowSessionError(timeoutDetails); + } throw error; } finally { if (message) this.pendingMessageCommands -= 1; @@ -2505,8 +2753,19 @@ export class AgentSessionWrapper { async send(command: Record): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); + // A timed-out session switch may still land: never act on a stale identity. + if (this.identityStale) { + try { + await this.reconcileFencedIdentity(); + } catch { + throw slowSessionError(); + } + } 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 (this.pendingCommands >= MAX_PENDING_COMMANDS) { + throw new WebRpcError("Too many commands are in flight for this session", "session_busy"); + } if (this.hostDown() || this.oldChildExiting) throw this.hostOfflineError("refused"); if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); @@ -2583,20 +2842,36 @@ export class AgentSessionWrapper { } if (ack?.agentInvoked === false) return ack; } catch (error) { + if (error instanceof RpcCommandTimeoutError) { + if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); + // 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 (!stalled) { + this.awaitingAgentStart = true; + this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; + } + if (!streamingBehavior) 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) { - if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); - // 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("session-unresponsive", true); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); - } + throw error; } finally { if (!streamingBehavior) { @@ -2612,11 +2887,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 && !this.streaming) return await this.queueWhileShellRunning(command); + // 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.sendNativeMessageCommand({ type, message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), - }, undefined, command); + }, PROMPT_ACK_TIMEOUT_MS, command, { maybeStarted: true }); return null; } @@ -2624,7 +2902,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; } @@ -2635,7 +2913,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. @@ -2654,22 +2935,24 @@ export class AgentSessionWrapper { } case "get_state": { + // 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. try { - const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + const state = await this.sendControl({ 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. + if (error instanceof WebRpcError && error.code === SESSION_SLOW_CODE) { 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; } } 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); } @@ -2677,7 +2960,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); @@ -2686,7 +2969,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 }; @@ -2694,14 +2977,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 }; } @@ -2715,7 +2998,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, }); @@ -2727,7 +3010,19 @@ 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. + // A timeout leaves the outcome unknown: the switch may still land after + // this request gives up, so the wrapper's identity is fenced until a + // state read reconciles it (see reconcileFencedIdentity). + let result: { cancelled: boolean }; + try { + result = await this.sendControl<{ cancelled: boolean }>(command as { type: string }, PROMPT_ACK_TIMEOUT_MS); + } catch (error) { + if (error instanceof WebRpcError && error.code === SESSION_SLOW_CODE) this.identityStale = true; + throw error; + } if (!result.cancelled) { const newSessionId = await this.refreshIdentityAfterSessionChange(); return { cancelled: false, newSessionId }; @@ -2742,7 +3037,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 } : {}), }); @@ -2761,32 +3056,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) }; } @@ -2803,6 +3098,7 @@ export class AgentSessionWrapper { if (("answers" in rest || pendingAsk) && !isAskAnswers(rest.answers) && !(pendingAsk && rest.cancelled === true)) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } + // Forgets the pending dialog; the cancel frame below settles it in other tabs. const wasPending = this.pendingUiRequests.has(id); this.forgetPendingUiRequest(id); const serverRequest = this.serverUiRequests.get(id); @@ -2839,7 +3135,7 @@ export class AgentSessionWrapper { // `isStreaming`. Read it then: an agent_end in the same batch is // applied before this await resumes. let deferred = this.streaming; - const result = await this.proc.sendCommand({ type: "bash", command: command.command as string }, undefined, () => { deferred = this.streaming; }); + const result = await this.sendRpc({ type: "bash", command: command.command as string }, undefined, () => { deferred = this.streaming; }); return { ...result, deferred }; } finally { this.bashRunning = false; @@ -2873,7 +3169,7 @@ export class AgentSessionWrapper { return null; } // Applied as the successful reply is read, before a call in the same host-link batch is routed. - await this.proc.sendCommand({ type: "set_host_tools", tools: merged }, undefined, (success) => { + await this.sendControl({ type: "set_host_tools", tools: merged }, GET_STATE_TIMEOUT_MS, undefined, (success) => { if (!success) return; this.hostToolNames = new Set(merged.map((t) => t.name as string)); this.registeredHostTools = valid.filter((tool) => !AGENT_TOOL_NAMES.has(tool.name as string)); @@ -2910,7 +3206,7 @@ export class AgentSessionWrapper { this.registeredHostUriSchemes = schemes; return null; } - await this.proc.sendCommand({ type: "set_host_uri_schemes", schemes }, undefined, (success) => { + await this.sendControl({ type: "set_host_uri_schemes", schemes }, GET_STATE_TIMEOUT_MS, undefined, (success) => { if (!success) return; this.registeredHostUriSchemes = schemes; this.hostUriSchemes = new Map(); @@ -2936,11 +3232,24 @@ export class AgentSessionWrapper { this.responseRunActive = false; this.streamSequence += 1; } - const result: unknown = await this.sendNativeMessageCommand( - command as { type: string }, - type === "predict_word" ? PREDICT_WORD_TIMEOUT_MS : undefined, - command, - ); + 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: unknown = timeoutMs === undefined + ? await this.sendRpc(command as { type: string }) + // A message-bearing passthrough (`abort_and_prompt`) keeps the native + // write bookkeeping the replacement watcher depends on. + : IMAGE_BEARING_COMMANDS.has(type) + ? await this.sendNativeMessageCommand(command as { type: string }, timeoutMs, command, timeoutDetails) + : await this.sendControl(command as { type: string }, timeoutMs, timeoutDetails); if (type === "set_thinking_level") this.invalidateSessionLists(); return result ?? null; } @@ -2962,11 +3271,13 @@ export class AgentSessionWrapper { */ private async queueWhileShellRunning(command: Record): Promise { const images = toImageContents(command.images); + // 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.sendNativeMessageCommand({ type: "follow_up", message: command.message as string, ...(images ? { images } : {}), - }, undefined, command); + }, PROMPT_ACK_TIMEOUT_MS, command, { maybeStarted: true }); return { queued: true, queue: "followUp", reason: "shellRunning" }; }