diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..5a4eb9559 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,18 @@ 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. +- **A chat another omp process owns is no longer silently forked.** omp ≥ 18.5 grants one writer per session file; a second `--resume` does not fail, it moves the conversation into a copy on its first write, which looked like a brand-new empty chat. omp-web now detects a foreign owner from portable read-only signals (another omp-web instance's resume list, a live `omp --resume` process, a transcript that is still being written; `OMP_WEB_FOREIGN_SCAN=0` disables only the process scan), marks the chat in the sidebar and composer, and refuses to spawn: `POST /api/agent/[id]` answers `409 session_running_elsewhere`, auto-naming and session resume skip it, and `/api/mcp` reports the live server list as unavailable. An explicit "Send anyway (copy)" sends with `?force=1`; a move that follows it is reported as `session_contention_fork` with links to both the original and the copy. Spawned service and scan children no longer inherit omp-web's own secrets on non-Windows platforms. +- **The sidebar keeps the ownership map the live stream delivered.** A session-list request that was already in flight can no longer replace a newer ownership snapshot, so foreign-session badges do not blink out until the next frame, and a foreign owner that is idle between turns no longer counts as a running session in the project totals or the running filter. +- **A confirmed "Send anyway" also covers shell commands.** A `!` command now forwards the confirmation as `?force=1`, so a chat another omp process owns runs the copy the user just approved instead of answering `session_running_elsewhere`. +- **A chat whose prompt never started still reports its child's death.** The exit notification is published before the terminal event clears the run flags, so a prompt that reached omp's stdin without an `agent_start` no longer loses the stall/crash notice. A late answer to a timed-out poll no longer resets the no-events clock, so a silent run stays measurable. +- **A timed-out preset on a fresh session no longer leaves an orphaned child.** When `set_model`/`set_thinking_level` times out during an `ensure_session` request, the route destroys the child it can never hand out; a session-owner refresh that lands while another scan is running is queued for the next pass instead of being dropped; and an exited child no longer keeps reporting the pid the ownership scan should ignore. +- **Naming a session no longer clears another chat's naming indicator.** A title-less auto-name response now honours the same active-session guard as the titled and error branches. --- diff --git a/README.md b/README.md index 7e7fec4d2..0454afb81 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,7 @@ host (KDE Plasma, and most Wayland/X11 desktops). | `OMP_WEB_DISABLE_AUTOUPDATE` | Set to `1` to disable update checks and in-app updates; restart after changing | `0` | | `OMP_WEB_NAME` | Name shown in browser tabs and installed-app names. `url`, `host` or `domain` (any case) uses the hostname the browser connected to, without port; localhost and IP addresses keep `omp web`. Any other value is used as-is. Restart after changing | `omp web` | | `OMP_WEB_OMP_BIN` | Path to `omp` binary if not on `PATH` | _auto-detected_ | +| `OMP_WEB_FOREIGN_SCAN` | Set to `0` to stop scanning the OS process table for `omp --resume ` owners (10 s cache). The other ownership signals stay active: a session held by another omp-web instance is still detected from its resume list, and a session file that is still being written is detected from its transcript. A terminal `omp` that sits idle on a file is then no longer detected | `1` (enabled) | | `OMP_WEB_DEV_ORIGIN` | Additional allowed hostname for the development server (no scheme or port); ignored in production | _None_ | | `PI_CODING_AGENT_DIR` | Custom omp agent directory | `~/.omp/agent` | | `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ | diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 892d71293..1a00fd05b 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -1,7 +1,8 @@ import { NextResponse } from "next/server"; -import { readSessionHeader } from "@/lib/session-reader"; +import { readSessionHeader, resolveSessionPath } from "@/lib/session-reader"; import { apiErrorResponse, resolveSessionPathOr404 } from "@/lib/api-utils"; -import { startRpcSession, getRpcSession, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager"; +import { startRpcSession, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager"; +import { detectSessionOwner } from "@/lib/session-owner"; import { RpcCommandError } from "@/lib/omp/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; @@ -35,7 +36,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 }); @@ -87,6 +88,29 @@ export async function POST( if ("response" in resolved) return resolved.response; const filePath = resolved.filePath; + // omp ≥ 18.5 grants one writer per session. A second `--resume` does not + // fail: it silently moves the conversation to a copy on its first write, + // which is exactly the "new chat appeared from nowhere" bug. Refuse the + // spawn (409) unless the client explicitly asked for the copy. + const force = new URL(req.url).searchParams.get("force") === "1"; + if (!force) { + const elsewhere = await detectSessionOwner(id, filePath, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }); + if (elsewhere) { + return NextResponse.json( + { + error: "This session is being run by another omp process", + code: "session_running_elsewhere", + elsewhere, + }, + { status: 409 }, + ); + } + } + const header = readSessionHeader(filePath); const { cwd } = resolveSpawnCwdResult(header?.cwd); @@ -150,14 +174,44 @@ export async function GET( try { const session = getRpcSession(id); if (!session || !session.isAlive()) { - return NextResponse.json({ running: false }); + // Not ours: tell the client who is running it, if anyone. Never spawns. + const filePath = await resolveSessionPath(id).catch(() => null); + const elsewhere = filePath + ? await detectSessionOwner(id, filePath, { isLocal: isLocallyOwnedSession, ownCrashed: isOwnCrashedSession, excludePids: getOwnChildPids() }) + : null; + return NextResponse.json({ running: false, alive: false, elsewhere }); } 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, elsewhere: null }); } 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/agent/new/route.ts b/app/api/agent/new/route.ts index 21585b727..bb4152528 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -18,7 +18,13 @@ function newSessionErrorResponse(error: unknown) { } if (error instanceof WebRpcError || error instanceof RpcCommandError) { return NextResponse.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 }, ); } @@ -83,6 +89,27 @@ export async function POST(req: Request) { return NextResponse.json({ success: true, sessionId: realSessionId, data: result }); } 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. + // `ensure_session` is the exception: it only asked for a runtime, so a + // timeout there can only be a preset (`set_model`/`set_thinking_level`) + // that never dispatched a run. The caller never receives that id + // (`ensureNewSession` throws before reading it), so nothing could adopt + // the child — destroy it instead of leaving an orphan to the watchdog. + if (error instanceof WebRpcError && error.code === "session_slow" && promptCommand.type !== "ensure_session") { + return NextResponse.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/mcp/route.ts b/app/api/mcp/route.ts index 03119e132..e64d316f7 100644 --- a/app/api/mcp/route.ts +++ b/app/api/mcp/route.ts @@ -2,7 +2,8 @@ import { NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import { deleteMcpServer, parseMcpListOutput, readDiscoveredMcpServers, readMcpConfig, readUserMcpConfig, type McpLiveServer, validateMcpServer, writeMcpServer } from "@/lib/omp/mcp-config"; import { readSessionHeader, resolveSessionPath } from "@/lib/session-reader"; -import { WebRpcError, getRpcSession, resolveSpawnCwdResult, startRpcSession } from "@/lib/rpc-manager"; +import { WebRpcError, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, startRpcSession } from "@/lib/rpc-manager"; +import { detectSessionOwner } from "@/lib/session-owner"; import { RpcCommandError } from "@/lib/omp/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { redactMcpServer } from "@/lib/omp/mcp-config"; @@ -85,22 +86,44 @@ export async function GET(request: Request) { // /api/agent/[id]): an alive child is reused as-is below, never replaced — // listing servers must stay side-effect-free. const advisor = params.get("advisor") === "1"; - let liveServers: ReturnType | undefined; + let liveServers: McpLiveServer[] | undefined; let liveError: string | undefined; if (includeLive && sessionId) { try { let session = getRpcSession(sessionId); + let foreignOwned = false; if (!session?.isAlive()) { const sessionFile = await resolveSessionPath(sessionId); if (!sessionFile) throw new Error("Session not found"); - const header = readSessionHeader(sessionFile); - const { cwd } = resolveSpawnCwdResult(header?.cwd); - // Fresh spawn only (an alive child is reused above): apply the - // caller's advisor opinion so a racing prompt doesn't inherit a - // wrong-flag child for its whole turn. - ({ session } = await startRpcSession(sessionId, sessionFile, cwd, undefined, advisor, header?.cwd)); + // Same gate as POST /api/agent/[id]: listing servers must not start a + // second writer. omp ≥ 18.5 moves a chat whose file another live + // process owns into a copy on its first write — that spawn is exactly + // the silent fork the ownership detection exists to prevent. + const elsewhere = await detectSessionOwner(sessionId, sessionFile, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }); + if (elsewhere) { + // Answer through the existing error path: an empty live list reads + // as "no MCP servers" in both clients, so the ownership message is + // what makes them fall back to the configured inventory and explain + // the missing live status. + foreignOwned = true; + liveError = "This session is being run by another omp process."; + } else { + const header = readSessionHeader(sessionFile); + const { cwd } = resolveSpawnCwdResult(header?.cwd); + // Fresh spawn only (an alive child is reused above): apply the + // caller's advisor opinion so a racing prompt doesn't inherit a + // wrong-flag child for its whole turn. + ({ session } = await startRpcSession(sessionId, sessionFile, cwd, undefined, advisor, header?.cwd)); + } + } + if (!foreignOwned) { + if (!session) throw new Error("Session not found"); + liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory); } - liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory); } catch (error) { liveError = sanitizeMcpLiveError(error); } diff --git a/app/api/sessions/[id]/auto-name/route.ts b/app/api/sessions/[id]/auto-name/route.ts index 80aea2ed2..4abf9f40f 100644 --- a/app/api/sessions/[id]/auto-name/route.ts +++ b/app/api/sessions/[id]/auto-name/route.ts @@ -1,8 +1,9 @@ import { NextResponse } from "next/server"; import { scanSessionInfo, setSessionTitle } from "@/lib/omp/session-files"; import { deriveSessionTitleFromFirstMessage, sanitizeSessionTitle } from "@/lib/session-title"; -import { getRpcSession, resolveSpawnCwdResult, startRpcSession, WebRpcError } from "@/lib/rpc-manager"; +import { getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, startRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { invalidateSessionCaches, readSessionHeader } from "@/lib/session-reader"; +import { detectSessionOwner } from "@/lib/session-owner"; import { resolveSessionPathOr404 } from "@/lib/api-utils"; /** @@ -29,6 +30,20 @@ export async function POST( if (!rpc?.isAlive?.()) { const resolved = await resolveSessionPathOr404(id); if ("response" in resolved) return resolved.response; + // A title is cosmetic: never spawn a second omp for a session another + // process owns (that spawn would fork the conversation on its dispose). + // Report the stored title instead, and write nothing to a foreign file. + const elsewhere = await detectSessionOwner(id, resolved.filePath, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }); + if (elsewhere) { + // No title yet is a valid answer here, not an error: the caller treats + // a 200 without a title as a silent no-op (another process owns it). + const stored = sanitizeSessionTitle(scanSessionInfo(resolved.filePath, false)?.title) || null; + return NextResponse.json({ title: stored, generated: false, usage: null }); + } try { const header = readSessionHeader(resolved.filePath); const { cwd } = resolveSpawnCwdResult(header?.cwd); diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index 97cd2386b..a52e880ed 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -27,7 +27,8 @@ import { import { resolveSessionPathOr404 } from "@/lib/api-utils"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { sessionPathKey } from "@/lib/paths"; -import { clearExitedRpcSession, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; +import { clearExitedRpcSession, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, WebRpcError } from "@/lib/rpc-manager"; +import { detectSessionOwner, type SessionElsewhere } from "@/lib/session-owner"; /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ @@ -35,6 +36,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 +240,34 @@ 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. + // `elsewhere` is always present when `agent` is: a client that just opened + // a foreign-owned session learns it from this one request, before it tries + // to send anything. + let agent: { running: boolean; alive: boolean; state?: unknown; elsewhere: SessionElsewhere | null } | 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, elsewhere: null }; } 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, + elsewhere: await detectSessionOwner(id, filePath, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }), + }; } } @@ -285,8 +307,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..2ff613712 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -1,6 +1,8 @@ import { NextResponse } from "next/server"; -import { getExitedRpcSession, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; +import { getExitedRpcSession, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, WebRpcError } from "@/lib/rpc-manager"; import { apiErrorResponse, resolveSessionPathOr404 } from "@/lib/api-utils"; +import { resolveSessionPath } from "@/lib/session-reader"; +import { detectSessionOwner } from "@/lib/session-owner"; export async function GET( _req: Request, @@ -15,21 +17,53 @@ 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, elsewhere: null }); } 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) { + // Our own crashed child: it does not make the session local, a foreign + // owner still matters (and its spawn must stay blocked). + const filePath = await resolveSessionPath(id).catch(() => null); + const elsewhere = filePath + ? await detectSessionOwner(id, filePath, { isLocal: isLocallyOwnedSession, ownCrashed: isOwnCrashedSession, excludePids: getOwnChildPids() }) + : null; + return NextResponse.json({ running: false, alive: false, exited, elsewhere }); + } const resolved = await resolveSessionPathOr404(id); if ("response" in resolved) return resolved.response; - return NextResponse.json({ running: false }); + const elsewhere = await detectSessionOwner(id, resolved.filePath, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }); + return NextResponse.json({ running: false, alive: false, elsewhere }); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 56af7d8e3..b70101093 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -1,7 +1,8 @@ import { NextResponse } from "next/server"; import { createHash } from "crypto"; import { listAllSessions } from "@/lib/session-reader"; -import { getRunningRpcSessions } from "@/lib/rpc-manager"; +import { getOwnChildPids, getRunningRpcSessions, isLocallyOwnedSession, isOwnCrashedSession } from "@/lib/rpc-manager"; +import { refreshElsewhereSessions } from "@/lib/session-owner"; // The session list mixes on-disk sessions with the live runningSessionIds set, // which changes on every agent turn, so it must never be cached by proxies or @@ -18,7 +19,18 @@ export async function GET(req: Request) { const sessions = await listAllSessions(); const runningSessions = getRunningRpcSessions(); const runningSessionIds = runningSessions.map((s) => s.id); - const body = { sessions, runningSessionIds, runningSessions }; + // Sessions a foreign omp writer holds: another omp-web instance, a terminal + // `omp`, or a transcript that was still open a moment ago. Detected here so + // the sidebar gets the badge with the list instead of a second round trip. + const elsewhereSessions = await refreshElsewhereSessions( + sessions.map((session) => ({ + id: session.id, + sessionFile: session.path, + mtimeMs: Date.parse(session.modified), + })), + { isLocal: isLocallyOwnedSession, ownCrashed: isOwnCrashedSession, excludePids: getOwnChildPids() }, + ); + const body = { sessions, runningSessionIds, runningSessions, elsewhereSessions }; const bodyJson = JSON.stringify(body); const etag = `"${createHash("sha1").update(bodyJson).digest("hex").slice(0, 16)}"`; if (req.headers.get("if-none-match") === etag) { diff --git a/components/AppShell.tsx b/components/AppShell.tsx index a0ea786a4..76a187b32 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1438,9 +1438,20 @@ export function AppShell({ appName }: { appName: string }) { method: "POST", }); const body = (await response.json().catch(() => ({}))) as { title?: string; error?: string; code?: string }; - if (!response.ok || !body.title) { + if (!response.ok) { throw new Error(body.error || body.code ? formatApiError(body) : `HTTP ${response.status}`); } + // A 200 without a title means another process owns the session and it has + // no stored title yet: a title is cosmetic, so this is a silent no-op, not + // the "HTTP 200" error a missing title used to produce. + if (!body.title) { + // Same guard as the branches below: the reset belongs to this session + // only, or it would re-enable the wand of the session now selected and + // let a second request start while its own naming is still pending. + if (activeSessionIdRef.current !== sessionId) return; + setAutoNameStatus({ kind: "idle" }); + return; + } const title = body.title.trim(); if (activeSessionIdRef.current !== sessionId) return; diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index dacc49fc8..71c4c82f1 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -11,6 +11,7 @@ import { ConfirmDialog } from "@/components/ui/field"; import { useDictation } from "@/hooks/useDictation"; import { toastBtwError } from "@/hooks/useBtw"; import type { GenerationSpeedInfo, SessionStatsInfo, SlowModeScope, UsageLimitState } from "@/lib/pi-types"; +import type { SessionElsewhere } from "@/lib/types"; import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; @@ -151,7 +152,10 @@ const TOOL_PRESET_OPTIONS: Array<{ value: ToolPreset; descriptionKey: string }> interface Props { /** Only a rejected submission is restored; completed/superseded runs must not be replayed. */ - onSend: (message: string, images?: AttachedImage[]) => Promise; + onSend: (message: string, images?: AttachedImage[], options?: { force?: boolean }) => Promise; + /** Another omp process owns this session: the composer blocks and offers an + * explicit "send anyway (copy)" instead of forking the conversation. */ + foreignRun?: SessionElsewhere | null; /** Ghost-text word completion for the draft (omp `predict_word`); absent = no ghost text. */ onPredictWord?: PredictWord; onPredictWordFeedback?: PredictWordFeedback; @@ -330,7 +334,7 @@ function menuDropStyle(placement: MenuPlacement, maxHeight: number | null): Reac } export const ChatInput = memo(forwardRef(function ChatInput({ - onSend, onPredictWord, onPredictWordFeedback, onAbort, onSteer, onFollowUp, isStreaming, model, isAutoModelSelection, modelNames, modelList, modelError, modelsLoading, onModelChange, fastModeEnabled, fastModeActive, usageLimit, fastModeSupported, onFastModeChange, slowModeSupported, slowModeEnabled, slowModeScope, onSlowModeChange, + onSend, foreignRun, onPredictWord, onPredictWordFeedback, onAbort, onSteer, onFollowUp, isStreaming, model, isAutoModelSelection, modelNames, modelList, modelError, modelsLoading, onModelChange, fastModeEnabled, fastModeActive, usageLimit, fastModeSupported, onFastModeChange, slowModeSupported, slowModeEnabled, slowModeScope, onSlowModeChange, onAbortCompaction, isCompacting, compactResult, thinkingLevel, onThinkingLevelChange, availableThinkingLevels, thinkingLevelMap, modelNameOverride, toolPreset, onToolPresetChange, @@ -400,6 +404,11 @@ export const ChatInput = memo(forwardRef(function ChatIn [locale], ); const [value, setValue] = useState(() => (draftKey ? getDraft(draftKey)?.value ?? "" : "")); + // "Send anyway (copy)" confirmation: only an explicit click here sets force. + const [foreignConfirmOpen, setForeignConfirmOpen] = useState(false); + useEffect(() => { + if (!foreignRun) setForeignConfirmOpen(false); + }, [foreignRun]); const [queuedDeleteTarget, setQueuedDeleteTarget] = useState<{ text: string; kind: "follow-up" | "steer"; @@ -966,6 +975,12 @@ export const ChatInput = memo(forwardRef(function ChatIn const msg = raw.trim(); if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; if (submissionBlockedRef.current || isStreaming) return; + if (foreignRun) { + // Another omp process owns this file; sending would move the conversation + // into a copy. Keep the draft and ask for the explicit override. + setForeignConfirmOpen(true); + return; + } onAudioUnlock?.(); if (sendSideQuestion(msg, overrideText)) return; const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); @@ -991,7 +1006,31 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt, runBuiltinCommand, sendSideQuestion, foreignRun]); + + /** The user confirmed the copy: send the draft with the explicit override. */ + const confirmSendAnyway = useCallback(() => { + const msg = value.trim(); + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; + if (submissionBlockedRef.current || isStreaming) return; + setForeignConfirmOpen(false); + onAudioUnlock?.(); + const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); + if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; + const key = draftKeyRef.current; + const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; + const recovery = { text: composedMessage, images: images?.map(imageToDraftImage) }; + const pending = onSend(composedMessage, images, { force: true }); + clearInput(); + pending.then((result) => { + if (result.status !== "rejected") return; + const destination = result.recoveryKey ?? key; + if (destination) recoverDraft(destination, recovery); + }).catch((error) => { + if (key) recoverDraft(key, recovery); + console.error("[chatInput] forced send failed", error); + }); + }, [value, isStreaming, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt]); const { isRecording, isPaused, @@ -2787,6 +2826,50 @@ export const ChatInput = memo(forwardRef(function ChatIn )} )} + {/* Foreign ownership: another omp process holds this session's file */} + {foreignRun && ( +
0 ? 0 : "var(--radius-card) var(--radius-card) 0 0", + background: "color-mix(in srgb, var(--accent) 8%, var(--bg-panel))", + padding: "7px 14px", + display: "flex", + alignItems: "center", + gap: 8, + fontSize: 12, + color: "var(--text)", + }} + > + + + {t("sessionOwnership.bannerTitle")}{" "} + {t("sessionOwnership.bannerBody")} + + +
+ )} {/* Live agent status bar — attached to composer's top edge */} {statusText && (
(function ChatIn flexDirection: "column", background: "var(--bg)", border: `1px solid ${bashMode ? "var(--tool-bg)" : "color-mix(in srgb, var(--border) 70%, transparent)"}`, - borderRadius: (queuedCount > 0 || Boolean(statusText)) ? "0 0 var(--radius-card) var(--radius-card)" : "var(--radius-card)", + borderRadius: (queuedCount > 0 || Boolean(statusText) || Boolean(foreignRun)) ? "0 0 var(--radius-card) var(--radius-card)" : "var(--radius-card)", padding: "12px 12px 10px", boxShadow: "var(--shadow-card)", } as React.CSSProperties} @@ -3597,8 +3680,10 @@ export const ChatInput = memo(forwardRef(function ChatIn type="button" className="composer-primary-action" onClick={isRecording || isPaused || isReviewing ? () => stopAndFinishDictation("send") : () => void handleSend()} - disabled={submissionBlocked || isTranscribing || !(isRecording || isPaused || isReviewing || value.trim() || attachedImages.length || attachedTextFiles.length)} - title={isRecording || isPaused || isReviewing ? t("chatInput.sendDictation") : t("chatInput.send")} + disabled={submissionBlocked || isTranscribing || Boolean(foreignRun) || !(isRecording || isPaused || isReviewing || value.trim() || attachedImages.length || attachedTextFiles.length)} + title={foreignRun + ? t("sessionOwnership.bannerTitle") + : isRecording || isPaused || isReviewing ? t("chatInput.sendDictation") : t("chatInput.send")} style={{ display: "flex", alignItems: "center", gap: 6, background: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || attachedImages.length || attachedTextFiles.length) ? "var(--accent-strong)" : "var(--bg-panel)", @@ -3634,6 +3719,18 @@ export const ChatInput = memo(forwardRef(function ChatIn
)} + {/* Explicit override: sending now continues in a COPY of the session. */} + + diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 52a5354aa..f8963d4c2 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,13 +525,14 @@ 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, isAutoModelSelection, agentPhase, activeGoal, activePlan, liveToolResults, + foreignRun, subagents, subagentEvents, subagentTranscriptVersions, activeSubagentCount, currentTodoPhase, todoPhases, isNew, sessionIdRef, messagesEndRef, scrollContainerRef, @@ -1023,9 +1031,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 +1049,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); @@ -1061,6 +1072,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa ref={composerRef} sessionInfoContainer={sessionInfoContainer} onSend={handleSend} + foreignRun={foreignRun} onPredictWord={handlePredictWord} onPredictWordFeedback={handlePredictWordFeedback} onAbort={handleAbort} diff --git a/components/SessionSidebar-chrome.tsx b/components/SessionSidebar-chrome.tsx index 2dde5a106..acc8d0f14 100644 --- a/components/SessionSidebar-chrome.tsx +++ b/components/SessionSidebar-chrome.tsx @@ -398,6 +398,30 @@ function RunningSessionIndicator({ size = 14 }: { size?: number }) { ); } +/** Another omp process owns the session: a hollow ring, distinct from the + * solid running spinner and from the unread dot. */ +function ElsewhereSessionIndicator({ title, size = 14 }: { title: string; size?: number }) { + return ( + + + + ); +} function ExitedSessionIndicator({ title, size = 14 }: { title: string; size?: number }) { return ( ; + /** Sessions another omp process holds, keyed by id (badge only). */ + runningElsewhere: Map; unreadSessionIds: Set; recentlyCompletedIds?: Set; exitedSessions: Map; @@ -77,6 +81,7 @@ function ProjectRow({ hiddenCount, selectedSessionId, runningSessionIds, + runningElsewhere, unreadSessionIds, recentlyCompletedIds, exitedSessions, @@ -399,6 +404,7 @@ function ProjectRow({ node={node} selectedSessionId={selectedSessionId} runningSessionIds={runningSessionIds} + runningElsewhere={runningElsewhere} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} recentlyCompletedIds={recentlyCompletedIds} @@ -450,6 +456,7 @@ const SessionTreeItem = memo(function SessionTreeItem({ node, selectedSessionId, runningSessionIds, + runningElsewhere, unreadSessionIds, exitedSessions, recentlyCompletedIds, @@ -462,6 +469,7 @@ const SessionTreeItem = memo(function SessionTreeItem({ node: SessionTreeNode; selectedSessionId: string | null; runningSessionIds: Set; + runningElsewhere: Map; unreadSessionIds: Set; exitedSessions: Map; recentlyCompletedIds?: Set; @@ -479,6 +487,7 @@ const SessionTreeItem = memo(function SessionTreeItem({ // check then never re-renders unless this row's flags actually changed. const isSelected = sessionId === selectedSessionId; const isRunning = runningSessionIds.has(sessionId); + const elsewhere = runningElsewhere.get(sessionId); const isUnread = unreadSessionIds.has(sessionId); const isRecentlyCompleted = !isRunning && (recentlyCompletedIds?.has(sessionId) ?? false); const exited = exitedSessions.get(sessionId); @@ -513,6 +522,7 @@ const SessionTreeItem = memo(function SessionTreeItem({ session={node.session} isSelected={isSelected} isRunning={isRunning} + elsewhere={elsewhere} isUnread={isUnread} exited={exited} isRecentlyCompleted={isRecentlyCompleted} @@ -534,6 +544,7 @@ const SessionTreeItem = memo(function SessionTreeItem({ node={child} selectedSessionId={selectedSessionId} runningSessionIds={runningSessionIds} + runningElsewhere={runningElsewhere} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} recentlyCompletedIds={recentlyCompletedIds} @@ -564,6 +575,12 @@ const SessionTreeItem = memo(function SessionTreeItem({ const id = prev.node.session.id; if ((prev.recentlyCompletedIds?.has(id) ?? false) !== (next.recentlyCompletedIds?.has(id) ?? false)) return false; } + if (prev.runningElsewhere !== next.runningElsewhere) { + const id = prev.node.session.id; + const before = prev.runningElsewhere.get(id); + const after = next.runningElsewhere.get(id); + if (before !== after) return false; + } if (prev.unreadSessionIds !== next.unreadSessionIds) { const id = prev.node.session.id; if (prev.unreadSessionIds.has(id) !== next.unreadSessionIds.has(id)) return false; @@ -579,6 +596,7 @@ const SessionItem = memo(function SessionItem({ session, isSelected, isRunning, + elsewhere, isUnread, exited, isRecentlyCompleted, @@ -594,6 +612,8 @@ const SessionItem = memo(function SessionItem({ session: SessionInfo; isSelected: boolean; isRunning?: boolean; + /** Another omp process holds this session (badge + tooltip). */ + elsewhere?: ElsewhereSessionInfo; isUnread?: boolean; exited?: ExitedRpcSession; isRecentlyCompleted?: boolean; @@ -645,7 +665,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. @@ -758,14 +786,16 @@ const SessionItem = memo(function SessionItem({ {session.worktreeBranch && } {hasChildren && }
- {(isRunning || exited || isRecentlyCompleted || isUnread) && ( + {(isRunning || exited || isRecentlyCompleted || isUnread || elsewhere) && ( {isRunning ? - : exited - ? - : isRecentlyCompleted - ? + : elsewhere + ? + : exited + ? + : isRecentlyCompleted + ? : } )} diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index 5d37da060..5be531a0b 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -1,7 +1,7 @@ "use client"; import { memo, useEffect, useLayoutEffect, useState, useCallback, useRef, useMemo, useDeferredValue } from "react"; -import type { ExitedRpcSession, ManagedProject, ProjectLaunchConfig, SessionInfo } from "@/lib/types"; +import type { ElsewhereSessionInfo, ExitedRpcSession, ManagedProject, ProjectLaunchConfig, SessionInfo } from "@/lib/types"; import { useI18n } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; import { DirectoryPicker } from "./DirectoryPicker"; @@ -136,6 +136,10 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, const [worktreeStateByProject, setWorktreeStateByProject] = useState>({}); const [sessionRefreshDone, setSessionRefreshDone] = useState(false); const [runningSessionIds, setRunningSessionIds] = useState>(() => new Set()); + // Sessions another omp process holds (other omp-web instance / terminal). + // Badge-only: they never enter runningSessionIds, so unread markers and + // notifications keep meaning "a run THIS instance started". + const [elsewhereSessions, setElsewhereSessions] = useState>(() => new Map()); const [runningSessionCwds, setRunningSessionCwds] = useState>({}); const [exitedSessions, setExitedSessions] = useState>(() => new Map()); const knownRunningCwdsRef = useRef>(new Map()); @@ -218,8 +222,15 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, if (!res.ok) throw new Error(`HTTP ${res.status}`); const etag = res.headers.get("ETag"); if (etag) sessionsEtagRef.current = etag; - const data = await res.json() as { sessions: SessionInfo[]; runningSessionIds?: string[]; runningSessions?: Array<{ id: string; cwd: string }> }; + const data = await res.json() as { sessions: SessionInfo[]; runningSessionIds?: string[]; runningSessions?: Array<{ id: string; cwd: string }>; elsewhereSessions?: ElsewhereSessionInfo[] }; setAllSessions(data.sessions); + // Same rule as the running set below: once an SSE frame has delivered an + // ownership snapshot, the stream owns it. A GET that was already in + // flight can be older than that frame, and applying it would drop the + // foreign-session badges until the next frame. + if (!sseAuthoritativeRef.current) { + setElsewhereSessions(new Map((data.elsewhereSessions ?? []).map((entry) => [entry.id, entry]))); + } if (data.runningSessions) { for (const rs of data.runningSessions) { if (rs.id && rs.cwd) knownRunningCwdsRef.current.set(rs.id, rs.cwd); @@ -352,12 +363,14 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, runningSessionIds?: string[]; runningSessions?: Array<{ id: string; cwd: string }>; exitedSessions?: ExitedRpcSession[]; + elsewhereSessions?: ElsewhereSessionInfo[]; refreshSessionList?: boolean; sessionIds?: string[]; }; if (data.type === "running") { sseAuthoritativeRef.current = true; setRunningSessionIds(new Set(data.runningSessionIds ?? [])); + setElsewhereSessions(new Map((data.elsewhereSessions ?? []).map((entry) => [entry.id, entry]))); setExitedSessions(new Map((data.exitedSessions ?? []).map((session) => [session.id, session]))); if (data.runningSessions) { const nextCwds: Record = {}; @@ -768,9 +781,20 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, () => groupSessionsByProject(sortedProjects, visibleSessions), [sortedProjects, visibleSessions], ); + // "Running" for the sidebar = a run this instance owns (spinner, unread, + // notifications) plus a run another omp process holds (badge/filter). The two + // stay separate in state; only the aggregate views merge them. + const liveOrElsewhereIds = useMemo(() => { + if (elsewhereSessions.size === 0) return runningSessionIds; + const next = new Set(runningSessionIds); + for (const [id, info] of elsewhereSessions) { + if (info.running) next.add(id); + } + return next; + }, [runningSessionIds, elsewhereSessions]); const projectActivity = useMemo( - () => projectActivityCounts(visibleSessions, runningSessionIds, unreadSessionIds, exitedSessions.keys()), - [visibleSessions, runningSessionIds, unreadSessionIds, exitedSessions], + () => projectActivityCounts(visibleSessions, liveOrElsewhereIds, unreadSessionIds, exitedSessions.keys()), + [visibleSessions, liveOrElsewhereIds, unreadSessionIds, exitedSessions], ); // Client-side filtering (Workspaces header: search + "running only"). @@ -847,7 +871,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, const entries: { project: ManagedProject; sessions: SessionInfo[]; scores?: Map; rank: number }[] = []; for (const project of sortedProjects) { let list = sessionsByProject.get(project.path) ?? []; - if (runningOnly) list = list.filter((s) => runningSessionIds.has(s.id) || effectiveRecentCompletedSet.has(s.id)); + if (runningOnly) list = list.filter((s) => runningSessionIds.has(s.id) || effectiveRecentCompletedSet.has(s.id) || liveOrElsewhereIds.has(s.id)); if (!query) { if (list.length === 0 && runningOnly) continue; entries.push({ project, sessions: list, rank: 0 }); @@ -871,7 +895,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, // Best match first; ties keep the workspace order (stable sort). if (query) entries.sort((a, b) => b.rank - a.rank); return entries; - }, [sortedProjects, sessionsByProject, runningOnly, trimmedSearchQuery, currentTranscriptSearch, runningSessionIds, effectiveRecentCompletedSet]); + }, [sortedProjects, sessionsByProject, runningOnly, trimmedSearchQuery, currentTranscriptSearch, runningSessionIds, effectiveRecentCompletedSet, liveOrElsewhereIds]); const treesByProject = useMemo(() => { const m = new Map>(); @@ -1645,6 +1669,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, hiddenCount={filtersActive ? 0 : Math.max(0, tree.length - MAX_PROJECT_SESSIONS)} selectedSessionId={selectedSessionId} runningSessionIds={runningSessionIds} + runningElsewhere={elsewhereSessions} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} recentlyCompletedIds={effectiveRecentCompletedSet} 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..883c3da85 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,26 @@ 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: [], + elsewhereSessions: [], + }); + } 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 +183,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 +384,7 @@ function resetWorld() { world.nativeHistories.clear(); world.btwHistory.clear(); world.abortRestoreQueue = null; + world.runningSessionIds = []; } function primeSession(sid, messages) { @@ -434,6 +458,23 @@ test("the queue panel shows omp's snapshot on load and follows queue_update, not assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["later"] }); }); +test("a 'send anyway' bash message forwards force so a foreign owner accepts the copy", async () => { + // The confirmation in ChatInput is the explicit opt-in for `force=1`. A `!` + // command took the shell path, which dropped the flag: the POST hit the + // ownership gate unforced and came back `session_running_elsewhere` instead of + // running the copy the user just confirmed. + resetWorld(); + primeSession("bash-force", [userMsg("u0", "q")]); + const w = await mountSession("bash-force"); + await act(async () => { + await w.latest.handleSend("!ls", undefined, { force: true }); + await sleep(30); + }); + const posts = callsTo("POST", "/api/agent/").filter((call) => call.body?.type === "bash"); + assert.equal(posts.length, 1, "the shell command reached the agent route"); + assert.ok(posts[0].url.includes("force=1"), `the confirmed send carries force, got ${posts[0].url}`); +}); + test("a prompt queued behind a running shell command drops the phantom turn and reports it", async () => { resetWorld(); primeSession("bash-queue", [userMsg("u0", "q")]); @@ -1338,6 +1379,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 +2054,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 +4873,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..326bf2a6f 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -1,6 +1,6 @@ "use client"; -import { useState, useCallback, useRef, useEffect, useMemo, useReducer } from "react"; +import { Fragment, createElement, useState, useCallback, useRef, useEffect, useMemo, useReducer } from "react"; import type { AgentMessage, ExitedRpcSession, @@ -8,6 +8,7 @@ import type { ExtensionStatusItem, ExtensionWidgetItem, SessionContext, + SessionElsewhere, SessionInfo, SessionTreeNode, ToolResultMessage, @@ -15,7 +16,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"; @@ -27,6 +28,7 @@ import { createReconcileGuard, type ReconcileGuard } from "@/lib/reconcile-guard import { getToolNamesForPreset, type ToolPreset } from "@/lib/tool-presets"; import { getPreferredToolPreset, setPreferredToolPreset } from "@/lib/tool-preset-preference"; import { toast } from "@/components/ui/toast"; +import Link from "next/link"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { validateOutgoingPrompt } from "@/lib/image-attachments"; import { createActiveGoal, parseActiveGoal, type ActiveGoal, type ActivePlan } from "@/lib/web-mode-state"; @@ -77,6 +79,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 +177,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; @@ -222,6 +287,21 @@ export function useAgentSession(opts: UseAgentSessionOptions) { streamStateRef.current = streamState; const [agentRunning, setAgentRunning] = useState(false); const [bashRunning, setBashRunning] = useState(false); + // Another omp process (another omp-web instance, a terminal) holds this + // session's file. omp moves the conversation to a copy on our first write, so + // the composer blocks until the user explicitly sends anyway. + const [foreignRun, setForeignRun] = useState(null); + const foreignRunRef = useRef(null); + const applyForeignRun = useCallback((next: SessionElsewhere | null) => { + const previous = foreignRunRef.current; + if (previous === next) return; + if (previous && next + && previous.kind === next.kind && previous.source === next.source + && previous.running === next.running && previous.active === next.active + && previous.lastActivityAt === next.lastActivityAt) return; + foreignRunRef.current = next; + setForeignRun(next); + }, []); const [pendingBash, setPendingBash] = useState<{ command: string; excludeFromContext: boolean } | null>(null); // False once this hook instance unmounts: background loops (prompt/bash // settlement polling) must not keep firing on a dead instance. @@ -273,6 +353,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); @@ -417,7 +502,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const initialScrollDoneRef = useRef(false); const pendingScrollToUserRef = useRef(false); const completionScrollAllowedRef = useRef(true); - const executeBashRef = useRef<(command: string, excludeFromContext: boolean) => Promise | undefined>(undefined); + const executeBashRef = useRef<(command: string, excludeFromContext: boolean, force?: boolean) => Promise | undefined>(undefined); const userScrollIntentUntilRef = useRef(0); const ignoreProgrammaticScrollUntilRef = useRef(0); const messagesEndRef = useRef(null); @@ -455,6 +540,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,8 +879,9 @@ 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; elsewhere?: SessionElsewhere | null }; if (!hookAliveRef.current || sessionIdRef.current !== sid) return; + applyForeignRun(agentState.alive ? null : agentState.elsewhere ?? null); applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, agentState.state?.skillDiagnostics); const applied = applyAuthoritativeModel(toThinkingModelMeta(agentState.state?.model), token); if (!applied) return; // stale snapshot — drop its thinking level too @@ -802,7 +896,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); @@ -814,7 +908,30 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } catch { // Best effort; the next loadSession/reconcile re-syncs. } - }, [applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync]); + }, [applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, applyForeignRun]); + + // 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; @@ -881,8 +998,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; elsewhere?: SessionElsewhere | null }; if (!hookAliveRef.current) return null; if (sessionIdRef.current !== sid) { if (showLoading) setLoading(false); @@ -897,6 +1032,11 @@ 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. + applyForeignRun(agentState.alive ? null : agentState.elsewhere ?? null); applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, liveState?.skillDiagnostics); const modelApplied = applyAuthoritativeModel(toThinkingModelMeta(liveState?.model), token); if (liveState) { @@ -905,7 +1045,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 +1058,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 +1085,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, applyForeignRun, markSessionAliveStateUnknown]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1116,8 +1256,23 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const sid = sessionIdRef.current; if (!sid || !sessionIds.includes(sid) || editInFlightRef.current?.sessionId === sid) return; void catchUp.request(); + // A write is also the moment a foreign owner can appear (a terminal omp + // or another instance started on this chat). This bus is the only channel + // that announces it while the tab already has the chat open, so re-read + // ownership here — the state route is read-only and never spawns. Our own + // run never coexists with a foreign owner, so skip it then. + if (agentRunningRef.current || bashRunningRef.current) return; + void fetch(`/api/sessions/${encodeURIComponent(sid)}/state`) + .then((res) => (res.ok ? res.json() : null)) + .then((data: { alive?: boolean; elsewhere?: SessionElsewhere | null } | null) => { + if (!hookAliveRef.current || sessionIdRef.current !== sid || !data) return; + // `alive` (our child exists), not `running` (a turn is in flight): + // an idle wrapper still owns the session and is no foreign owner. + applyForeignRun(data.alive ? null : data.elsewhere ?? null); + }) + .catch(() => {}); }); - }, [catchUp]); + }, [catchUp, applyForeignRun]); // Reconnect actions captured after their definitions (host-tool and URI // registrations are per-wrapper and are not persisted by omp, and the @@ -1589,7 +1744,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 +1799,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 +1816,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 +1856,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,13 +1937,55 @@ 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; elsewhere?: SessionElsewhere | null }; // 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. if (!hookAliveRef.current || sessionIdRef.current !== sid || promptRunIdRef.current !== runId || responseRunVersionRef.current !== responseVersion) return; + applyForeignRun(data.alive ? null : data.elsewhere ?? null); const state = data.state; applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, state?.skillDiagnostics); if (!promptDispatchPendingRef.current && state?.responseObserved) runHadContentRef.current = true; @@ -1807,7 +2027,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { void reconcileAgentState(sid); } } - }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster]); + }, [applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, finishPromptWithoutStream, refreshSubagentRoster, applyForeignRun, 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 +2084,28 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return () => clearInterval(timer); }, [externalRunActive, catchUp]); + // Another process owns the session: re-check ownership at the transcript + // poll cadence so the banner clears the moment that process exits (a + // terminal `omp`, or another instance finishing). The state route is + // read-only and never spawns, so this cannot fork anything. + useEffect(() => { + if (!foreignRun?.active) return; + const timer = setInterval(() => { + const sid = sessionIdRef.current; + if (!hookAliveRef.current || !sid) return; + void fetch(`/api/sessions/${encodeURIComponent(sid)}/state`) + .then((res) => (res.ok ? res.json() : null)) + .then((data: { alive?: boolean; elsewhere?: SessionElsewhere | null } | null) => { + if (!hookAliveRef.current || sessionIdRef.current !== sid || !data) return; + // `alive` (our child exists), not `running` (a turn is in flight): + // an idle wrapper still owns the session and is no foreign owner. + applyForeignRun(data.alive ? null : data.elsewhere ?? null); + }) + .catch(() => {}); + }, EXTERNAL_RUN_POLL_MS); + return () => clearInterval(timer); + }, [foreignRun?.active, applyForeignRun]); + // 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 +2124,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 +2144,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 +2163,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 +2291,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 +2361,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); @@ -2135,6 +2401,46 @@ export function useAgentSession(opts: UseAgentSessionOptions) { onAgentEnd?.(); break; } + case "session_contention_fork": { + // omp moved this conversation to a copy because another process held + // the file: a forced send raced the owner, or a stale second writer won. + // The copy carries the user's text, so report it instead of letting the + // sidebar show an unexplained new chat. Both links matter: the original + // is read-only from here on, the copy is where the reply continues. + const fromId = typeof event.fromId === "string" ? event.fromId : null; + const toId = typeof event.toId === "string" ? event.toId : null; + const linkStyle = { color: "var(--accent)", textDecoration: "underline" }; + // This hook is a .ts module (no JSX): build the description with + // createElement, as the toast tests do. + toast.info( + translate("sessionOwnership.copyNoticeTitle"), + createElement( + Fragment, + null, + translate("sessionOwnership.copyNotice"), + fromId ? " " : null, + fromId + ? createElement( + Link, + { href: `/?session=${encodeURIComponent(fromId)}`, style: linkStyle }, + translate("sessionOwnership.openOriginal"), + ) + : null, + toId ? " · " : null, + toId + ? createElement( + Link, + { href: `/?session=${encodeURIComponent(toId)}`, style: linkStyle }, + translate("sessionOwnership.openCopy"), + ) + : null, + ), + { timeout: 0 }, + ); + // The copy is ours now; the original may still be foreign. + applyForeignRun(null); + break; + } case "prompt_result": // A prompt handled entirely by a builtin/extension slash command: // no agent_start/agent_end pair will follow. @@ -2587,7 +2893,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } -}, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); +}, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot, applyForeignRun]); handleAgentEventRef.current = handleAgentEvent; syncActionsRef.current = { metadata: (context, version, hasLive = liveModelMeta !== null || currentModelOverride !== null) => { @@ -2683,11 +2989,22 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return snapshot.entryIds; }, []); - const handleSend = useCallback(async (message: string, images?: AttachedImage[]): Promise => { + const handleSend = useCallback(async ( + message: string, + images?: AttachedImage[], + options: { force?: boolean } = {}, + ): Promise => { const trimmedMessage = message.trim(); if (!trimmedMessage && !images?.length) return { status: "rejected" }; if (agentRunningRef.current || bashRunningRef.current || editInFlightRef.current) return { status: "rejected" }; if (initialHydrationPendingRef.current) return { status: "rejected" }; + // Another omp process holds the file: sending would fork the conversation + // into a copy on omp's first write. The composer banners this and offers an + // explicit "send anyway"; anything that bypasses it stops here. + if (foreignRunRef.current && !options.force) { + addNotice({ type: "warning", message: translate("sessionOwnership.sendBlocked") }); + return { status: "rejected" }; + } const isSlashCommandPrompt = !images?.length && trimmedMessage.startsWith("/"); // omp runs TUI-only commands such as `/guided-goal` nowhere but its own // terminal, so over RPC the text is sent as an ordinary prompt and the turn @@ -2707,7 +3024,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const isExcluded = trimmedMessage.startsWith("!!"); const bashCmd = (isExcluded ? trimmedMessage.slice(2) : trimmedMessage.slice(1)).trim(); if (!bashCmd) return { status: "rejected" }; - await executeBashRef.current?.(bashCmd, isExcluded); + await executeBashRef.current?.(bashCmd, isExcluded, options.force); return { status: "accepted" }; } @@ -2733,6 +3050,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; @@ -2797,14 +3115,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { type: "prompt", message, ...(piImages?.length ? { images: piImages } : {}), - })); + }, { force: options.force })); } } else if (session) { const sid = sessionIdRef.current ?? session.id; sentSessionId = sid; // The event route is observer-only. Start or resume the web-owned RPC // wrapper with a supported command before opening the SSE connection. - await sendAgentCommand(sid, { type: "get_state" }); + await sendAgentCommand(sid, { type: "get_state" }, { force: options.force }); await ensureEventsConnected(sid); void refreshSubagentRoster(sid); void registerHostTools(sid); @@ -2817,7 +3135,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { type: "prompt", message, ...(piImages?.length ? { images: piImages } : {}), - })); + }, { force: options.force })); } if (promptRunIdRef.current === promptRunId) promptDispatchPendingRef.current = false; if (queuedBehindShell) { @@ -2846,8 +3164,35 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } catch (e) { if (promptRunIdRef.current !== promptRunId) return { status: "superseded" }; promptDispatchPendingRef.current = false; + if (e instanceof AgentCommandError && e.code === "session_running_elsewhere") { + // Another omp owns the session file. Nothing was started, nothing was + // dropped: roll the optimistic turn back, hand the text to the composer + // and let the banner offer the explicit "send anyway (copy)". + applyForeignRun(e.elsewhere ?? { kind: "terminal", source: "transcript", running: false, active: true }); + setOptimisticUserMessage(null); + agentRunningRef.current = false; + catchUp.invalidate(); + eventCoalescer.reset(); + setAgentRunning(false); + setAgentPhase(null); + clearLiveToolResults(); + lastQuotaErrorRef.current = null; + lastRunErrorRef.current = null; + slashCommandRunRef.current = false; + dispatch({ type: "end" }); + return { status: "rejected", recoveryKey }; + } 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({ @@ -2870,7 +3215,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { dispatch({ type: "end" }); return { status: "rejected", recoveryKey }; } - }, [catchUp, eventCoalescer, isNew, newSessionCwd, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, registerHostTools, registerHostUriSchemes, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries]); + }, [catchUp, eventCoalescer, isNew, newSessionCwd, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, registerHostTools, registerHostUriSchemes, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries, applyForeignRun]); /** Abort the running agent and send the message as a fresh prompt * (abort_and_prompt). Only valid mid-run; the old turn's agent_end is @@ -2926,6 +3271,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; } @@ -2939,7 +3295,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [addNotice, catchUp, eventCoalescer, ensureEventsConnected, refreshSubagentRoster, clearTerminalReconcileTimer, opts.chatInputRef, snapshotRunEntries]); - const executeBash = useCallback(async (command: string, excludeFromContext: boolean) => { + const executeBash = useCallback(async (command: string, excludeFromContext: boolean, force = false) => { if (agentRunningRef.current || bashRunningRef.current || editInFlightRef.current) return; const inputText = `${excludeFromContext ? "!!" : "!"}${command}`; bashRunningRef.current = true; @@ -2952,7 +3308,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { type: "bash", command, excludeFromContext, - }); + }, { force }); // Same abandonment rule as handleSend: navigating away mid-spawn must // not pull the fresh chat into this session's history. if (hookAliveRef.current) { @@ -2990,17 +3346,34 @@ 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 : []; const followUp = Array.isArray(restoredQueue?.followUp) ? restoredQueue.followUp : []; @@ -3082,6 +3455,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. @@ -3207,6 +3584,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [addNotice, catchUp, connectEvents, isNew, onSessionMoved, opts.chatInputRef, reloadActiveSessionHistory]); + /** + * A settings or fork command hit the ownership gate: another omp process owns + * the file, so the route refused to spawn (409 `session_running_elsewhere`). + * Show the banner the prompt path uses instead of the raw English server text, + * and tell the user nothing changed. Returns true when it handled the error. + */ + const reportForeignCommandError = useCallback((error: unknown): boolean => { + if (!(error instanceof AgentCommandError) || error.code !== "session_running_elsewhere") return false; + applyForeignRun(error.elsewhere ?? { kind: "terminal", source: "transcript", running: false, active: true }); + addNotice({ type: "warning", message: translate("sessionOwnership.commandBlocked") }); + return true; + }, [addNotice, applyForeignRun]); + // editPrompt: omp's `branch` drops the chosen user prompt from the fork and // returns its text — put it in the fork's composer (edit-and-resend). const handleFork = useCallback(async (entryId: string, editPrompt: boolean) => { @@ -3237,12 +3627,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { onSessionForked?.(newSessionId); } } catch (e) { - console.error("Fork failed:", e); + // The fork spawns a resume child, so the ownership gate applies here too. + if (!reportForeignCommandError(e)) console.error("Fork failed:", e); } finally { forkInFlightRef.current = false; setForkingEntryId(null); } - }, [advisorEnabled, onSessionForked]); + }, [advisorEnabled, onSessionForked, reportForeignCommandError]); const handleLeafChange = useCallback(async (leafId: string | null) => { if (bashRunningRef.current || agentRunningRef.current || editInFlightRef.current) return; @@ -3272,6 +3663,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setCurrentModelOverride({ provider, modelId }); await refreshLiveModelState(sid); } catch (e) { + if (reportForeignCommandError(e)) return; // Previously this was console-only, so a cold-start failure (e.g. an // unrestorable saved model, #277) left the composer showing the old // model with no explanation. The override above is only set on success, @@ -3281,7 +3673,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } finally { modelCommandPendingRef.current -= 1; } - }, [isNew, setNewSessionModel, refreshLiveModelState, addNotice]); + }, [isNew, setNewSessionModel, refreshLiveModelState, addNotice, reportForeignCommandError]); const handleFastModeChange = useCallback(async (enabled: boolean) => { // A brand-new session has no runtime yet: the model picker updates local @@ -3295,10 +3687,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setFastModeActive(result?.active); void refreshLiveModelState(sid); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change Fast mode:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice, ensureNewSession, refreshLiveModelState]); + }, [addNotice, ensureNewSession, refreshLiveModelState, reportForeignCommandError]); const handleSlowModeChange = useCallback(async (enabled: boolean) => { // Before omp runs, the toggle comes from the catalog: spawn it like Fast. @@ -3309,10 +3702,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setSlowModeEnabled(result?.enabled ?? enabled); void refreshLiveModelState(sid); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change Slow mode:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice, ensureNewSession, refreshLiveModelState]); + }, [addNotice, ensureNewSession, refreshLiveModelState, reportForeignCommandError]); /** Toggle automatic retry for transient model failures. */ const handleAutoRetryChange = useCallback(async (enabled: boolean) => { @@ -3323,9 +3717,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "set_auto_retry", enabled }); } catch (error) { setAutoRetryEnabled((current) => (current === enabled ? !enabled : current)); + if (reportForeignCommandError(error)) return; addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); const setSkillStartupDiagnostics = useCallback(async (enabled: boolean): Promise => { if (typeof enabled !== "boolean") throw new Error("Skill startup diagnostics enabled must be a boolean"); @@ -3356,10 +3751,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { await sendAgentCommand(sid, { type: "set_interrupt_mode", mode }); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change interrupt mode:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); /** Toggle automatic context compaction on the live session. */ const handleAutoCompactionChange = useCallback(async (enabled: boolean) => { @@ -3369,10 +3765,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { await sendAgentCommand(sid, { type: "set_auto_compaction", enabled }); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change auto-compaction:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); /** Change how queued steering messages are delivered (all at once / one at a time). */ const handleSteeringModeChange = useCallback(async (mode: "all" | "one-at-a-time") => { @@ -3382,10 +3779,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { await sendAgentCommand(sid, { type: "set_steering_mode", mode }); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change steering mode:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); /** Change how queued follow-up messages are delivered. */ const handleFollowUpModeChange = useCallback(async (mode: "all" | "one-at-a-time") => { @@ -3395,10 +3793,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { await sendAgentCommand(sid, { type: "set_follow_up_mode", mode }); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to change follow-up mode:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); /** Cycle to the next available model (⌘/Ctrl+Alt+M). */ const handleCycleModel = useCallback(async () => { @@ -3410,12 +3809,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "cycle_model" }); await refreshLiveModelState(sid); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to cycle model:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } finally { modelCommandPendingRef.current -= 1; } - }, [addNotice, refreshLiveModelState]); + }, [addNotice, refreshLiveModelState, reportForeignCommandError]); /** Cycle to the next thinking level (⌘/Ctrl+Alt+T). */ const handleCycleThinkingLevel = useCallback(async () => { @@ -3427,12 +3827,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "cycle_thinking_level" }); await refreshLiveModelState(sid); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to cycle thinking level:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } finally { modelCommandPendingRef.current -= 1; } - }, [addNotice, refreshLiveModelState]); + }, [addNotice, refreshLiveModelState, reportForeignCommandError]); /** Stop an in-progress automatic retry from the retry banner. */ const handleAbortRetry = useCallback(async () => { @@ -3442,10 +3843,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { await sendAgentCommand(sid, { type: "abort_retry" }); } catch (error) { + if (reportForeignCommandError(error)) return; console.error("Failed to abort retry:", error); addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice]); + }, [addNotice, reportForeignCommandError]); const handleHandoff = useCallback(async () => { const sid = sessionIdRef.current; @@ -3455,9 +3857,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await loadSession(sid, true); void refreshLiveModelState(sid); } catch (error) { + if (reportForeignCommandError(error)) return; addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); } - }, [addNotice, loadSession, refreshLiveModelState]); + }, [addNotice, loadSession, refreshLiveModelState, reportForeignCommandError]); const handleCompact = useCallback(async () => { const sid = sessionIdRef.current; @@ -3472,13 +3875,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await loadSession(sid, true); void refreshLiveModelState(sid); } catch (e) { + if (reportForeignCommandError(e)) return; setCompactError(e instanceof Error ? e.message : String(e)); setCompactResult(null); } finally { isCompactingRef.current = false; setIsCompacting(false); } - }, [isCompacting, loadSession, refreshLiveModelState]); + }, [isCompacting, loadSession, refreshLiveModelState, reportForeignCommandError]); const loadModels = useCallback(async (signal?: AbortSignal) => { setModelsLoading(true); @@ -3717,6 +4121,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 +4155,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 +4178,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; } @@ -3787,11 +4211,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "set_thinking_level", level }); await refreshLiveModelState(sid); } catch (e) { + if (reportForeignCommandError(e)) return; console.error("Failed to set thinking level:", e); } finally { modelCommandPendingRef.current -= 1; } - }, [refreshLiveModelState]); + }, [refreshLiveModelState, reportForeignCommandError]); const handleToolPresetChange = useCallback(async (preset: ToolPreset) => { setToolPresetState(preset); @@ -3875,7 +4300,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 +4525,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, @@ -4116,6 +4547,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // True while a run this UI does not own looks active from the transcript // tail; drives the live-tail rendering and the bounded sync poll. externalRunActive, + // Another omp process owns this session: composer banner + blocked send. + foreignRun, liveToolResults, // Subscriptions handleAgentEventRef, diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 235561f8a..fd8b878ae 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,49 @@ 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. + // Both sinks are rate-limited per minute: a tick that rejects once a second + // would otherwise rotate real crash records out of the 1 MB journal (the size + // cap bounds the file, not the write rate) and bury the console. The first + // ten records of each window carry the full description; the rest are + // reported as one count line with the last one when the window rolls over. + let rejectionWindowStart = Date.now(); + let rejectionsLogged = 0; + let rejectionsSuppressed = 0; + let lastSuppressedRejection = ""; process.on("unhandledRejection", (reason) => { - appendDiag("crash", `unhandledRejection ${describe(reason)}`); - // Same as above: preserve Node's crash-on-unhandled-rejection default. - process.exit(2); + const now = Date.now(); + if (now - rejectionWindowStart >= 60_000) { + if (rejectionsSuppressed > 0) { + const sample = lastSuppressedRejection.slice(0, 300); + appendDiag("rejection", `${rejectionsSuppressed} further unhandled rejection(s) in the last minute were not journaled individually (last: ${sample})`); + console.error(`[omp-web] ${rejectionsSuppressed} further unhandled rejection(s) in the last minute were not logged individually.`); + } + rejectionWindowStart = now; + rejectionsLogged = 0; + rejectionsSuppressed = 0; + lastSuppressedRejection = ""; + } + const text = describe(reason); + if (rejectionsLogged < 10) { + rejectionsLogged += 1; + appendDiag("rejection", `unhandledRejection ${text}`); + console.error(`[omp-web] unhandled rejection (server keeps running): ${text}`); + } else { + rejectionsSuppressed += 1; + lastSuppressedRejection = text; + } }); let lastTick = Date.now(); let lastCpu = process.cpuUsage(); diff --git a/lib/agent-client.ts b/lib/agent-client.ts index 6686b5a6a..685d23b4c 100644 --- a/lib/agent-client.ts +++ b/lib/agent-client.ts @@ -8,22 +8,63 @@ // hooks/useAgentSession.ts. This helper collapses that down to one line. import { formatApiError } from "@/lib/i18n/api-error"; +import type { SessionElsewhere } from "@/lib/types"; // 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. 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; `session_running_elsewhere` means another omp holds the + * session and the user must decide) 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; + /** For `session_running_elsewhere`: who holds the session. */ + readonly elsewhere: SessionElsewhere | null; + + constructor( + message: string, + code: string | undefined, + maybeStarted: boolean, + abortUnconfirmed: boolean, + elsewhere: SessionElsewhere | null = null, + ) { + super(message); + this.name = "AgentCommandError"; + this.code = code; + this.maybeStarted = maybeStarted; + this.abortUnconfirmed = abortUnconfirmed; + this.elsewhere = elsewhere; + } +} + export function setSessionAdvisorSpawn(sessionId: string, enabled: boolean) { if (enabled) advisorSpawnSessions.add(sessionId); else advisorSpawnSessions.delete(sessionId); } +export interface SendAgentCommandOptions { + /** Send into a copy even though another omp process owns the session. Only + * from an explicit user confirmation — never cached, never auto-retried. */ + force?: boolean; +} + export async function sendAgentCommand( sessionId: string, command: Record, + options: SendAgentCommandOptions = {}, ): Promise { - const query = advisorSpawnSessions.has(sessionId) ? "?advisor=1" : ""; + const params = new URLSearchParams(); + if (advisorSpawnSessions.has(sessionId)) params.set("advisor", "1"); + if (options.force) params.set("force", "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 +75,19 @@ export async function sendAgentCommand( data?: T; error?: string; code?: string; + maybeStarted?: boolean; + abortUnconfirmed?: boolean; + elsewhere?: SessionElsewhere | null; }; 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, + body.elsewhere ?? null, ); } return body.data as T; diff --git a/lib/agent-elsewhere-route.test.mjs b/lib/agent-elsewhere-route.test.mjs new file mode 100644 index 000000000..d6367fa79 --- /dev/null +++ b/lib/agent-elsewhere-route.test.mjs @@ -0,0 +1,243 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +// Real POST/GET /api/agent/[id] against a real saved session whose id is listed +// as running by ANOTHER live omp-web instance (its per-pid resume list). The omp +// binary is a launcher stub, so a launch record is the observable proof that a +// child process was created — the gate must prevent exactly that. +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const agentRoute = await jiti.import("../app/api/agent/[id]/route.ts"); +const sessionsRoute = await jiti.import("../app/api/sessions/route.ts"); +const sessionRoute = await jiti.import("../app/api/sessions/[id]/route.ts"); +const mcpRoute = await jiti.import("../app/api/mcp/route.ts"); +const { invalidateSessionListCache } = await jiti.import("../lib/session-reader.ts"); +const { resetElsewhereSessions } = await jiti.import("../lib/session-owner.ts"); +const { resetOmpProcessCache, setOmpProcessScanRunner } = await jiti.import("../lib/omp-processes.ts"); + +// The gate under test is the foreign-instance list; keep the OS process scan +// out of the test (and fast) by injecting an empty table. +setOmpProcessScanRunner(async () => (process.platform === "win32" ? "[]" : "")); + +test("a busy live session answers 503 with its frame clock, never an idle run", async (t) => { + // The route checks the class identity from the `@/` alias instance. + const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + const id = "busy-live-session"; + const previous = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, { + isAlive: () => true, + isRunning: () => true, + // Two hours without a frame — the only report a blocked child produces. + silentForMs: () => 7_200_000, + send: async () => { + throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + }, + }]]); + t.after(() => { + globalThis.__ompSessions = previous; + }); + + const response = await agentRoute.GET( + new Request(`http://localhost/api/agent/${id}`), + { params: Promise.resolve({ id }) }, + ); + const body = await response.json(); + + assert.equal(response.status, 503); + assert.equal(body.code, "session_slow"); + assert.equal(body.silentForMs, 7_200_000, "the busy answer carries how long omp has been silent"); + assert.equal(body.running, true, "the slow answer carries the wrapper's run state"); + assert.equal(body.alive, true, "the child exists"); +}); + +const SAVED_ID = "9f1c0a11-2b3c-4d5e-8f60-7a8b9c0d1e2f"; +const agentDir = mkdtempSync(join(tmpdir(), "omp-web-elsewhere-route-")); +const projectDir = join(agentDir, "sessions", "-project"); +mkdirSync(projectDir, { recursive: true }); +writeFileSync( + join(projectDir, `2026-01-01T00-00-00-000Z_${SAVED_ID}.jsonl`), + `${[ + { type: "session", version: 3, id: SAVED_ID, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "assistant", content: [{ type: "text", text: "hi" }] } }, + ].map((line) => JSON.stringify(line)).join("\n")}\n`, +); + +// A second session nobody owns: its transcript ends with the `session_exit` +// omp flushes when the writer closes the file, so the tail heuristic does not +// invent an owner. It is the control for the ownership gates. +const OWNERLESS_ID = "5c2d8f31-7a49-4b0e-9d18-3f6a2b1c0d77"; +writeFileSync( + join(projectDir, `2026-01-02T00-00-00-000Z_${OWNERLESS_ID}.jsonl`), + `${[ + { type: "session", version: 3, id: OWNERLESS_ID, cwd: tmpdir(), timestamp: "2026-01-02T00:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-02T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: null, timestamp: "2026-01-02T00:00:00.000Z", message: { role: "assistant", content: [{ type: "text", text: "hi" }] } }, + { type: "custom", customType: "session_exit", data: { reason: "dispose", kind: "normal", recordedAt: "2026-01-02T00:00:01.000Z" } }, + ].map((line) => JSON.stringify(line)).join("\n")}\n`, +); + +// A live pid that is not this test process: the "other omp-web instance". +const foreignOwner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 120000)"], { stdio: "ignore" }); +const foreignListPath = join(agentDir, `omp-web-interrupted-sessions-${foreignOwner.pid}.json`); +writeFileSync(foreignListPath, `${JSON.stringify({ sessions: [{ id: SAVED_ID, advisor: false }] }, null, 2)}\n`); + +const launchLog = join(agentDir, "omp-launches.log"); +const fakeOmp = join(agentDir, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp"); +writeFileSync( + fakeOmp, + process.platform === "win32" + ? `@echo off\r\necho launched>> "${launchLog}"\r\nexit /b 1\r\n` + : `#!/bin/sh\necho launched >> '${launchLog}'\nexit 1\n`, + { mode: 0o755 }, +); + +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +const previousBin = process.env.OMP_WEB_OMP_BIN; +process.env.PI_CODING_AGENT_DIR = agentDir; +process.env.OMP_WEB_OMP_BIN = fakeOmp; +after(async () => { + foreignOwner.kill(); + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = previousBin; + resetElsewhereSessions(); + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + invalidateSessionListCache(); + rmSync(agentDir, { recursive: true, force: true }); +}); + +const launches = () => (existsSync(launchLog) ? readFileSync(launchLog, "utf8").split(/\r?\n/).filter(Boolean).length : 0); +const resetLaunches = () => { + rmSync(launchLog, { force: true }); + rmSync(fakeOmp, { force: true }); + writeFileSync( + fakeOmp, + process.platform === "win32" + ? `@echo off\r\necho launched>> "${launchLog}"\r\nexit /b 1\r\n` + : `#!/bin/sh\necho launched >> '${launchLog}'\nexit 1\n`, + { mode: 0o755 }, + ); +}; + +const post = (id, body, query = "") => agentRoute.POST( + new Request(`http://localhost/api/agent/${id}${query}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }), + { params: Promise.resolve({ id }) }, +); + +test("sending to a session another live instance runs is refused with 409 and never spawns", async () => { + resetLaunches(); + const response = await post(SAVED_ID, { type: "prompt", message: "hello again" }); + assert.equal(response.status, 409); + const body = await response.json(); + assert.equal(body.code, "session_running_elsewhere"); + assert.equal(typeof body.error, "string"); + assert.equal(body.elsewhere.kind, "omp-web"); + assert.equal(body.elsewhere.source, "instance-list"); + assert.equal(body.elsewhere.running, true); + assert.equal(body.elsewhere.active, true); + assert.equal(body.elsewhere.pid, undefined, "the owning pid is not disclosed"); + assert.equal(launches(), 0, "no omp child was started"); +}); + +test("read-only commands that would spawn are gated as well", async () => { + resetLaunches(); + const response = await post(SAVED_ID, { type: "get_state" }); + assert.equal(response.status, 409); + assert.equal((await response.json()).code, "session_running_elsewhere"); + assert.equal(launches(), 0); +}); + +test("?force=1 is the explicit override and proceeds to spawn a copy", async () => { + resetLaunches(); + const response = await post(SAVED_ID, { type: "prompt", message: "into the copy" }, "?force=1"); + // The stub omp exits at once, so the spawn fails — the point is that the + // spawn HAPPENED: the gate did not answer 409 for the forced request. + assert.notEqual(response.status, 409); + const body = await response.json(); + assert.notEqual(body.code, "session_running_elsewhere"); + assert.equal(launches(), 1, "the forced request spawned the child"); +}); + +test("GET reports the foreign owner without spawning", async () => { + resetLaunches(); + const response = await agentRoute.GET(new Request(`http://localhost/api/agent/${SAVED_ID}`), { + params: Promise.resolve({ id: SAVED_ID }), + }); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.running, false); + assert.equal(body.elsewhere.kind, "omp-web"); + assert.equal(body.elsewhere.pid, undefined); + assert.equal(launches(), 0); +}); + +test("the session list and the session detail carry the owner in `elsewhereSessions`", async () => { + invalidateSessionListCache(); + const listResponse = await sessionsRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(listResponse.status, 200); + const list = await listResponse.json(); + const entry = (list.elsewhereSessions ?? []).find((item) => item.id === SAVED_ID); + assert.ok(entry, `missing elsewhere entry: ${JSON.stringify(list.elsewhereSessions)}`); + assert.equal(entry.kind, "omp-web"); + assert.equal(entry.source, "instance-list"); + assert.equal(entry.pid, undefined, "no owner pid on the wire"); + assert.equal(entry.cwd, undefined, "no cwd on the wire"); + // Foreign ownership must never be mixed into the local running set. + assert.equal((list.runningSessionIds ?? []).includes(SAVED_ID), false); + + const detail = await sessionRoute.GET(new Request(`http://localhost/api/sessions/${SAVED_ID}?includeState=1`), { + params: Promise.resolve({ id: SAVED_ID }), + }); + assert.equal(detail.status, 200); + const detailBody = await detail.json(); + assert.equal(detailBody.agent.running, false); + assert.equal(detailBody.agent.elsewhere.kind, "omp-web"); +}); + +test("GET /api/mcp does not spawn a second writer for a foreign-owned session", async () => { + resetLaunches(); + invalidateSessionListCache(); + // The live server list of a session detail view reads MCP states through an + // omp child. For a session another process owns that spawn IS the silent + // fork (the child's `dispose` writes its `session_exit` into a copy), so the + // route must answer from the ownership report instead. + const response = await mcpRoute.GET(new Request(`http://localhost/api/mcp?sessionId=${SAVED_ID}`)); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(launches(), 0, "no omp child was started"); + // The client falls back to the configured inventory; the ownership message + // is what explains why the live block is missing (an empty list used to read + // as "no MCP servers configured"). + assert.equal(body.liveServers, undefined, "no live list without a child"); + assert.equal(typeof body.liveError, "string"); + assert.match(body.liveError, /another omp process/); + assert.equal(body.liveElsewhere, undefined); +}); + +test("GET /api/mcp still starts omp for a session nobody owns", async () => { + resetLaunches(); + invalidateSessionListCache(); + // The control: the gate answers only for an owner. A closed transcript of an + // idle session must still get its live MCP list (the stub omp exits at once, + // so the launch record is the observable). + const response = await mcpRoute.GET(new Request(`http://localhost/api/mcp?sessionId=${OWNERLESS_ID}`)); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(launches(), 1, "the session without an owner spawned its child"); + assert.equal(body.liveElsewhere, undefined); +}); diff --git a/lib/agent-skill-diagnostics-route.test.mjs b/lib/agent-skill-diagnostics-route.test.mjs index 76fcb2591..fc1d4a61c 100644 --- a/lib/agent-skill-diagnostics-route.test.mjs +++ b/lib/agent-skill-diagnostics-route.test.mjs @@ -24,6 +24,14 @@ writeFileSync( `${[ { type: "session", version: 3, id: SAVED_ID, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }, { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + // A saved session nobody is writing any more: omp flushes this record on + // dispose. Without it a recently written file counts as a possible foreign + // writer and the spawn gate answers 409 (lib/session-owner.ts, tail signal). + { + type: "custom", + customType: "session_exit", + data: { reason: "dispose", kind: "exit", recordedAt: "2026-01-01T00:01:00.000Z" }, + }, ].map((line) => JSON.stringify(line)).join("\n")}\n`, ); @@ -82,6 +90,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 +161,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/auto-name-elsewhere-route.test.mjs b/lib/auto-name-elsewhere-route.test.mjs new file mode 100644 index 000000000..4a79e86f2 --- /dev/null +++ b/lib/auto-name-elsewhere-route.test.mjs @@ -0,0 +1,155 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +// Real POST /api/sessions/[id]/auto-name against a saved session that ANOTHER +// live omp-web instance lists as running. Generating a title starts an omp +// child (and its dispose writes a copy of a foreign conversation), so the route +// must answer from the file instead: a stored title, or 200 without one — the +// client treats that as a silent no-op. The omp binary is a launcher stub, so a +// launch record is the observable proof that nothing was spawned. +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/route.ts"); +const { setSessionTitle } = await jiti.import("../lib/omp/session-files.ts"); +const { invalidateSessionListCache, invalidateSessionCaches } = await jiti.import("../lib/session-reader.ts"); +const { resetElsewhereSessions } = await jiti.import("../lib/session-owner.ts"); +const { resetOmpProcessCache, setOmpProcessScanRunner } = await jiti.import("../lib/omp-processes.ts"); + +// The gate under test is the foreign-instance list; keep the OS process scan +// out of the test (and fast) by injecting an empty table. +setOmpProcessScanRunner(async () => (process.platform === "win32" ? "[]" : "")); + +const TITLED_ID = "9f1c0a11-2b3c-4d5e-8f60-7a8b9c0d1e2f"; +const UNTITLED_ID = "5c2d8f31-7a49-4b0e-9d18-3f6a2b1c0d77"; +const OWNERLESS_ID = "0b8e6d42-91c7-4f3a-8d55-1e2f3a4b5c6d"; + +const agentDir = mkdtempSync(join(tmpdir(), "omp-web-auto-name-")); +const projectDir = join(agentDir, "sessions", "-project"); +mkdirSync(projectDir, { recursive: true }); + +function writeSession(id, { exit = false } = {}) { + const path = join(projectDir, `2026-01-01T00-00-00-000Z_${id}.jsonl`); + const lines = [ + { type: "session", version: 3, id, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "assistant", content: [{ type: "text", text: "hi" }] } }, + ]; + if (exit) { + // Closed by its writer: the tail heuristic invents no owner. + lines.push({ type: "custom", customType: "session_exit", data: { reason: "dispose", kind: "normal", recordedAt: "2026-01-01T00:00:01.000Z" } }); + } + writeFileSync(path, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`); + return path; +} + +const titledFile = writeSession(TITLED_ID, { exit: true }); +// omp's own title slot (the fixed-width first line) via the same writer the +// route uses, so `scanSessionInfo` reads what the sidebar would show. +setSessionTitle(titledFile, "Stored title", "auto"); +const untitledFile = writeSession(UNTITLED_ID, { exit: true }); +const ownerlessFile = writeSession(OWNERLESS_ID, { exit: true }); + +// A live pid that is not this test process: the "other omp-web instance". +const foreignOwner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 120000)"], { stdio: "ignore" }); +writeFileSync( + join(agentDir, `omp-web-interrupted-sessions-${foreignOwner.pid}.json`), + `${JSON.stringify({ sessions: [{ id: TITLED_ID, advisor: false }, { id: UNTITLED_ID, advisor: false }] }, null, 2)}\n`, +); + +const launchLog = join(agentDir, "omp-launches.log"); +const fakeOmp = join(agentDir, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp"); +function writeFakeOmp() { + writeFileSync( + fakeOmp, + process.platform === "win32" + ? `@echo off\r\necho launched>> "${launchLog}"\r\nexit /b 1\r\n` + : `#!/bin/sh\necho launched >> '${launchLog}'\nexit 1\n`, + { mode: 0o755 }, + ); +} +writeFakeOmp(); + +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +const previousBin = process.env.OMP_WEB_OMP_BIN; +process.env.PI_CODING_AGENT_DIR = agentDir; +process.env.OMP_WEB_OMP_BIN = fakeOmp; +after(async () => { + foreignOwner.kill(); + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = previousBin; + resetElsewhereSessions(); + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + invalidateSessionListCache(); + rmSync(agentDir, { recursive: true, force: true }); +}); + +const launches = () => (existsSync(launchLog) ? readFileSync(launchLog, "utf8").split(/\r?\n/).filter(Boolean).length : 0); +const resetLaunches = () => { + rmSync(launchLog, { force: true }); + rmSync(fakeOmp, { force: true }); + writeFakeOmp(); +}; +/** Session-looking files in the project dir (a fork/copy would add one). */ +const sessionFiles = () => readdirSync(projectDir).filter((name) => name.endsWith(".jsonl")).sort(); + +const autoName = (id) => autoNameRoute.POST( + new Request(`http://localhost/api/sessions/${id}/auto-name`, { method: "POST" }), + { params: Promise.resolve({ id }) }, +); + +test("auto-name answers from the file for a foreign-owned session and spawns nothing", async () => { + resetLaunches(); + const before = sessionFiles(); + const bytesBefore = readFileSync(titledFile, "utf8"); + + const response = await autoName(TITLED_ID); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.title, "Stored title", "the stored title comes back"); + assert.equal(body.generated, false); + assert.equal(body.elsewhere, undefined, "no owner report in the title answer"); + assert.equal(launches(), 0, "no omp child was started"); + assert.deepEqual(sessionFiles(), before, "no copy/fork file was created"); + assert.equal(readFileSync(titledFile, "utf8"), bytesBefore, "the foreign file was not written"); +}); + +test("a foreign-owned session without a title answers 200 without one (silent no-op)", async () => { + resetLaunches(); + const before = sessionFiles(); + const bytesBefore = readFileSync(untitledFile, "utf8"); + + const response = await autoName(UNTITLED_ID); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.title, null, "no title invented for someone else's chat"); + assert.equal(body.generated, false); + assert.equal(body.error, undefined, "no title is not an error"); + assert.equal(launches(), 0); + assert.deepEqual(sessionFiles(), before, "the fallback title was not written to a foreign file"); + assert.equal(readFileSync(untitledFile, "utf8"), bytesBefore, "the foreign file was not written"); +}); + +test("an unowned session still gets a name (the gate answers only for owners)", async () => { + resetLaunches(); + invalidateSessionCaches(ownerlessFile); + invalidateSessionListCache(); + // The stub omp exits at once, so the route falls back to the first user + // message — the launch record is what proves the gate let it through. + const response = await autoName(OWNERLESS_ID); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(launches(), 1, "the unowned session was allowed to spawn"); + assert.equal(body.generated, false); + assert.equal(body.title, "hello"); +}); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index c929c832f..68143419c 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -477,3 +477,45 @@ test("file channel enforces the allow-list and reports content changes", { timeo assert.equal(change.data.type, "change"); assert.equal(change.data.size, 7); }); + +test("running frames carry the elsewhere snapshot in both the initial and the update frame", async (t) => { + const { setOmpProcessScanRunner, resetOmpProcessCache } = await jiti.import("./omp-processes.ts"); + const { refreshElsewhereSessions, resetElsewhereSessions } = await jiti.import("./session-owner.ts"); + const { notifyRunningChange } = await jiti.import("./rpc-manager.ts"); + setOmpProcessScanRunner(async () => (process.platform === "win32" ? "[]" : "")); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omp-web-hub-elsewhere-")); + t.after(() => { + resetElsewhereSessions(); + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + const sessionFile = path.join(dir, "elsewhere.jsonl"); + // Ends mid-turn (a tool call without its result): the transcript signal. + fs.writeFileSync(sessionFile, `${JSON.stringify({ type: "message", id: "u1", parentId: null, message: { role: "user", content: "go" } })}\n${JSON.stringify({ type: "message", id: "a1", parentId: null, message: { role: "assistant", content: [{ type: "toolCall", id: "c1", name: "bash", arguments: {} }] } })}\n`); + + const { connection, reader } = await connect(); + try { + await connection.subscribe("s1", { kind: "running" }); + assert.deepEqual(await readFrame(reader), { event: "mux", data: { type: "open", sub: "s1" } }); + const initial = await readFrame(reader); + assert.equal(initial.data.type, "running"); + assert.ok(Array.isArray(initial.data.elsewhereSessions), "the initial frame carries the array"); + + await refreshElsewhereSessions([{ id: "hub-elsewhere", sessionFile, mtimeMs: Date.now() }]); + notifyRunningChange({ refreshSessionList: true }); + + let update = await readFrame(reader); + for (let i = 0; i < 4 && update.data.type !== "running"; i += 1) update = await readFrame(reader); + assert.equal(update.data.type, "running"); + const entry = update.data.elsewhereSessions.find((item) => item.id === "hub-elsewhere"); + assert.ok(entry, `missing elsewhere entry: ${JSON.stringify(update.data.elsewhereSessions)}`); + assert.equal(entry.source, "transcript"); + assert.equal(entry.running, true); + assert.equal(entry.active, true); + // Foreign ownership stays out of the local running ids. + assert.equal(update.data.runningSessionIds.includes("hub-elsewhere"), false); + } finally { + await reader.cancel(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 32be7067d..d4882950a 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -3,7 +3,8 @@ import fs from "fs"; import { authorizeFileAccess } from "./file-authorization"; import { filePathApiSegments } from "./file-paths"; import { attachNotificationClient } from "./notification-hub"; -import { getExitedRpcSessions, getRpcSession, getRunningRpcSessions, subscribeHostToolCalls, subscribeRunningSessions } from "./rpc-manager"; +import { getExitedRpcSessions, getOwnChildPids, getRpcSession, getRunningRpcSessions, isLocallyOwnedSession, isOwnCrashedSession, notifyRunningChange, subscribeHostToolCalls, subscribeRunningSessions } from "./rpc-manager"; +import { getElsewhereSessions, refreshElsewhereForSessionIds } from "./session-owner"; import { subscribeSessionFileChanges } from "./session-watcher"; import { MUX_CONTROL_EVENT, @@ -244,17 +245,29 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { handle.open(); // Subscribe BEFORE taking the initial snapshot so no state change can slip // through the gap between snapshot and subscription. - const unsubscribeRunning = subscribeRunningSessions(({ ids, runningSessions, exitedSessions, refreshSessionList }) => { + const unsubscribeRunning = subscribeRunningSessions(({ ids, runningSessions, exitedSessions, elsewhereSessions, refreshSessionList }) => { handle.send({ type: "running", runningSessionIds: ids, runningSessions, exitedSessions, + elsewhereSessions, ...(refreshSessionList ? { refreshSessionList: true } : {}), }); }); const unsubscribeFiles = subscribeSessionFileChanges((sessionIds) => { handle.send({ type: "sessions-changed", sessionIds, refreshSessionList: true }); + // A write is the moment ownership can change (a foreign omp just started on + // the file, or wrote its `session_exit`): re-check, then let the running + // broadcast carry the new `elsewhereSessions` to every tab. + void refreshElsewhereForSessionIds(sessionIds, { + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids(), + }).then(() => notifyRunningChange()).catch(() => { + // Same as the self-tick: this chain is fire-and-forget, so a rejection + // would be unhandled and end the server. The next file write retries. + }); }); handle.setDetach(() => { unsubscribeRunning(); @@ -266,6 +279,7 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { runningSessionIds: initialRunning.map((session) => session.id), runningSessions: initialRunning, exitedSessions: getExitedRpcSessions(), + elsewhereSessions: getElsewhereSessions(), }); return SUBSCRIBED; } 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..b0ff60819 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", @@ -1748,5 +1753,16 @@ "modelsConfig.accountApiKey": "API key", "modelsConfig.disconnectAccount": "Disconnect {label}", "modelsConfig.disconnectAccountTitle": "Disconnect account?", - "modelsConfig.disconnectAccountBody": "omp will delete the stored credential for {label}. Other accounts for this provider stay connected." + "modelsConfig.disconnectAccountBody": "omp will delete the stored credential for {label}. Other accounts for this provider stay connected.", + "sessionOwnership.openElsewhere": "Another omp process owns this chat ({source}). Open it from a terminal or the other omp-web window to continue there.", + "sessionOwnership.bannerTitle": "This chat is running elsewhere.", + "sessionOwnership.bannerBody": "Another omp process holds this conversation (another omp-web window or a terminal). You are following it read-only; sending would continue in a separate copy.", + "sessionOwnership.sendBlocked": "This chat is being run by another omp process — send anyway to continue in a copy.", + "sessionOwnership.sendAnyway": "Send anyway (copy)", + "sessionOwnership.sendAnywayConfirm": "omp will move this conversation into a new copy when it writes, so the other process keeps the original untouched. Your message and the following replies live in the copy.", + "sessionOwnership.commandBlocked": "This chat is being run by another omp process — nothing was changed.", + "sessionOwnership.copyNoticeTitle": "Continued in a copy", + "sessionOwnership.copyNotice": "Another omp process owned this chat, so your message continued in a copy.", + "sessionOwnership.openOriginal": "Open original", + "sessionOwnership.openCopy": "Open copy" } diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..4ef44c728 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": "不明", @@ -1707,5 +1712,16 @@ "modelsConfig.accountApiKey": "APIキー", "modelsConfig.disconnectAccount": "{label} を切断", "modelsConfig.disconnectAccountTitle": "アカウントを切断しますか?", - "modelsConfig.disconnectAccountBody": "omp は {label} の保存済み資格情報を削除します。このプロバイダーの他のアカウントは接続されたままです。" + "modelsConfig.disconnectAccountBody": "omp は {label} の保存済み資格情報を削除します。このプロバイダーの他のアカウントは接続されたままです。", + "sessionOwnership.openElsewhere": "別の omp プロセスがこのチャットを所有しています ({source})。続けるにはターミナルまたは別の omp-web ウィンドウで開いてください。", + "sessionOwnership.bannerTitle": "このチャットは他の場所で実行されています。", + "sessionOwnership.bannerBody": "別の omp プロセス (別の omp-web ウィンドウまたはターミナル) がこの会話を所有しています。ここでは読み取り専用で追従しています。送信すると別のコピーで続行されます。", + "sessionOwnership.sendBlocked": "このチャットは別の omp プロセスが実行中です。コピーで続行するには「それでも送信」を選んでください。", + "sessionOwnership.sendAnyway": "それでも送信 (コピー)", + "sessionOwnership.sendAnywayConfirm": "書き込み時に omp はこの会話を新しいコピーへ移動するため、他のプロセスは元のファイルをそのまま保持します。あなたのメッセージと以降の返信はコピーに残ります。", + "sessionOwnership.commandBlocked": "このチャットは別の omp プロセスが実行中です。変更は行われませんでした。", + "sessionOwnership.copyNoticeTitle": "コピーで続行しました", + "sessionOwnership.copyNotice": "別の omp プロセスがこのチャットを所有していたため、メッセージはコピーで続行されました。", + "sessionOwnership.openOriginal": "元のチャットを開く", + "sessionOwnership.openCopy": "コピーを開く" } diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..ccc1cfd85 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": "未知", @@ -1707,5 +1712,16 @@ "modelsConfig.accountApiKey": "API 密钥", "modelsConfig.disconnectAccount": "断开 {label}", "modelsConfig.disconnectAccountTitle": "断开账户?", - "modelsConfig.disconnectAccountBody": "omp 将删除 {label} 的已存储凭据。此提供商的其他账户保持连接。" + "modelsConfig.disconnectAccountBody": "omp 将删除 {label} 的已存储凭据。此提供商的其他账户保持连接。", + "sessionOwnership.openElsewhere": "另一个 omp 进程拥有此聊天 ({source})。请在终端或另一个 omp-web 窗口中继续。", + "sessionOwnership.bannerTitle": "此聊天正在别处运行。", + "sessionOwnership.bannerBody": "另一个 omp 进程 (另一个 omp-web 窗口或终端) 拥有此对话。你正在只读跟随;发送将在单独的副本中继续。", + "sessionOwnership.sendBlocked": "另一个 omp 进程正在运行此聊天 — 选择“仍然发送”以在副本中继续。", + "sessionOwnership.sendAnyway": "仍然发送 (副本)", + "sessionOwnership.sendAnywayConfirm": "写入时 omp 会将此对话移动到新的副本,另一个进程保留原始文件。你的消息和后续回复位于副本中。", + "sessionOwnership.commandBlocked": "另一个 omp 进程正在运行此聊天 — 未做任何更改。", + "sessionOwnership.copyNoticeTitle": "已在副本中继续", + "sessionOwnership.copyNotice": "另一个 omp 进程拥有此聊天,因此你的消息在副本中继续。", + "sessionOwnership.openOriginal": "打开原始聊天", + "sessionOwnership.openCopy": "打开副本" } diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index 39f566e7e..d6c57259e 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,40 @@ 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 are rate-limited in both sinks, with a count line for the suppressed ones", () => { + // A tick that rejects once a second must neither bury the console nor rotate + // real crash records out of the 1 MB journal (the size cap bounds the file, + // not the write rate): ten records carry the full description per minute, the + // rest arrive as one count line with the last reason when the window rolls. + const body = ` + for (let i = 0; i < 14; i += 1) Promise.reject(new Error("tick " + i)); + await new Promise((resolve) => setTimeout(resolve, 50)); + const realNow = Date.now; + Date.now = () => realNow() + 61000; + Promise.reject(new Error("tick late")); + `; + const { status, journal, stderr } = runAfterRegister(body); + assert.equal(status, 0, stderr); + assert.equal(journal.match(/\[rejection\] unhandledRejection/g)?.length, 11, "ten records plus the first of the next window"); + assert.match(journal, /\[rejection\] 4 further unhandled rejection\(s\) in the last minute were not journaled individually/, "the suppressed ones are counted, not lost"); + assert.equal(stderr.match(/unhandled rejection \(server keeps running\)/g)?.length, 11, "the console copy uses the same cap"); + assert.match(stderr, /4 further unhandled rejection\(s\) in the last minute were not logged individually/, "the console says the same"); +}); diff --git a/lib/omp-processes.test.mjs b/lib/omp-processes.test.mjs new file mode 100644 index 000000000..68df3cf90 --- /dev/null +++ b/lib/omp-processes.test.mjs @@ -0,0 +1,239 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { existsSync } from "node:fs"; +import { isAbsolute } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const { + FOREIGN_SCAN_TTL_MS, + foreignScanEnabled, + listOmpProcesses, + matchSessionOwner, + parsePosixProcessList, + parseWindowsProcessList, + resetOmpProcessCache, + resumeArguments, + sameUserProcesses, + sessionIdsNamedByProcesses, + setOmpProcessScanRunner, +} = await jiti.import("./omp-processes.ts"); + +const SESSION_ID = "8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e63"; +const SESSION_FILE = `C:\\Users\\user\\.omp\\agent\\sessions\\-Desktop-project\\2026-10-21T12-08-21-139Z_${SESSION_ID}.jsonl`; + +test("windows process list parses an array, a single object and garbage", () => { + const array = parseWindowsProcessList(JSON.stringify([ + { ProcessId: 10, CommandLine: "omp.exe --mode rpc-ui" }, + { ProcessId: 11, CommandLine: null }, + ])); + assert.deepEqual(array, [ + { pid: 10, commandLine: "omp.exe --mode rpc-ui" }, + { pid: 11, commandLine: "" }, + ]); + // ConvertTo-Json emits a bare object for exactly one match. + assert.deepEqual(parseWindowsProcessList(JSON.stringify({ ProcessId: 7, CommandLine: "omp.exe" })), [ + { pid: 7, commandLine: "omp.exe" }, + ]); + assert.deepEqual(parseWindowsProcessList("not json"), []); + assert.deepEqual(parseWindowsProcessList(""), []); + assert.deepEqual(parseWindowsProcessList('[{"ProcessId":0,"CommandLine":"x"}]'), []); +}); + +test("posix process list parses pid, uid and the full command line", () => { + assert.deepEqual(parsePosixProcessList(" 123 1000 omp --resume /home/x/a.jsonl\n 456 501 /usr/bin/omp\nbroken\n 7 user omp\n"), [ + { pid: 123, uid: 1000, commandLine: "omp --resume /home/x/a.jsonl" }, + { pid: 456, uid: 501, commandLine: "/usr/bin/omp" }, + ]); +}); + +test("only this user's processes are trusted as owners", () => { + // `ps -e` lists every user's processes; a foreign command line that merely + // prints `--resume ` must not make the session look taken. + const scanned = parsePosixProcessList([ + " 900 1000 omp --resume sess-a", + " 901 1001 omp --resume sess-b", + " 902 1001 python3 -c pass --resume sess-a", + ].join("\n")); + assert.deepEqual(sameUserProcesses(scanned, 1000).map((process) => process.pid), [900]); + assert.equal(matchSessionOwner(sameUserProcesses(scanned, 1000), { sessionId: "sess-b" }), undefined); + assert.deepEqual(sameUserProcesses(scanned, 1001).map((process) => process.pid), [901, 902]); + // An OS without uids (Windows) cannot filter, so every scanned process stays. + assert.deepEqual(sameUserProcesses(scanned, null).map((process) => process.pid), [900, 901, 902]); +}); + +test("resume arguments cover quoted, unquoted-with-spaces, = and id forms", () => { + assert.deepEqual(resumeArguments('omp --mode rpc-ui --resume "C:\\a b\\file.jsonl"'), ["C:\\a b\\file.jsonl"]); + assert.deepEqual(resumeArguments("omp --resume=C:\\x\\y.jsonl"), ["C:\\x\\y.jsonl"]); + const spaced = resumeArguments("omp --resume C:\\Project Alpha\\file.jsonl --foo"); + assert.ok(spaced.includes("C:\\Project Alpha\\file.jsonl"), `spaced path missing: ${JSON.stringify(spaced)}`); + // `ps` loses the quoting, so the space-joined tokens are offered as well — + // but only up to a flag, never the whole rest of the command line. + assert.ok(spaced.includes("C:\\Project"), "the first token is offered"); + assert.ok(!spaced.includes("C:\\Project Alpha\\file.jsonl --foo"), "joining stops at the next flag"); + // A different flag that merely starts with --resume is not a resume argument. + assert.deepEqual(resumeArguments("omp --resumeX nope"), []); + assert.deepEqual(resumeArguments("omp --mode rpc-ui"), []); +}); + +test("a hostile 128 KB command line stays bounded and matches in under 50 ms", () => { + const hostile = `omp --resume ${" ".repeat(64 * 1024)}${"a ".repeat(80_000)}`; + assert.ok(hostile.length > 128 * 1024); + const started = performance.now(); + const values = resumeArguments(hostile); + matchSessionOwner([{ pid: 1, commandLine: hostile }], { sessionId: SESSION_ID, sessionFile: SESSION_FILE }); + const elapsed = performance.now() - started; + assert.ok(values.length <= 8 * 8, `candidate count is capped, got ${values.length}`); + assert.ok(elapsed < 50, `the parse took ${elapsed} ms`); +}); + +test("session matching accepts path, basename, id, separators and rejects other pids", () => { + const owners = [ + { pid: 900, commandLine: `omp --mode rpc-ui --cwd C:\\x --resume "${SESSION_FILE}"` }, + ]; + assert.deepEqual(matchSessionOwner(owners, { sessionId: SESSION_ID, sessionFile: SESSION_FILE }), owners[0]); + // Forward slashes in the process list (a POSIX/WSL-style command line). + assert.deepEqual( + matchSessionOwner([{ pid: 901, commandLine: `omp --resume ${SESSION_FILE.replace(/\\/g, "/")}` }], { sessionId: SESSION_ID, sessionFile: SESSION_FILE }), + { pid: 901, commandLine: `omp --resume ${SESSION_FILE.replace(/\\/g, "/")}` }, + ); + // Same basename, different root (network drive, another home). + assert.deepEqual( + matchSessionOwner([{ pid: 902, commandLine: `omp --resume /mnt/c/other/2026-10-21T12-08-21-139Z_${SESSION_ID}.jsonl` }], { sessionId: SESSION_ID, sessionFile: SESSION_FILE }), + { pid: 902, commandLine: `omp --resume /mnt/c/other/2026-10-21T12-08-21-139Z_${SESSION_ID}.jsonl` }, + ); + // Id only. + assert.deepEqual( + matchSessionOwner([{ pid: 903, commandLine: `omp --resume ${SESSION_ID}` }], { sessionId: SESSION_ID, sessionFile: SESSION_FILE }), + { pid: 903, commandLine: `omp --resume ${SESSION_ID}` }, + ); + // Our own child names the old file on its command line: excluded by pid. + assert.equal(matchSessionOwner(owners, { sessionId: SESSION_ID, sessionFile: SESSION_FILE, excludePids: [900] }), undefined); + // A process without --resume never owns a session. + assert.equal(matchSessionOwner([{ pid: 904, commandLine: "omp __omp_worker_daemon_broker" }], { sessionId: SESSION_ID, sessionFile: SESSION_FILE }), undefined); + // A different session. + assert.equal(matchSessionOwner(owners, { sessionId: "other-id", sessionFile: "C:\\x\\2026-01-01_other-id.jsonl" }), undefined); +}); + +test("the scan names the sessions it owns, so no candidate list cap hides one", () => { + const candidates = [ + { id: SESSION_ID, sessionFile: SESSION_FILE }, + { id: "8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e64" }, + { id: "8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e65", sessionFile: "C:\\sessions\\2026-10-20_8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e65.jsonl" }, + ]; + const processes = [ + // The original file path, in the other separator form. + { pid: 910, commandLine: `omp --resume ${SESSION_FILE.replace(/\\/g, "/")}` }, + // An id only (no file in the list for it). + { pid: 911, commandLine: "omp --resume 8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e64" }, + // A basename that matches the third candidate. + { pid: 912, commandLine: "omp --resume /mnt/elsewhere/2026-10-20_8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e65.jsonl" }, + // A session the list does not know: nothing to report. + { pid: 913, commandLine: "omp --resume /mnt/elsewhere/2026-01-01_00000000-0000-0000-0000-000000000000.jsonl" }, + // No --resume, never an owner. + { pid: 914, commandLine: "omp __omp_worker_daemon_broker" }, + ]; + for (const process of processes) process.resumeTargets = resumeArguments(process.commandLine); + const ids = [...sessionIdsNamedByProcesses(processes, candidates)].sort(); + assert.deepEqual(ids, [`8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e64`, `8f3c1d2a-4b5c-4d6e-8f70-1a2b3c4d5e65`, SESSION_ID].sort()); +}); + +test("posix scans run ps from an absolute system path, never from PATH", async () => { + const seen = []; + setOmpProcessScanRunner(async (file, args) => { + seen.push({ file, args }); + return "1 1000 omp --resume x\n"; + }); + try { + const scan = await listOmpProcesses({ platform: process.platform, uid: 1000 }); + if (process.platform === "win32") return; + if (!existsSync("/bin/ps") && !existsSync("/usr/bin/ps")) { + // No absolute ps: "unknown" (the snapshot keeps a known owner), and no + // PATH lookup ever happened. + assert.deepEqual(scan, { processes: [], ok: false, enabled: true }); + assert.equal(seen.length, 0); + return; + } + assert.equal(scan.ok, true); + assert.ok(isAbsolute(seen[0].file), `ps must be an absolute system path, got ${seen[0].file}`); + assert.ok(seen[0].args.includes("pid=,uid=,args="), "the scan asks ps for the uid column"); + } finally { + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + } +}); + +test("the scan is cached for FOREIGN_SCAN_TTL_MS and can be disabled", async () => { + let calls = 0; + let now = 1_000_000; + setOmpProcessScanRunner(async () => { + calls += 1; + return JSON.stringify([{ ProcessId: 42, CommandLine: "omp.exe --mode rpc-ui" }]); + }); + try { + const first = await listOmpProcesses({ platform: "win32", now: () => now }); + assert.equal(first.processes.length, 1); + now += FOREIGN_SCAN_TTL_MS - 1; + await listOmpProcesses({ platform: "win32", now: () => now }); + assert.equal(calls, 1, "within the TTL the cached scan is reused"); + now += 2; + await listOmpProcesses({ platform: "win32", now: () => now }); + assert.equal(calls, 2, "after the TTL the process table is scanned again"); + } finally { + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + } + assert.equal(foreignScanEnabled({ OMP_WEB_FOREIGN_SCAN: "0" }), false); + assert.equal(foreignScanEnabled({}), true); +}); + +test("concurrent callers share one scan and the resume arguments are computed once", async () => { + let calls = 0; + let release; + const gate = new Promise((resolve) => { release = resolve; }); + setOmpProcessScanRunner(async () => { + calls += 1; + await gate; + return JSON.stringify([{ ProcessId: 77, CommandLine: 'omp.exe --resume "C:\\a b\\file.jsonl"' }]); + }); + try { + const first = listOmpProcesses({ platform: "win32" }); + const second = listOmpProcesses({ platform: "win32" }); + release(); + const [a, b] = await Promise.all([first, second]); + assert.equal(calls, 1, "one in-flight scan serves every caller"); + assert.equal(a.processes.length, 1); + assert.equal(b.processes.length, 1); + assert.deepEqual(a.processes[0].resumeTargets, ["C:\\a b\\file.jsonl"]); + } finally { + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + } +}); + +test("a failing scan is reported as unknown, never as 'no processes'", async () => { + setOmpProcessScanRunner(async () => { + throw new Error("powershell missing"); + }); + try { + const failed = await listOmpProcesses({ platform: "win32" }); + assert.deepEqual(failed, { processes: [], ok: false, enabled: true }); + } finally { + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + } + const previous = process.env.OMP_WEB_FOREIGN_SCAN; + process.env.OMP_WEB_FOREIGN_SCAN = "0"; + try { + resetOmpProcessCache(); + // Disabled is not a failure: the other ownership signals stay in charge. + assert.deepEqual(await listOmpProcesses(), { processes: [], ok: true, enabled: false }); + } finally { + if (previous === undefined) delete process.env.OMP_WEB_FOREIGN_SCAN; + else process.env.OMP_WEB_FOREIGN_SCAN = previous; + resetOmpProcessCache(); + } +}); diff --git a/lib/omp-processes.ts b/lib/omp-processes.ts new file mode 100644 index 000000000..9de3c935d --- /dev/null +++ b/lib/omp-processes.ts @@ -0,0 +1,411 @@ +import { execFile } from "child_process"; +import { existsSync } from "fs"; +import { getWindowsExecutionEnv, resolvePowerShellBin } from "./windows-service"; +import { comparableProjectPath } from "./comparable-path"; + +/** + * Which live omp processes exist, and which session each one was opened on. + * + * omp ≥ 18.5 keeps a process-owned OS lease per session (a named mutex on + * Windows, an abstract socket on Linux) — deliberately not a file, so omp-web + * cannot read it. The command line is the portable, version-independent + * evidence instead: both omp-web (`buildSessionSpawnArgs`) and the terminal + * (`omp --resume `) name the session they were started on, and a live + * process with that argument holds the lease. + * + * Scanning spawns a process (PowerShell cold start on Windows is expensive), so + * results are cached for `FOREIGN_SCAN_TTL_MS`, concurrent callers share one + * in-flight scan, and a failure is reported as "unknown" (`ok: false`) rather + * than "no processes": a broken scan must never block a send, and must never + * erase an owner that was already known. `OMP_WEB_FOREIGN_SCAN=0` turns the + * process scan off; the instance lists and the transcript signal keep working. + * + * Only processes of this server's own OS user are trusted. A command line is + * unauthenticated evidence — any local process could print `--resume ` — + * so a foreign user's process would be a free "this session runs elsewhere" + * (409 on every send) for as long as it lives. POSIX scans ask `ps` for the + * uid and drop every other user's rows. Windows narrows the query to + * `omp`-named processes instead: reading another user's process owner needs + * PROCESS_QUERY_INFORMATION, which an unelevated server does not have. + */ + +export interface OmpProcessInfo { + pid: number; + commandLine: string; + /** Owning uid where the OS reports one (POSIX); undefined on Windows. */ + uid?: number; + /** `--resume` arguments, computed once per scan (see `listOmpProcesses`). */ + resumeTargets?: string[]; +} + +/** How long one process scan is reused. Cheap enough to hide in a request, + * short enough that a stale process list cannot block for long. */ +export const FOREIGN_SCAN_TTL_MS = 10_000; +/** Hard bound on one scan; a slow PowerShell must not stall a send. */ +const FOREIGN_SCAN_TIMEOUT_MS = 1_500; + +/** One command line can be ~2 MB (Linux ARG_MAX). Nothing that identifies a + * session lives past this prefix, and parsing must stay bounded. */ +const MAX_COMMAND_LINE_CHARS = 8 * 1024; +/** Work caps per command line: a process has one `--resume`, and a session + * path with spaces has a handful of tokens — never thousands of prefixes. */ +const MAX_RESUME_OCCURRENCES = 8; +const MAX_BARE_JOIN_TOKENS = 8; + +export type ProcessScanRunner = (file: string, args: string[]) => Promise; + +export interface OmpProcessScanOptions { + /** Injectable process boundary (tests, hosts without PowerShell). */ + run?: ProcessScanRunner; + platform?: NodeJS.Platform; + now?: () => number; + /** + * Effective uid of this server process; a POSIX process of another user is + * never trusted as a session owner. Defaults to `process.getuid()`; `null` + * (Windows, or an OS without uids) keeps every scanned process. + */ + uid?: number | null; +} + +export interface OmpProcessScan { + processes: OmpProcessInfo[]; + /** False when the scan failed or timed out: "unknown", not "none". */ + ok: boolean; + /** False when `OMP_WEB_FOREIGN_SCAN=0` switched the scan off. */ + enabled: boolean; +} + +export function foreignScanEnabled(env: NodeJS.ProcessEnv = process.env): boolean { + return env.OMP_WEB_FOREIGN_SCAN !== "0"; +} + +const defaultRunner: ProcessScanRunner = (file, args) => { + const { promise, resolve, reject } = Promise.withResolvers(); + execFile( + file, + args, + { timeout: FOREIGN_SCAN_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024, env: getWindowsExecutionEnv() }, + (error, stdout) => { + // A timeout leaves partial stdout unusable: report failure. + if (error) reject(error); + else resolve(stdout); + }, + ); + return promise; +}; + +/** The scan child must run the system `ps` from a fixed absolute path, never a + * project-local binary: a repository could ship one named `ps`, and it would + * run with our env. No known absolute path means no scan at all — reported as + * `ok: false` ("unknown") instead of falling back to PATH. */ +function resolvePosixPsBin(): string | null { + for (const candidate of ["/bin/ps", "/usr/bin/ps"]) { + if (existsSync(candidate)) return candidate; + } + return null; +} + +function capCommandLine(commandLine: string): string { + return commandLine.length > MAX_COMMAND_LINE_CHARS ? commandLine.slice(0, MAX_COMMAND_LINE_CHARS) : commandLine; +} + +/** `Get-CimInstance ... | ConvertTo-Json` — one JSON object or an array. */ +export function parseWindowsProcessList(raw: string): OmpProcessInfo[] { + const text = raw.trim(); + if (!text) return []; + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return []; + } + const rows = Array.isArray(parsed) ? parsed : [parsed]; + const processes: OmpProcessInfo[] = []; + for (const row of rows) { + if (!row || typeof row !== "object") continue; + const record = row as { ProcessId?: unknown; CommandLine?: unknown }; + const pid = typeof record.ProcessId === "number" ? record.ProcessId : Number(record.ProcessId); + const commandLine = typeof record.CommandLine === "string" ? capCommandLine(record.CommandLine) : ""; + if (!Number.isInteger(pid) || pid <= 0) continue; + processes.push({ pid, commandLine }); + } + return processes; +} + +/** `ps -eo pid=,uid=,args=` — one `pid uid command line` per line. */ +export function parsePosixProcessList(raw: string): OmpProcessInfo[] { + const processes: OmpProcessInfo[] = []; + for (const line of raw.split(/\r?\n/)) { + const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + if (!match) continue; + const pid = Number(match[1]); + const uid = Number(match[2]); + if (!Number.isInteger(pid) || pid <= 0 || !Number.isSafeInteger(uid)) continue; + processes.push({ pid, uid, commandLine: capCommandLine(match[3].trim()) }); + } + return processes; +} + +interface OmpProcessScanState { + cache: { at: number; platform: NodeJS.Platform; runner: ProcessScanRunner; uid: number | null; processes: OmpProcessInfo[] } | null; + /** One scan at a time, process-wide. */ + inFlight: Promise | null; + injectedRunner: ProcessScanRunner | null; +} + +declare global { + var __ompProcessScanState: OmpProcessScanState | undefined; +} + +/** + * Next compiles every route as its own server bundle, so this module is + * evaluated once per bundle in one process. The cache, the single-flight + * promise and the test seam must therefore live on `globalThis` — a + * module-local copy would let a burst of requests across routes spawn one + * PowerShell each, which is exactly what the single-flight promise exists to + * prevent. + */ +function scanState(): OmpProcessScanState { + const state = globalThis.__ompProcessScanState ??= { cache: null, inFlight: null, injectedRunner: null }; + // A state object created by an older module version lacks fields added later. + state.cache ??= null; + state.inFlight ??= null; + state.injectedRunner ??= null; + return state; +} + +/** Drop the cached scan (tests: the next call must observe the OS again). */ +export function resetOmpProcessCache(): void { + scanState().cache = null; +} + +export function setOmpProcessScanRunner(runner: ProcessScanRunner | null): void { + const state = scanState(); + state.injectedRunner = runner; + state.cache = null; +} + +/** + * Drop processes of other OS users: `ps -e` lists everyone, and a command line + * of another user is no evidence that they hold this session (any local + * process could print `--resume ` and block sending). A `null` uid means + * the OS does not report one (Windows) and keeps every process. + */ +export function sameUserProcesses(processes: OmpProcessInfo[], uid: number | null): OmpProcessInfo[] { + return uid === null ? processes : processes.filter((process) => process.uid === uid); +} + +async function runScan(platform: NodeJS.Platform, run: ProcessScanRunner, uid: number | null): Promise { + let processes: OmpProcessInfo[]; + if (platform === "win32") { + // Ownership could be narrowed to this user with a `GetOwner` call per + // process, but that needs PROCESS_QUERY_INFORMATION, which an unelevated + // server lacks for another user's process — the query would cost a CIM + // round trip per process and still answer "unknown". The name filter below + // stays the cheap narrowing: an arbitrary foreign process (a script named + // `sleep`, say) cannot name a session this way. + const command = + "Get-CimInstance Win32_Process -Filter \"Name='omp.exe' OR Name='omp'\" -ErrorAction SilentlyContinue | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"; + processes = parseWindowsProcessList(await run(resolvePowerShellBin(), ["-NoProfile", "-NonInteractive", "-Command", command])); + } else { + const psBin = resolvePosixPsBin(); + // No absolute `ps`: report "unknown" (the caller keeps a known owner) + // rather than resolving some binary from PATH. + if (!psBin) throw new Error("no absolute ps binary"); + // Unlike the Windows branch this does not filter by executable name: `ps` + // prints the command line as one string with the quoting already lost, so + // the image name cannot be recovered reliably (a wrapper `sh -c "omp + // --resume …"` or a path with spaces would fail a name test that its omp + // child passes). A same-user process whose arguments merely look like + // `--resume ` (an editor, a shell job, `grep`) can therefore be + // reported as the owner. Accepting the extra candidate is the safe side of + // the trade-off: a false owner blocks a send with a retryable 409 + // `session_running_elsewhere` (the chat's "Send anyway (copy)" sets + // `force=1`), while a missed owner would let two writers corrupt the same + // session file. + processes = sameUserProcesses(parsePosixProcessList(await run(psBin, ["-eo", "pid=,uid=,args="])), uid); + } + // Parse the resume arguments once per process: the snapshot matches one scan + // against many candidates, and the scan itself selects its candidates. + for (const process of processes) process.resumeTargets = resumeArguments(process.commandLine); + return processes; +} + +export async function listOmpProcesses(options: OmpProcessScanOptions = {}): Promise { + const platform = options.platform ?? process.platform; + const uid = options.uid === undefined + ? (typeof process.getuid === "function" ? process.getuid() : null) + : options.uid; + const now = options.now?.() ?? Date.now(); + if (!foreignScanEnabled()) return { processes: [], ok: true, enabled: false }; + const state = scanState(); + const run = options.run ?? state.injectedRunner ?? defaultRunner; + // The runner is part of the cache key: a scan produced by another boundary + // (a swapped test seam) must never answer for this one. The uid is too: the + // filter runs inside the scan. + if (state.cache && state.cache.runner === run && state.cache.platform === platform && state.cache.uid === uid && now - state.cache.at < FOREIGN_SCAN_TTL_MS) { + return { processes: state.cache.processes, ok: true, enabled: true }; + } + const scan = async (): Promise => { + try { + const processes = await runScan(platform, run, uid); + state.cache = { at: now, platform, runner: run, uid, processes }; + return { processes, ok: true, enabled: true }; + } catch { + // No process list is a soft "unknown", never a reason to block — and the + // failure is not cached, so the next caller retries instead of inheriting + // an answer that may clear a live owner. + return { processes: [], ok: false, enabled: true }; + } + }; + // A per-call runner is a one-off boundary; it never joins the shared scan. + if (options.run) return scan(); + if (state.inFlight) return state.inFlight; + const started = scan().finally(() => { + state.inFlight = null; + }); + state.inFlight = started; + return started; +} + +function basenameAny(value: string): string { + const normalized = value.replace(/\\/g, "/"); + const index = normalized.lastIndexOf("/"); + return index >= 0 ? normalized.slice(index + 1) : value; +} + +/** + * Values a `--resume` argument may carry: the exact token, or — on POSIX, + * where `ps` loses the quoting — the space-joined tokens that follow it. + * Work stays bounded (`MAX_BARE_JOIN_TOKENS` joins per occurrence), so a + * hostile command line cannot turn this into a quadratic parse. + */ +export function resumeArguments(commandLine: string): string[] { + const text = capCommandLine(commandLine); + const values: string[] = []; + const marker = "--resume"; + let searchFrom = 0; + let occurrences = 0; + while (occurrences < MAX_RESUME_OCCURRENCES) { + const index = text.indexOf(marker, searchFrom); + if (index < 0) break; + searchFrom = index + marker.length; + // `--resume` must start an argument, not sit inside another token. + if (index > 0 && !/\s/.test(text[index - 1])) continue; + occurrences += 1; + let cursor = index + marker.length; + if (text[cursor] === "=") cursor += 1; + else if (cursor < text.length && !/\s/.test(text[cursor])) continue; // `--resumeX` + else while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1; + if (cursor >= text.length) continue; + const quote = text[cursor]; + if (quote === '"' || quote === "'") { + const end = text.indexOf(quote, cursor + 1); + values.push(end > cursor + 1 ? text.slice(cursor + 1, end) : text.slice(cursor + 1)); + continue; + } + // Unquoted: the token itself plus the joins with the tokens after it. A + // path with spaces arrives quoted from Windows and unquoted from `ps`; + // joining stops at the next flag. + const tokens: string[] = []; + while (cursor < text.length && tokens.length < MAX_BARE_JOIN_TOKENS) { + let end = cursor; + while (end < text.length && !/\s/.test(text[end])) end += 1; + const token = text.slice(cursor, end); + if (token.startsWith("-")) break; + tokens.push(token); + values.push(tokens.join(" ")); + while (end < text.length && /\s/.test(text[end])) end += 1; + cursor = end; + } + } + return values.filter((value) => value.length > 0); +} + +/** Does one `--resume` value name this session? omp accepts the file path or + * the id, so a path, a basename, `.jsonl` and `_.jsonl` all count. + * Shared by the per-session match and the scan-first candidate selection so + * the two can never drift apart. */ +function resumeValueMatches(value: string, sessionId: string, fileKey: string, fileBase: string): boolean { + if (fileKey && comparableProjectPath(value) === fileKey) return true; + const valueBase = basenameAny(value); + if (fileBase && valueBase === fileBase) return true; + // An id may be passed instead of a path: `` or `_.jsonl`. + if (value === sessionId) return true; + if (valueBase === `${sessionId}.jsonl`) return true; + if (valueBase.endsWith(`_${sessionId}.jsonl`)) return true; + return false; +} + +/** The session id a `--resume` value may carry: the value itself, or the + * trailing `` of `.jsonl` / `_.jsonl`. */ +function sessionIdFromResumeValue(value: string): string { + const base = basenameAny(value); + if (!base.endsWith(".jsonl")) return value; + const stem = base.slice(0, -".jsonl".length); + const underscore = stem.lastIndexOf("_"); + return underscore >= 0 ? stem.slice(underscore + 1) : stem; +} + +export interface SessionOwnerTarget { + sessionId: string; + sessionFile?: string; + /** Pids to ignore (our own child still names the old file on its cmdline). */ + excludePids?: number[]; +} + +/** The process opened on this session, or undefined. */ +export function matchSessionOwner( + processes: OmpProcessInfo[], + target: SessionOwnerTarget, +): OmpProcessInfo | undefined { + const fileKey = target.sessionFile ? comparableProjectPath(target.sessionFile) : ""; + const fileBase = target.sessionFile ? basenameAny(target.sessionFile) : ""; + for (const process of processes) { + if (target.excludePids?.includes(process.pid)) continue; + if (!process.commandLine.includes("--resume")) continue; + const values = process.resumeTargets ?? resumeArguments(process.commandLine); + for (const value of values) { + if (resumeValueMatches(value, target.sessionId, fileKey, fileBase)) return process; + } + } + return undefined; +} + +/** + * Which of `candidates` a scanned process names on its command line. The scan + * runs first and this decides who needs a closer look, so a session tree of any + * size cannot hide a live foreign owner behind a cap: only the *transcript* + * signal needs the candidate list to be recent, a process/instance owner is + * found by its own command line. Matching rules are `resumeValueMatches`. + */ +export function sessionIdsNamedByProcesses( + processes: OmpProcessInfo[], + candidates: Iterable<{ id: string; sessionFile?: string }>, +): Set { + const byId = new Map(); + const byPath = new Map(); + const byBase = new Map(); + for (const candidate of candidates) { + byId.set(candidate.id, candidate.id); + if (!candidate.sessionFile) continue; + byPath.set(comparableProjectPath(candidate.sessionFile), candidate.id); + byBase.set(basenameAny(candidate.sessionFile), candidate.id); + } + const ids = new Set(); + for (const process of processes) { + if (!process.commandLine.includes("--resume")) continue; + const values = process.resumeTargets ?? resumeArguments(process.commandLine); + for (const value of values) { + const pathHit = byPath.get(comparableProjectPath(value)); + if (pathHit) { + ids.add(pathHit); + continue; + } + const base = basenameAny(value); + const baseHit = byBase.get(base) ?? byId.get(sessionIdFromResumeValue(value)); + if (baseHit) ids.add(baseHit); + } + } + return ids; +} diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 47c5be6ff..d106734b7 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -110,6 +110,19 @@ test("RpcProcess does not create a separate Windows console", async () => { await proc.dispose(0); }); +test("an exited child reports no pid", async () => { + // The getter feeds the ownership scan's exclusion list. A retained pid after + // the exit event is a hazard: the OS can hand that pid to an unrelated omp + // while the dispose is still in flight, and the scan would then ignore the + // real owner of the session. + const transport = makeTransport(); + const proc = startProcess(transport); + await proc.waitReady(); + assert.equal(proc.pid, 4321, "a live child reports its pid"); + transport.child.emit("exit", 0, null); + assert.equal(proc.pid, undefined, "an exited child has no pid to exclude"); +}); + test("RpcProcess reassembles v2 events and rejects pending commands when the child crashes", async () => { const transport = makeTransport(); transport.onCommand = (command) => { @@ -193,8 +206,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..01ac6dce7 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -212,6 +212,14 @@ export class RpcProcess { return !this.exited; } + /** The omp child's OS pid; undefined before spawn resolved or after exit. + * A retained pid is a hazard: the OS can reuse it while a dispose is still + * in flight, and the ownership scan would then exclude an unrelated omp + * process that happens to hold it. */ + get pid(): number | undefined { + return this.exited ? undefined : 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 +252,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..dfafd1fd4 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,403 @@ 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 late answer to a timed-out command is life, not a frame of the run", async (t) => { + // `RpcProcess` forwards a `response` frame even when its command already + // timed out. It proves the child's event loop is alive (the watchdog must not + // dispose it), but it is not the run reporting: moving the frame clock would + // hide a stream that has been silent for hours behind a poll answer. + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + let disposed = 0; + let timeouts = false; + const frameListeners = new Set(); + const fakeProc = { + isAlive: true, + onFrame: (listener) => { frameListeners.add(listener); return () => frameListeners.delete(listener); }, + sendCommand: async (command, timeoutMs) => { + if (timeouts) throw new RpcCommandTimeoutError(command.type, timeoutMs); + return { sessionId: "late-answer", sessionFile: "", isStreaming: true, isCompacting: false }; + }, + sendFrame: () => {}, + dispose: async () => { disposed += 1; }, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "late-answer"); + wrapper.start(); + t.after(() => wrapper.destroyAndWait()); + const emit = (frame) => { for (const listener of frameListeners) listener(frame); }; + emit({ type: "agent_start" }); + + const realNow = Date.now; + let offset = 0; + Date.now = () => realNow() + offset; + try { + offset = 30 * 60_000; + emit({ type: "response", id: "late", success: true, data: {} }); + const silent = (await wrapper.send({ type: "get_state" })).silentForMs; + assert.ok(silent !== null && Math.abs(silent - offset) < 100, `a late response must not reset the run's clock, got ${silent}`); + + // It still counts as evidence of life: the next command timeout must answer + // `session_slow` without disposing a child that answered a moment ago. + timeouts = true; + await assert.rejects(wrapper.send({ type: "get_state" }), (err) => { + assert.equal(err.code, "session_slow"); + return true; + }); + assert.equal(disposed, 0, "a child that just answered is not stalled"); + assert.equal(wrapper.isAlive(), true); + } finally { + Date.now = realNow; + } +}); + +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 +1030,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 () => { @@ -807,6 +1289,59 @@ test("a crash of an idle session does not notify", async (t) => { assert.deepEqual(delivered, []); }); +test("a prompt that was never started still notifies when the child exits", async (t) => { + // The prompt is in omp's stdin and the ack arrived, but `agent_start` never + // did: only `promptRunning` marks the run (`unsettled` and `streaming` are + // false). A terminal `agent_end` clears that flag synchronously, so emitting + // it before the notification guard silenced the exit notice entirely. + const { wrapper, delivered } = await notifyingSession(t); + await wrapper.send({ type: "prompt", message: "Hello" }); + wrapper.handleProcessExit({ code: 1, signal: null, stderrTail: "killed" }); + assert.deepEqual(delivered, [["error", "killed"]]); +}); + +test("the stall watchdog notifies before the terminal agent_end clears the run flags", async (t) => { + const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + const { saveDevice, listHistory } = await runtimeJiti.import("./notification-store.ts"); + const { WebRpcError } = await runtimeJiti.import("./rpc-manager.ts"); + const previousHub = globalThis.__ompNotificationHub; + globalThis.__ompNotificationHub = { presence: new Map(), streams: new Map() }; + saveDevice("stall-device", { enabled: true, types: { completed: true, input: true, error: true, modelSwitch: false }, whenActive: "toast", locale: "en" }); + t.after(() => { globalThis.__ompNotificationHub = previousHub; }); + + let promptAcked = false; + const fakeProc = { + isAlive: true, + onFrame: () => () => {}, + sendCommand: async (command, timeoutMs) => { + if (command.type === "prompt") { + promptAcked = true; + return { agentInvoked: true }; + } + if (promptAcked) throw new RpcCommandTimeoutError(command.type, timeoutMs); + return { sessionId: "stall-notify", sessionFile: "", isStreaming: false, isCompacting: false }; + }, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "stall-notify"); + wrapper.start(); + t.after(() => wrapper.destroyAndWait()); + await wrapper.send({ type: "prompt", message: "Hello" }); + + const realNow = Date.now; + Date.now = () => realNow() + 5 * 60_000; + try { + await assert.rejects(wrapper.send({ type: "get_state" }), (error) => error instanceof WebRpcError && error.code === "session_slow"); + } finally { + Date.now = realNow; + } + assert.equal(wrapper.isAlive(), false, "the watchdog disposed the child"); + const recorded = listHistory().filter((entry) => entry.event.sessionId === "stall-notify"); + assert.equal(recorded.length, 1, "the stalled exit reaches the notification history"); +}); + test("buildSessionSpawnArgs maps tool presets to spawn flags", async () => { const { createJiti } = await import("jiti"); const jiti = createJiti(import.meta.url); @@ -893,40 +1428,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 +1465,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 +1636,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 +2032,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" }); @@ -2659,3 +3233,71 @@ test("waitForTurnEnd resolves on terminal agent_end and rejects on timeout (#275 emit({ type: "prompt_result" }); await promptDone; }); + +test("a move right after our own prompt is announced as a contention copy", async (t) => { + let state = { sessionId: "orig", sessionFile: "/s/orig.jsonl", isStreaming: false }; + const { wrapper, emit } = snapshotSession(t, async (command) => (command.type === "get_state" ? { ...state } : {}), SnapshotWrapper, "orig"); + await wrapper.send({ type: "get_state" }); + const events = []; + wrapper.onEvent((event) => events.push(event)); + + // Our prompt goes out; omp then reports that it moved the conversation + // because another process owns the file. + await wrapper.send({ type: "prompt", message: "hello" }); + state = { sessionId: "copy", sessionFile: "/s/copy.jsonl", isStreaming: true }; + emit({ type: "notice", level: "warning", source: "session-persistence", message: "Session moved to a new file" }); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const fork = events.find((event) => event.type === "session_contention_fork"); + assert.ok(fork, `no contention event in ${JSON.stringify(events.map((event) => event.type))}`); + // Both ids identify the pair; the event carries no owner details (the clients + // never read them, and a failed scan must not shape a user-visible message). + assert.deepEqual({ fromId: fork.fromId, toId: fork.toId }, { fromId: "orig", toId: "copy" }); + assert.equal("elsewhere" in fork, false); +}); + +test("a starting omp child owns its session from the first moment", async (t) => { + // Regression (bug 1): the wrapper only entered the registry after its + // handshake, so a process scan inside the spawn window matched our OWN child's + // `--resume` command line and reported the session as foreign. The sidebar + // then showed an "elsewhere" badge for our own run and a second tab got + // 409 instead of sharing the start lock. + const { mkdtempSync, rmSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { createJiti } = await import("jiti"); + const jiti = createJiti(import.meta.url); + const { startRpcSession, isLocallyOwnedSession, getOwnChildPids } = jiti("./rpc-manager.ts"); + + const dir = mkdtempSync(join(tmpdir(), "omp-web-starting-")); + const sessionId = "01a17e30-0000-7000-8000-00000000beef"; + const sessionFile = join(dir, `2026-01-01_${sessionId}.jsonl`); + writeFileSync(sessionFile, `${JSON.stringify({ type: "session", version: 3, id: sessionId, cwd: dir })}\n`); + // A launcher that never answers the handshake: the spawn window stays open. + const sleeper = join(dir, "sleeper.cjs"); + writeFileSync(sleeper, "setTimeout(() => process.exit(0), 1500);\n"); + const launcher = join(dir, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp.sh"); + writeFileSync( + launcher, + process.platform === "win32" + ? `@echo off\r\n"${process.execPath}" "${sleeper}"\r\n` + : `#!/bin/sh\n"${process.execPath}" "${sleeper}"\n`, + { mode: 0o755 }, + ); + const previousBin = process.env.OMP_WEB_OMP_BIN; + process.env.OMP_WEB_OMP_BIN = launcher; + t.after(() => { + if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = previousBin; + globalThis.__ompExitedSessions?.delete(sessionId); + rmSync(dir, { recursive: true, force: true }); + }); + + const started = startRpcSession(sessionId, sessionFile, dir); + assert.equal(isLocallyOwnedSession(sessionId), true, "ours while the child is still starting"); + assert.equal(getOwnChildPids().length, 1, "the starting child is one of our own pids"); + + await assert.rejects(started, /exited|ready|omp/i); + assert.equal(isLocallyOwnedSession(sessionId), false, "a failed spawn leaves nothing behind"); + assert.deepEqual(getOwnChildPids(), []); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8e23cee8..de770c880 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -28,6 +28,7 @@ import { type AgentToolSessionOps, } from "./agent-tools"; import { markShuttingDown, recordRunningSessions, RESUME_PROMPT, takeInterruptedSessions } from "./session-resume"; +import { detectSessionOwner, getElsewhereSessions, setElsewhereChangeNotifier, setElsewhereOwnershipContext, type ElsewhereSessionInfo } from "./session-owner"; import { PRESET_FULL } from "./tool-presets"; import { comparableProjectPath } from "./comparable-path"; import { samePath } from "./paths"; @@ -69,6 +70,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 +102,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 +164,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 +248,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 +296,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 +352,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 +437,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 +466,15 @@ 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; + /** When a prompt of our own was dispatched; a move right after it means we + * collided with another writer (omp forked instead of taking the lease). */ + private lastPromptAt = 0; + /** This wrapper already announced the current move as a contention copy. */ + private movedByContention = 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 +534,7 @@ export class AgentSessionWrapper { this.advisorSpawned = advisorSpawned; this._sessionId = expectedSessionId; this.disconnectDestroyMs = disconnectDestroyMs; + this.lastEvidenceAt = Date.now(); } get sessionId(): string { @@ -436,15 +545,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 +589,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 +638,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 +651,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 +696,7 @@ export class AgentSessionWrapper { start(): void { this.unsubscribeFrames = this.proc.onFrame((frame) => this.handleFrame(frame)); + this.lastEvidenceAt = Date.now(); this.resetIdleTimer(); notifyRunningChange(); } @@ -566,17 +718,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 +745,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 +784,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 +828,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; @@ -734,9 +898,15 @@ export class AgentSessionWrapper { /** Re-read identity after omp reported that it moved this session to a new file. */ private async followSessionMove(): Promise { this.sessionMovePending = true; + const fromId = this._sessionId; + const promptAt = this.lastPromptAt; + let movedTo: string | null = null; try { const state = await this.getStateWithTimeout(); - if (this._alive) this.applyIdentity(state); + if (this._alive) { + this.applyIdentity(state); + if (this._sessionId !== fromId) movedTo = this._sessionId; + } } catch { // The next get_state-driven refresh still applies the pending move. } finally { @@ -745,6 +915,16 @@ export class AgentSessionWrapper { if (this.sessionMovePending && this._alive) this.sessionMovePending = false; notifyRunningChange({ refreshSessionList: true }); } + // A move within one prompt ack window is the collision case: another omp + // process held the lease, so omp moved the conversation to a copy when our + // prompt was written. That must be visible, not look like a new chat. + if (movedTo && fromId && promptAt > 0 && Date.now() - promptAt <= PROMPT_ACK_TIMEOUT_MS && !this.movedByContention) { + this.movedByContention = true; + // Another omp process held the lease, so omp moved the conversation to a + // copy when our prompt was written. Both ids identify the pair for the + // clients (original ↔ copy); nothing else is needed here. + this.emit({ type: "session_contention_fork", fromId, toId: movedTo }); + } } handleProcessExit( @@ -762,12 +942,16 @@ export class AgentSessionWrapper { level: "error", message: `The omp process for this session exited unexpectedly (${status})${detail ? `: ${detail}` : "."}`, }); - // Terminal agent_end so a client mid-stream stops spinning immediately - // instead of waiting for the reconcile poll. - if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); + // Published before the terminal `agent_end` below: that emit clears + // `promptRunning` synchronously, which would skip the exit notice for a + // prompt that was dispatched but never started (no `unsettled`, no + // `streaming`). if (this.streaming || this.promptRunning || this.unsettled) { this.publishNotifications({ type: "process_exit", detail: detail || status }); } + // Terminal agent_end so a client mid-stream stops spinning immediately + // instead of waiting for the reconcile poll. + if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); this.destroy(); } @@ -787,6 +971,15 @@ 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. A + // late answer to a timed-out command (`response`) is life, not a run frame: + // moving this clock would mask a stream that has been silent for hours, and + // `get_state` answers are exactly what a wedged run keeps producing. + if (frame.type !== "response") 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 +1653,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 +1673,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 +1741,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 +1800,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 +1890,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 +1963,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 +1972,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 +1987,112 @@ 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.", + }); + // Notification first: a terminal `agent_end` clears `promptRunning` + // synchronously, and the guard below would then skip the exit notice for a + // stalled prompt waiting for `agent_start` (no `unsettled`, no `streaming`). + if (this.streaming || this.promptRunning || this.unsettled) { + this.publishNotifications({ type: "process_exit", detail: "stalled" }); + } + // 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: [] }); + 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); @@ -1824,9 +2136,12 @@ export class AgentSessionWrapper { if (!streamingBehavior) { this.responseObserved = false; this.responseRunActive = false; + this.lastPromptAt = Date.now(); + this.movedByContention = false; 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 +2151,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 +2172,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 +2218,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 +2233,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 +2244,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 +2266,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 +2284,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 +2293,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 +2301,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 +2322,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 +2334,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 +2365,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 +2384,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 +2449,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 +2469,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 +2487,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 +2504,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 +2539,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" }; } @@ -2251,6 +2613,8 @@ export interface RunningSessionUpdate { ids: string[]; runningSessions: RunningRpcSession[]; exitedSessions: ExitedRpcSession[]; + /** Sessions a foreign omp process/instance holds (never in `ids`). */ + elsewhereSessions: ElsewhereSessionInfo[]; refreshSessionList: boolean; } @@ -2261,6 +2625,7 @@ declare global { var __ompRunningListeners: Set<(update: RunningSessionUpdate) => void> | undefined; var __ompHostToolListeners: Set<(call: CrossSessionHostToolCall) => void> | undefined; var __ompExitedSessions: Map | undefined; + var __ompStartingSessions: Map | undefined; } function getExitedMap(): Map { @@ -2303,6 +2668,18 @@ function getLocks(): Map { + if (!globalThis.__ompStartingSessions) globalThis.__ompStartingSessions = new Map(); + return globalThis.__ompStartingSessions; +} + export function getRpcSession(sessionId: string): AgentSessionWrapper | undefined { return getRegistry().get(sessionId); } @@ -2322,6 +2699,31 @@ export function getRunningRpcSessionIds(): string[] { return getRunningRpcSessions().map((s) => s.id); } +/** Sessions this process runs right now (a live wrapper owns them), including + * a wrapper whose child is still in its startup handshake. */ +export function isLocallyOwnedSession(sessionId: string): boolean { + if (getRegistry().get(sessionId)?.isAlive() === true) return true; + return getStartingSessions().has(sessionId); +} + +/** OS pids of every omp child this instance started — registry wrappers and + * the ones still starting. Ownership detection must exclude all of them: a + * child's command line keeps naming its session forever, which is exactly the + * shape of a foreign owner. */ +export function getOwnChildPids(): number[] { + const pids = new Set(); + for (const wrapper of [...getRegistry().values(), ...getStartingSessions().values()]) { + if (wrapper.pid !== undefined) pids.add(wrapper.pid); + } + return [...pids]; +} + +/** Whether our own child for this session died (so a missing `session_exit` + * is explained locally, not by a foreign writer). */ +export function isOwnCrashedSession(sessionId: string): boolean { + return getExitedMap().has(sessionId) && !getRegistry().get(sessionId)?.isAlive(); +} + /** Stop all live omp children after an explicit runtime update. The browser will * reconnect sessions on demand and start them with the updated executable. */ export async function restartAllRpcSessions(): Promise { @@ -2376,23 +2778,41 @@ 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. * A session file may first appear after its id starts running, so callers can * force one otherwise-identical update to refresh sidebar session metadata. + * Foreign ownership rides along in `elsewhereSessions` (but never in `ids`: the + * unread/notification logic keys off runs this instance actually started). */ export function notifyRunningChange({ refreshSessionList = false }: { refreshSessionList?: boolean } = {}): void { + // The snapshot expires entries and re-checks foreign owners on its own timer; + // it must be able to broadcast that result without importing this module. + setElsewhereChangeNotifier(() => notifyRunningChange()); + // The tick has no caller that could pass the ownership checks, so this module + // registers them: without them a chat this instance took over (our own child + // still names the original file) was re-detected as foreign on every tick. + setElsewhereOwnershipContext({ + isLocal: isLocallyOwnedSession, + ownCrashed: isOwnCrashedSession, + excludePids: getOwnChildPids, + }); const runningSessions = getRunningRpcSessions(); const exitedSessions = getExitedRpcSessions(); + const elsewhereSessions = getElsewhereSessions(); 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), + elsewhereSessions.slice().sort(byId), + ]); if (snapshot === lastRunningSnapshot && !refreshSessionList) return; lastRunningSnapshot = snapshot; syncInterruptibleSessions(); - const update: RunningSessionUpdate = { ids, runningSessions, exitedSessions, refreshSessionList }; + const update: RunningSessionUpdate = { ids, runningSessions, exitedSessions, elsewhereSessions, refreshSessionList }; for (const listener of getRunningListeners()) { try { listener(update); } catch { /* ignore listener errors */ } } @@ -2417,6 +2837,13 @@ export async function resumeInterruptedSessions(): Promise { try { const filePath = await resolveSessionPath(id); if (!filePath) return; + // Another omp (terminal, or an omp-web instance that took over) may hold + // the file now; a resume prompt would fork it into a copy. Skip instead. + const elsewhere = await detectSessionOwner(id, filePath, { excludePids: getOwnChildPids() }); + if (elsewhere) { + console.warn(`[omp-web] not resuming session ${id}: it is being run by another omp process`); + return; + } const header = readSessionHeader(filePath); const { cwd } = resolveSpawnCwdResult(header?.cwd); const { session } = await startRpcSession(id, filePath, cwd, undefined, advisor, header?.cwd); @@ -2618,6 +3045,11 @@ export async function startRpcSession( sessionFile ? sessionId : "", ); holder.wrapper = created; + // The omp child exists from here on and its command line names the session + // it resumes; ownership detection must treat it as ours during the whole + // handshake (up to several seconds), or it reports our own spawn as a + // foreign owner and the UI shows "running elsewhere" for our own run. + getStartingSessions().set(sessionId, created); created.start(); try { await created.waitUntilReady(); @@ -2663,7 +3095,13 @@ export async function startRpcSession( clearExitedRpcSession(sessionId); if (realSessionId !== sessionId) clearExitedRpcSession(realSessionId); return { session: created, realSessionId }; - })().finally(() => locks.delete(sessionId)); + })().finally(() => { + locks.delete(sessionId); + // The wrapper is registered by now (success) or disposed (failure); either + // way it is no longer "starting", and the start lock is already released so + // no replacement can race this delete. + getStartingSessions().delete(sessionId); + }); locks.set(sessionId, starting); return starting; diff --git a/lib/session-owner.test.mjs b/lib/session-owner.test.mjs new file mode 100644 index 000000000..c555218ec --- /dev/null +++ b/lib/session-owner.test.mjs @@ -0,0 +1,463 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const { + ELSEWHERE_ACTIVE_WINDOW_MS, + ELSEWHERE_REFRESH_MS, + detectSessionOwner, + getElsewhereSessions, + refreshElsewhereSessions, + resetElsewhereSessions, + setElsewhereChangeNotifier, + setElsewhereOwnershipContext, +} = await jiti.import("./session-owner.ts"); +const { resetOmpProcessCache, setOmpProcessScanRunner } = await jiti.import("./omp-processes.ts"); + +const SESSION_ID = "01a17cd4-6f4c-7d5e-8a90-112233445566"; +const dir = mkdtempSync(join(tmpdir(), "omp-web-session-owner-")); +test.after(() => rmSync(dir, { recursive: true, force: true })); + +let fileCounter = 0; +/** A session file whose transcript ends in assistant text (a finished turn). */ +function sessionFile({ exit = false } = {}) { + fileCounter += 1; + const path = join(dir, `2026-10-27_session-${fileCounter}.jsonl`); + const lines = [ + { type: "session", version: 3, id: SESSION_ID, cwd: dir, timestamp: "2026-10-27T10:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: null, message: { role: "assistant", content: [{ type: "text", text: "hi" }] } }, + ]; + if (exit) lines.push({ type: "custom", customType: "session_exit", id: "x1", parentId: null, data: { reason: "dispose" } }); + writeFileSync(path, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`); + return path; +} + +/** Process list output in the shape the host's scanner would emit. */ +function processOutput(entries) { + // The POSIX rows carry the uid column (`ps -eo pid=,uid=,args=`): the scan + // drops rows without a numeric uid, and the same-user filter compares this + // column against the server's own uid. + const uid = typeof process.getuid === "function" ? process.getuid() : 0; + return process.platform === "win32" + ? JSON.stringify(entries.map(({ pid, commandLine }) => ({ ProcessId: pid, CommandLine: commandLine }))) + : `${entries.map(({ pid, commandLine }) => `${pid} ${uid} ${commandLine}`).join("\n")}\n`; +} + +test.afterEach(() => { + setOmpProcessScanRunner(null); + resetOmpProcessCache(); + resetElsewhereSessions(); + setElsewhereChangeNotifier(() => {}); + setElsewhereOwnershipContext(null); +}); + +test("a local live wrapper is never elsewhere", async () => { + const file = sessionFile(); + assert.equal(await detectSessionOwner(SESSION_ID, file, { isLocal: () => true }), null); +}); + +test("another omp-web instance's running list outranks the transcript", async () => { + const file = sessionFile(); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { + foreignLists: [{ pid: 1234, ids: [SESSION_ID] }], + processes: [], + }); + assert.equal(elsewhere?.kind, "omp-web"); + assert.equal(elsewhere?.source, "instance-list"); + assert.equal(elsewhere?.running, true); + assert.equal(elsewhere?.active, true); +}); + +test("a live omp process started on the file owns it", async () => { + const file = sessionFile(); + let calls = 0; + setOmpProcessScanRunner(async () => { + calls += 1; + return processOutput([{ pid: 4242, commandLine: `omp.exe --mode rpc-ui --resume "${file}"` }]); + }); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { foreignLists: [] }); + assert.equal(calls, 1, "the detection ran the process scan"); + assert.equal(elsewhere?.kind, "terminal"); + assert.equal(elsewhere?.source, "process"); + assert.equal(elsewhere?.active, true); + assert.equal(elsewhere?.running, false, "a finished transcript is owned but idle"); +}); + +test("our own child's pid is excluded from the owner search", async () => { + // The file is closed, so the transcript cannot explain anything: the only + // signal is the process, and excluding its pid must clear it. + const file = sessionFile({ exit: true }); + setOmpProcessScanRunner(async () => processOutput([{ pid: 4242, commandLine: `omp.exe --resume "${file}"` }])); + assert.equal((await detectSessionOwner(SESSION_ID, file, { foreignLists: [] }))?.source, "process"); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { foreignLists: [], excludePids: [4242] }); + assert.equal(elsewhere, null); +}); + +test("an open transcript written just now is a weak foreign signal", async () => { + const file = sessionFile(); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { foreignLists: [], processes: [] }); + assert.equal(elsewhere?.kind, "terminal"); + assert.equal(elsewhere?.source, "transcript"); + assert.equal(elsewhere?.running, false); + assert.equal(elsewhere?.active, true); + assert.ok((elsewhere?.lastActivityAt ?? 0) > 0); + // Integer epoch ms: the wire contract in docs/android/protocol.md §3.7, and a + // `Long`-typed client rejects a fractional mtimeMs (breaks the whole frame). + assert.ok(Number.isInteger(elsewhere?.lastActivityAt), `integer epoch ms, got ${elsewhere?.lastActivityAt}`); +}); + +test("a trailing session_exit clears the transcript signal", async () => { + const file = sessionFile({ exit: true }); + assert.equal(await detectSessionOwner(SESSION_ID, file, { foreignLists: [], processes: [] }), null); +}); + +test("our own crash explains an exit-less transcript, not a foreign writer", async () => { + const file = sessionFile(); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { + foreignLists: [], + processes: [], + ownCrashed: () => true, + }); + assert.equal(elsewhere, null); + // A live foreign process still wins over the local crash record. + setOmpProcessScanRunner(async () => processOutput([{ pid: 777, commandLine: `omp.exe --resume "${file}"` }])); + const owned = await detectSessionOwner(SESSION_ID, file, { foreignLists: [], processes: undefined, ownCrashed: () => true }); + assert.equal(owned?.source, "process"); +}); + +test("a failing process scan degrades to the transcript signal", async () => { + const file = sessionFile(); + setOmpProcessScanRunner(async () => { + throw new Error("no powershell"); + }); + const elsewhere = await detectSessionOwner(SESSION_ID, file, { foreignLists: [] }); + assert.equal(elsewhere?.source, "transcript"); +}); + +test("OMP_WEB_FOREIGN_SCAN=0 disables only the process scan", async () => { + const file = sessionFile(); + const previous = process.env.OMP_WEB_FOREIGN_SCAN; + process.env.OMP_WEB_FOREIGN_SCAN = "0"; + try { + resetOmpProcessCache(); + // The foreign instance list needs no scan and stays authoritative. + const listed = await detectSessionOwner(SESSION_ID, file, { foreignLists: [{ pid: 1, ids: [SESSION_ID] }] }); + assert.equal(listed?.source, "instance-list"); + // The transcript fallback still protects a recently written, exit-less file. + const transcript = await detectSessionOwner(SESSION_ID, file, { foreignLists: [] }); + assert.equal(transcript?.source, "transcript"); + } finally { + if (previous === undefined) delete process.env.OMP_WEB_FOREIGN_SCAN; + else process.env.OMP_WEB_FOREIGN_SCAN = previous; + resetOmpProcessCache(); + } +}); + +test("the snapshot keeps foreign sessions and drops transcript entries after the window", async () => { + const file = sessionFile(); + setOmpProcessScanRunner(async () => processOutput([])); + const refreshed = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(refreshed.length, 1); + assert.equal(refreshed[0].id, SESSION_ID); + assert.equal(refreshed[0].source, "transcript"); + assert.equal(getElsewhereSessions().length, 1); + // A transcript-only signal expires with the activity window; no rescan needed. + assert.equal(getElsewhereSessions(Date.now() + ELSEWHERE_ACTIVE_WINDOW_MS + 1).length, 0); +}); + +test("an idle foreign owner keeps its badge after its file stopped growing", async () => { + // A terminal `omp --resume` that sits between turns holds the lease for + // hours: the list must still report it, even though the transcript is silent + // and therefore contributes nothing. + const file = sessionFile({ exit: true }); + setOmpProcessScanRunner(async () => processOutput([{ pid: 6060, commandLine: `omp.exe --resume "${file}"` }])); + const idleSince = Date.now() - ELSEWHERE_ACTIVE_WINDOW_MS - 60_000; + const refreshed = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: idleSince }]); + assert.equal(refreshed.length, 1); + assert.equal(refreshed[0].source, "process"); + assert.equal(refreshed[0].active, true); + assert.equal(refreshed[0].lastActivityAt, undefined, "an old file is not read for the tail"); +}); + +test("a failing scan keeps a known process owner instead of clearing it", async () => { + // A timeout is "unknown", not "no owner": the badge must survive until a scan + // answers again, or one slow PowerShell would hide a live terminal omp for as + // long as no file event triggers a refresh. + const file = sessionFile({ exit: true }); + let fail = false; + setOmpProcessScanRunner(async () => { + if (fail) throw new Error("powershell timed out"); + return processOutput([{ pid: 6061, commandLine: `omp.exe --resume "${file}"` }]); + }); + const idleSince = Date.now() - ELSEWHERE_ACTIVE_WINDOW_MS - 60_000; + const first = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: idleSince }]); + assert.equal(first.length, 1); + assert.equal(first[0].source, "process"); + + fail = true; + resetOmpProcessCache(); + const second = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: idleSince }]); + assert.equal(second.length, 1, "the known owner survives a failed scan"); + assert.equal(second[0].source, "process"); +}); + +test("a stale file with no live owner is not elsewhere", async () => { + // The same candidate shape as above without a process: an old transcript can + // never be a live run, and the file is not read to guess otherwise. + const file = sessionFile(); + setOmpProcessScanRunner(async () => processOutput([])); + const refreshed = await refreshElsewhereSessions([ + { id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() - ELSEWHERE_ACTIVE_WINDOW_MS - 1 }, + ]); + assert.deepEqual(refreshed, []); +}); + +test("refresh drops sessions this instance owns", async () => { + const file = sessionFile(); + setOmpProcessScanRunner(async () => processOutput([])); + const refreshed = await refreshElsewhereSessions( + [{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }], + { isLocal: () => true }, + ); + assert.deepEqual(refreshed, []); + assert.deepEqual(getElsewhereSessions(), []); +}); + +test("the snapshot tick re-checks ownership and notifies exactly once when it clears", async (t) => { + // The file is already closed (trailing session_exit), so once the owning + // process disappears nothing else can keep the entry alive. + const file = sessionFile({ exit: true }); + let scans = 0; + setOmpProcessScanRunner(async () => { + scans += 1; + // Owned on the first scan, gone afterwards (the terminal omp exited). + return processOutput(scans === 1 ? [{ pid: 5150, commandLine: `omp.exe --resume "${file}"` }] : []); + }); + // Mock the timers BEFORE the refresh arms its tick, so that timer is fake. + t.mock.timers.enable({ apis: ["setTimeout"] }); + const refreshed = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(refreshed[0]?.source, "process"); + + let notifications = 0; + setElsewhereChangeNotifier(() => { + notifications += 1; + }); + // The tick was armed by the refresh above; one refresh interval later the + // 10 s scan cache is long expired too, so it re-scans, finds nothing and + // broadcasts the change. + resetOmpProcessCache(); + t.mock.timers.tick(ELSEWHERE_REFRESH_MS + 1); + for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setImmediate(resolve)); + assert.equal(notifications, 1); + assert.deepEqual(getElsewhereSessions(), []); +}); + +test("a change that lands during an active refresh is queued, not dropped", async () => { + // The file watcher refreshes per changed file. When two writes land while one + // scan is running, the second caller used to receive the first pass's + // snapshot — which predates its own file — and broadcast it, so the new owner + // only appeared on the next event. + const firstFile = sessionFile({ exit: true }); + const secondFile = sessionFile({ exit: true }); + const SECOND_ID = "01a17cd4-6f4c-7d5e-8a90-aabbccddeeff"; + let release; + const blocked = new Promise((resolve) => { release = resolve; }); + let scans = 0; + setOmpProcessScanRunner(async () => { + scans += 1; + if (scans === 1) await blocked; + return processOutput([ + { pid: 7101, commandLine: `omp.exe --resume "${firstFile}"` }, + { pid: 7102, commandLine: `omp.exe --resume "${secondFile}"` }, + ]); + }); + const idleSince = Date.now() - ELSEWHERE_ACTIVE_WINDOW_MS - 60_000; + const active = refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: firstFile, mtimeMs: idleSince }]); + // Arrives mid-scan: its id cannot be in the pass that is already running. + const queued = refreshElsewhereSessions([{ id: SECOND_ID, sessionFile: secondFile, mtimeMs: idleSince }]); + release(); + const [, second] = await Promise.all([active, queued]); + assert.deepEqual(second.map((entry) => entry.id).sort(), [SECOND_ID, SESSION_ID].sort(), "the late caller's snapshot carries both sessions"); + assert.equal(second.find((entry) => entry.id === SECOND_ID)?.source, "process"); + assert.deepEqual(getElsewhereSessions().map((entry) => entry.id).sort(), [SECOND_ID, SESSION_ID].sort()); +}); + +test("the snapshot tick uses the registered ownership context", async (t) => { + // Rework N1: the tick fired without `isLocal`/`ownCrashed`/`excludePids`, so + // a chat this instance had taken over (owner ended, the user sent, `?force=1`) + // stayed "elsewhere" as long as our own child lived: that child still names + // the original file on its `--resume`, and the original file is never written + // again. The informed path already answered "ours" for the same state. + const file = sessionFile({ exit: true }); + // The scan sees exactly one owner: our own child, naming the original file. + setOmpProcessScanRunner(async () => processOutput([{ pid: 7777, commandLine: `omp.exe --resume "${file}"` }])); + t.mock.timers.enable({ apis: ["setTimeout"] }); + const first = await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(first[0]?.source, "process", "the foreign owner is reported first"); + + // The foreign process ended and this instance owns the session now: the same + // checks every route passes per call, registered for the caller-less tick. + setElsewhereOwnershipContext({ isLocal: () => true }); + let notifications = 0; + setElsewhereChangeNotifier(() => { + notifications += 1; + }); + resetOmpProcessCache(); + t.mock.timers.tick(ELSEWHERE_REFRESH_MS + 1); + for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(getElsewhereSessions(), [], "the tick must honour the ownership context"); + assert.equal(notifications, 1, "the cleared owner is broadcast"); +}); + +test("the tick also excludes this instance's own child pids", async (t) => { + // Same shape, only the pid list: our own child's stale command line is what + // made the entry stick, so the registered pid provider must reach the scan + // match even when `isLocal` does not (a moved-from file keeps the alias). + const file = sessionFile({ exit: true }); + setOmpProcessScanRunner(async () => processOutput([{ pid: 4040, commandLine: `omp.exe --resume "${file}"` }])); + t.mock.timers.enable({ apis: ["setTimeout"] }); + await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(getElsewhereSessions().length, 1); + + setElsewhereOwnershipContext({ excludePids: () => [4040] }); + resetOmpProcessCache(); + t.mock.timers.tick(ELSEWHERE_REFRESH_MS + 1); + for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(getElsewhereSessions(), [], "our own child never owns a chat"); +}); + +test("a failing self-tick re-check is contained instead of crashing the server", async (t) => { + // The tick is fire-and-forget: its promise had no rejection handler, so any + // failing re-check (a throwing ownership callback from the other server + // bundle, a rejecting scan) was an unhandled rejection — Node ends the whole + // server on those. + const file = sessionFile(); + setOmpProcessScanRunner(async () => processOutput([{ pid: 6161, commandLine: `omp.exe --resume "${file}"` }])); + t.mock.timers.enable({ apis: ["setTimeout"] }); + await refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(getElsewhereSessions().length, 1); + + setElsewhereOwnershipContext({ + isLocal: () => { + throw new Error("ownership check failed"); + }, + }); + let notifications = 0; + setElsewhereChangeNotifier(() => { + notifications += 1; + }); + const rejections = []; + const onRejection = (reason) => rejections.push(reason); + process.on("unhandledRejection", onRejection); + try { + resetOmpProcessCache(); + t.mock.timers.tick(ELSEWHERE_REFRESH_MS + 1); + for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setImmediate(resolve)); + } finally { + process.off("unhandledRejection", onRejection); + } + + assert.deepEqual(rejections, [], "a failing self-tick must not surface as an unhandled rejection"); + assert.equal(notifications, 0, "a failed refresh has nothing to broadcast"); + assert.equal(getElsewhereSessions().length, 1, "the last good snapshot survives a failed refresh"); +}); + +test("a live owner beyond the recent-candidate cap is still found", async () => { + // Rework N6: the queue used to be `[...cached, ...candidates].slice(0, 80)`, + // so with a busy session tree an idle-open foreign owner on a session that + // sat past the cap was invisible. The scan names its sessions, and those + // candidates are never cut off. + const candidates = []; + for (let i = 0; i < 100; i += 1) { + candidates.push({ + id: `01a17cd4-6f4c-7d5e-9999-${String(i).padStart(12, "0")}`, + sessionFile: sessionFile(), + mtimeMs: Date.now(), + }); + } + const idleId = "01a17cd4-6f4c-7d5e-9999-999999999999"; + const idleFile = sessionFile({ exit: true }); + // Last in the list and silent for longer than the activity window. + candidates.push({ id: idleId, sessionFile: idleFile, mtimeMs: Date.now() - ELSEWHERE_ACTIVE_WINDOW_MS - 60_000 }); + + setOmpProcessScanRunner(async () => processOutput([{ pid: 8181, commandLine: `omp.exe --resume "${idleFile}"` }])); + const refreshed = await refreshElsewhereSessions(candidates); + + const idle = refreshed.find((entry) => entry.id === idleId); + assert.ok(idle, "the idle foreign owner is reported"); + assert.equal(idle.source, "process"); +}); + +/** + * A second, fully independent evaluation of these modules in the same process — + * what Next.js does per server bundle (`lib/session-owner.ts` is compiled into + * every route that imports it, and into the SSE mux). jiti with `moduleCache` + * off gives fresh module bindings, so module-local state stays invisible across + * the split just like in the real server. + */ +async function moduleInstance() { + const fresh = createJiti(import.meta.url, { + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, + moduleCache: false, + }); + return { + owner: await fresh.import("./session-owner.ts"), + processes: await fresh.import("./omp-processes.ts"), + }; +} + +test("the ownership context reaches a tick running in another module instance", async (t) => { + // Rework N1: the context used to be a module-local `let`, so registering it + // from rpc-manager's bundle left the tick's copy empty — the tick re-detected + // a chat this instance had taken over (its own child still names the original + // file on `--resume`) as foreign, for as long as the child lived. Single- + // instance tests could not see that; these two evaluations can. + const tickSide = await moduleInstance(); + const routeSide = await moduleInstance(); + assert.notEqual( + tickSide.owner.setElsewhereOwnershipContext, + routeSide.owner.setElsewhereOwnershipContext, + "the two evaluations must be separate module instances", + ); + + // The file is recent and has no trailing `session_exit`, so even a tick that + // cannot see our scan seam still re-detects *a* signal and keeps the entry: + // the assertion below fails on a module-local context instead of passing by a + // scan miss. + const file = sessionFile(); + tickSide.processes.setOmpProcessScanRunner(async () => processOutput([ + { pid: 7171, commandLine: `omp.exe --resume "${file}"` }, + ])); + t.mock.timers.enable({ apis: ["setTimeout"] }); + const first = await tickSide.owner.refreshElsewhereSessions([{ id: SESSION_ID, sessionFile: file, mtimeMs: Date.now() }]); + assert.equal(first[0]?.source, "process", "the foreign owner is reported first"); + + // This instance took the session over (the user forced a send): the route + // side registers the checks every route passes per call. That registration + // happens in a different module copy, in the same process. + routeSide.owner.setElsewhereOwnershipContext({ isLocal: () => true }); + let notifications = 0; + tickSide.owner.setElsewhereChangeNotifier(() => { + notifications += 1; + }); + tickSide.processes.resetOmpProcessCache(); + t.mock.timers.tick(ELSEWHERE_REFRESH_MS + 1); + for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual( + tickSide.owner.getElsewhereSessions(), + [], + "the tick must see the context registered by the other module instance", + ); + assert.equal(notifications, 1, "the cleared owner is broadcast"); +}); diff --git a/lib/session-owner.ts b/lib/session-owner.ts new file mode 100644 index 000000000..355262d9f --- /dev/null +++ b/lib/session-owner.ts @@ -0,0 +1,548 @@ +import { closeSync, openSync, readSync, statSync } from "fs"; +import { looksLikeRunningTurn } from "./chat-transcript-plan"; +import { listOmpProcesses, matchSessionOwner, sessionIdsNamedByProcesses, type OmpProcessInfo } from "./omp-processes"; +import { readForeignRunningLists, type ForeignRunningList } from "./session-resume"; +import { parseJsonlLenient } from "./omp/session-files"; +import { resolveSessionPath } from "./session-reader"; +import { isRecord } from "./type-guards"; +import type { AgentMessage, ElsewhereSessionInfo, SessionElsewhere } from "./types"; + +export type { ElsewhereSessionInfo, SessionElsewhere }; + +/** + * Who owns a session right now — this instance, another omp-web instance, or a + * terminal `omp`? + * + * omp ≥ 18.5 lets exactly one process write a session: its lease lives in a + * named mutex / abstract socket (no file to read). A second writer does not + * fail, it silently moves the conversation to a fresh sibling file on its first + * write ("open-elsewhere"), which looked like a brand-new chat. omp-web only + * knew about its own children, so a session driven from a terminal, another + * omp-web instance or the installed server looked idle. + * + * Three portable signals, strongest first (see `detectSessionOwner`): + * 1. another live omp-web instance lists the session as mid-run, + * 2. a live `omp` process was started with `--resume `, + * 3. the transcript has no trailing `session_exit` and was written recently. + * + * Everything here is read-only and failure-tolerant: an unreadable session, a + * failing process scan or a timeout must never block a send. + */ + +/** + * Mirror of `EXTERNAL_RUN_STALE_MS` (hooks/useAgentSession-stream.ts): a tail + * that stopped growing for this long is not a live foreign run any more. The + * hook constant cannot be imported here — that module is browser-side. + */ +export const ELSEWHERE_ACTIVE_WINDOW_MS = 60_000; + +/** While a session is known to be elsewhere, re-check it at this cadence so a + * finished terminal `omp` clears the badge without a file write. */ +export const ELSEWHERE_REFRESH_MS = 10_000; + +const TAIL_BYTES = 64 * 1024; +/** Guard against a huge session tree: the transcript signal only needs a file + * written inside the activity window, so only this many *recent* candidates + * are tail-read per refresh. Sessions with a live owner (process scan) or a + * known/cached one are never cut off by this cap. */ +const MAX_RECENT_CANDIDATES = 80; + +export interface SessionTailState { + /** The last record is omp's own `session_exit` (the writer closed the file). */ + hasTrailingExit: boolean; + /** The tail looks mid-turn (tool call without result, or a running tool). */ + looksActive: boolean; + mtimeMs: number; +} + +/** True for the records omp writes while a tool call is executing. */ +const LIVE_TOOL_RECORDS: Record = { + tool_execution_start: true, + tool_execution_update: true, +}; + +function recordType(record: unknown): string | undefined { + return isRecord(record) && typeof record.type === "string" ? record.type : undefined; +} + +/** + * Read the last ≤64 KiB of a session file and describe its end. Backward-safe + * against a half-written last line (parsed leniently, skipped) and against the + * window starting mid-line (first partial line dropped). Returns null when the + * file cannot be read. + */ +export function readSessionTailState(filePath: string): SessionTailState | null { + let size: number; + let mtimeMs: number; + try { + const stat = statSync(filePath); + if (!stat.isFile()) return null; + size = stat.size; + // Integer epoch ms, as documented (docs/android/protocol.md §3.7): mtimeMs + // is fractional on Windows, and a typed client that decodes `Long` (the + // Android app) rejects the whole frame on 1793099856021.7422. + mtimeMs = Math.round(stat.mtimeMs); + } catch { + return null; + } + if (size === 0) return { hasTrailingExit: false, looksActive: false, mtimeMs }; + + const length = Math.min(TAIL_BYTES, size); + let text: string; + try { + const fd = openSync(filePath, "r"); + try { + const buffer = Buffer.allocUnsafe(length); + const read = readSync(fd, buffer, 0, length, size - length); + text = buffer.subarray(0, read).toString("utf8"); + } finally { + closeSync(fd); + } + } catch { + return null; + } + if (length < size) { + // The window starts mid-record; drop that truncated first line. + const newline = text.indexOf("\n"); + text = newline >= 0 ? text.slice(newline + 1) : ""; + } + + const records = parseJsonlLenient>(text); + const tail = records.at(-1); + const tailType = recordType(tail); + const hasTrailingExit = tailType === "custom" && tail?.customType === "session_exit"; + + let looksActive: boolean; + if (hasTrailingExit) { + looksActive = false; + } else if (tailType === "custom" && typeof tail?.customType === "string" && LIVE_TOOL_RECORDS[tail.customType] === true) { + // A tool is executing right now; the agent has not settled yet. + looksActive = true; + } else { + // Judge by the last message in the window: a trailing tool result or an + // assistant tool call means the turn continues. + const messages: AgentMessage[] = []; + for (const record of records) { + if (recordType(record) !== "message") continue; + const message: unknown = record.message; + if (isRecord(message) && typeof message.role === "string") { + // Parsed JSONL entry: the record shape is omp's, validated just enough + // for `looksLikeRunningTurn` (role + content + stopReason). + messages.push(message as unknown as AgentMessage); + } + } + looksActive = messages.length > 0 && looksLikeRunningTurn(messages); + } + + return { hasTrailingExit, looksActive, mtimeMs }; +} + +export interface DetectOwnerOptions { + /** Sessions this process owns (live wrapper) — never elsewhere. */ + isLocal?: (sessionId: string) => boolean; + /** Our own child for this session crashed here: a missing `session_exit` + * plus a recent write is explained locally, so the weakest signal (a + * transcript-only guess) is not a foreign owner. */ + ownCrashed?: (sessionId: string) => boolean; + /** Pids that must not count as the owner (our own child's stale cmdline). */ + excludePids?: number[]; + /** Injected scan results (tests, or one shared scan for a whole session list). */ + processes?: OmpProcessInfo[]; + foreignLists?: ForeignRunningList[]; + /** + * Pre-read tail. `undefined` (default) reads the file; `null` means "no tail + * available" — a file that stopped growing longer ago than the activity + * window cannot be a live transcript signal, but a live owning process must + * still be reported (the list refresh passes null for old sessions instead + * of reading 64 KiB per old chat). + */ + tail?: SessionTailState | null; + now?: () => number; +} + +/** + * Decide whether someone else holds this session. The caller must have ruled + * out its own live wrapper (`isLocal`) — this function's job is the foreign + * side only. Every failure degrades to `null` (do not block). + */ +export async function detectSessionOwner( + sessionId: string, + sessionFile: string | null | undefined, + options: DetectOwnerOptions = {}, +): Promise { + if (options.isLocal?.(sessionId)) return null; + try { + const now = options.now?.() ?? Date.now(); + const tail = options.tail !== undefined + ? options.tail + : (sessionFile ? readSessionTailState(sessionFile) : null); + + const lists = options.foreignLists ?? readForeignRunningLists(); + const listOwner = lists.find((list) => list.ids.includes(sessionId)); + if (listOwner) { + // Another omp-web is mid-run on it; that outranks any tail heuristic. + return { + kind: "omp-web", + source: "instance-list", + running: true, + active: true, + ...(tail ? { lastActivityAt: tail.mtimeMs } : {}), + }; + } + + const processes = options.processes ?? (await listOmpProcesses()).processes; + const owner = matchSessionOwner(processes, { sessionId, sessionFile: sessionFile ?? undefined, excludePids: options.excludePids }); + if (owner) { + return { + kind: "terminal", + source: "process", + // A live owning process keeps ownership even while it is idle between + // turns; `running` only says "mid-turn right now". + running: tail?.looksActive === true, + active: true, + ...(tail ? { lastActivityAt: tail.mtimeMs } : {}), + }; + } + + if (!tail || tail.hasTrailingExit) return null; + if (options.ownCrashed?.(sessionId)) return null; + if (now - tail.mtimeMs >= ELSEWHERE_ACTIVE_WINDOW_MS) return null; + return { + kind: "terminal", + source: "transcript", + running: tail.looksActive, + active: true, + lastActivityAt: tail.mtimeMs, + }; + } catch { + return null; + } +} + +// ---------------------------------------------------------------------------- +// Snapshot for the sidebar and the SSE `running` frames +// +// `notifyRunningChange` is synchronous and called from the hot path of omp's +// event loop, so it cannot await a process scan. This cache is refreshed by the +// session-list route, the SSE file watcher and a small self-scheduling tick +// while anything is elsewhere; readers only filter by time. +// ---------------------------------------------------------------------------- + +interface CachedElsewhere { + id: string; + sessionFile: string; + state: SessionElsewhere; +} + +interface ElsewhereState { + entries: Map; + notifier: (() => void) | null; + timer: NodeJS.Timeout | undefined; + /** One refresh in flight at a time; later callers share its result. */ + refreshing: Promise | null; + /** Candidates that arrived while `refreshing` was in flight; the pass that + * follows it re-detects them. Without this queue a file watcher event that + * landed mid-scan was dropped, and the broadcast carried a map that + * predated the file it was about. */ + pending: Map; + /** Options of the callers that queued into `pending` (merged). */ + pendingOptions: RefreshElsewhereOptions | null; + /** Registered by `rpc-manager`; see `ElsewhereOwnershipContext`. */ + ownershipContext: ElsewhereOwnershipContext | null; +} + +declare global { + var __ompElsewhereState: ElsewhereState | undefined; +} + +function elsewhereState(): ElsewhereState { + const state = globalThis.__ompElsewhereState ??= { + entries: new Map(), + notifier: null, + timer: undefined, + refreshing: null, + pending: new Map(), + pendingOptions: null, + ownershipContext: null, + }; + // Next.js compiles every route as its own server bundle, so this module is + // evaluated once per bundle in one process. Everything the tick needs must + // live on `globalThis` (as it survives hot-reload too); a module-local `let` + // is invisible to the other bundles and the registration silently misses. + // A state object created by an older module version lacks fields added + // later, so fill them in. + state.pending ??= new Map(); + state.pendingOptions ??= null; + state.ownershipContext ??= null; + return state; +} + +/** Sessions an entry may still describe; a transcript-only signal goes stale + * with its last write, ownership signals are cleared by the next refresh. */ +function isStale(entry: CachedElsewhere, now: number): boolean { + return entry.state.source === "transcript" + && entry.state.lastActivityAt !== undefined + && now - entry.state.lastActivityAt >= ELSEWHERE_ACTIVE_WINDOW_MS; +} + +/** Drop expired entries and return what is left. Never scans by itself. */ +export function getElsewhereSessions(now = Date.now()): ElsewhereSessionInfo[] { + const state = elsewhereState(); + const out: ElsewhereSessionInfo[] = []; + for (const [id, entry] of state.entries) { + if (isStale(entry, now)) { + state.entries.delete(id); + continue; + } + out.push({ id, ...entry.state }); + } + return out.sort((a, b) => a.id.localeCompare(b.id)); +} + +export interface ElsewhereCandidate { + id: string; + sessionFile?: string; + mtimeMs?: number; +} + +export interface RefreshElsewhereOptions { + isLocal?: (sessionId: string) => boolean; + ownCrashed?: (sessionId: string) => boolean; + /** Pids that must never count as an owner (our own omp children). */ + excludePids?: number[]; + now?: () => number; +} + +/** + * This instance's own-liveness checks. The routes pass them per call; the + * self-tick has no caller to take them from, and without them it re-detected a + * chat this instance had itself taken over (its own child still names the + * original file on `--resume`) as a foreign owner — forever, while the child + * lived. Registered from `rpc-manager` (which owns the registry and the child + * pids) exactly like `setElsewhereChangeNotifier`, so there is no import cycle. + */ +export interface ElsewhereOwnershipContext { + isLocal?: (sessionId: string) => boolean; + ownCrashed?: (sessionId: string) => boolean; + /** Read on every refresh: our children change while the tick waits. */ + excludePids?: () => number[]; +} + +/** Register (or clear) the ownership context every refresh falls back to. */ +export function setElsewhereOwnershipContext(context: ElsewhereOwnershipContext | null): void { + // On the shared state, never in a module-local binding: the caller + // (`rpc-manager`) and the tick (`refreshElsewhereSessions` below) commonly + // live in different Next server bundles, i.e. in different evaluations of + // this module in the same process. + elsewhereState().ownershipContext = context; +} + +/** Merge the options of two callers queued into the same follow-up pass: the + * first explicit value per field wins, so a queuing caller's own hooks are + * never replaced by a later caller that passed none. */ +function mergeRefreshOptions( + current: RefreshElsewhereOptions | null, + next: RefreshElsewhereOptions, +): RefreshElsewhereOptions { + if (!current) return next; + return { + isLocal: current.isLocal ?? next.isLocal, + ownCrashed: current.ownCrashed ?? next.ownCrashed, + excludePids: current.excludePids ?? next.excludePids, + now: current.now ?? next.now, + }; +} + +/** + * Re-detect ownership for the given sessions (plus everything already cached) + * and replace the snapshot. Sessions known to be locally owned are dropped. + */ +export function refreshElsewhereSessions( + candidates: ElsewhereCandidate[], + options: RefreshElsewhereOptions = {}, +): Promise { + const state = elsewhereState(); + if (state.refreshing) { + // The active pass snapshotted its own candidates, so these ids cannot make + // it. Queue them for the pass that follows instead of dropping them: the + // caller broadcasts the returned snapshot, and an answer that predates its + // own files would show the wrong owners until the next event. + for (const candidate of candidates) { + const previous = state.pending.get(candidate.id); + state.pending.set(candidate.id, { + id: candidate.id, + // Keep the newest knowledge per field: a later event without a path + // must not erase the file an earlier one resolved. + sessionFile: candidate.sessionFile ?? previous?.sessionFile, + mtimeMs: candidate.mtimeMs ?? previous?.mtimeMs, + }); + } + state.pendingOptions = mergeRefreshOptions(state.pendingOptions, options); + return state.refreshing.then(() => { + const pending = [...state.pending.values()]; + if (pending.length === 0) return getElsewhereSessions(); + const pendingOptions = state.pendingOptions ?? {}; + state.pending.clear(); + state.pendingOptions = null; + return refreshElsewhereSessions(pending, pendingOptions); + }); + } + state.refreshing = (async () => { + const now = options.now?.() ?? Date.now(); + // Per-call values win; the registered context covers callers without any + // (the self-tick). Read from the shared state, not a module-local binding: + // the tick can run in a different server bundle than the registration. + const context = state.ownershipContext; + const isLocal = options.isLocal ?? context?.isLocal; + const ownCrashed = options.ownCrashed ?? context?.ownCrashed; + const excludePids = options.excludePids ?? context?.excludePids?.(); + const byId = new Map(); + // The tail is only read for files written inside the activity window — + // that is the only signal a silent old file could contribute. + const stale = new Set(); + for (const candidate of candidates) { + if (!candidate.sessionFile) continue; + if (candidate.mtimeMs !== undefined && Number.isFinite(candidate.mtimeMs) && now - candidate.mtimeMs >= ELSEWHERE_ACTIVE_WINDOW_MS) { + stale.add(candidate.id); + } + byId.set(candidate.id, candidate); + } + for (const entry of state.entries.values()) { + if (!byId.has(entry.id)) byId.set(entry.id, { id: entry.id, sessionFile: entry.sessionFile }); + } + if (byId.size === 0) { + state.entries.clear(); + return []; + } + // One shared scan for the whole list: the scan itself is TTL-cached and + // single-flight, and the foreign instance lists are one directory read. + const scan = await listOmpProcesses(); + const foreignLists = readForeignRunningLists(); + // The scan decides which sessions need a closer look: it names the files a + // live foreign `omp` opened, so an idle owner outside the recent window is + // found by its own command line. Instance-list ids come from the same + // "someone else says it runs" source. + const ownerIds = sessionIdsNamedByProcesses(scan.processes, byId.values()); + for (const list of foreignLists) { + for (const id of list.ids) if (byId.has(id)) ownerIds.add(id); + } + const queue: ElsewhereCandidate[] = []; + const queued = new Set(); + const enqueue = (candidate: ElsewhereCandidate) => { + if (queued.has(candidate.id)) return; + queued.add(candidate.id); + queue.push(candidate); + }; + // Known owners first: an idle `omp --resume` between turns has no recent + // write, and a cached entry must never be starved by a burst of new files. + for (const entry of state.entries.values()) enqueue({ id: entry.id, sessionFile: entry.sessionFile }); + for (const id of ownerIds) enqueue(byId.get(id) ?? { id }); + // Everything else can only contribute the transcript signal, so a recent + // write is what makes it a candidate — and only that tier is capped. + let recent = 0; + for (const candidate of byId.values()) { + if (queued.has(candidate.id) || stale.has(candidate.id)) continue; + if (recent >= MAX_RECENT_CANDIDATES) break; + recent += 1; + enqueue(candidate); + } + for (const candidate of queue) { + if (isLocal?.(candidate.id)) { + state.entries.delete(candidate.id); + continue; + } + const detected = await detectSessionOwner(candidate.id, candidate.sessionFile, { + isLocal, + ownCrashed, + excludePids, + processes: scan.processes, + foreignLists, + // An owner-derived candidate with an old file is not read; its owner + // signal is enough. + tail: stale.has(candidate.id) ? null : undefined, + now: options.now, + }); + if (detected) { + state.entries.set(candidate.id, { id: candidate.id, sessionFile: candidate.sessionFile ?? "", state: detected }); + continue; + } + // A failed scan is not evidence of absence: keep a known process owner + // (and an instance-list one) until a scan actually answers again, or one + // timeout would erase a live owner for good. A transcript entry still + // ages out with its window. + const previous = state.entries.get(candidate.id); + if (!scan.ok && previous && previous.state.source !== "transcript") continue; + state.entries.delete(candidate.id); + } + return getElsewhereSessions(now); + })().finally(() => { + state.refreshing = null; + scheduleElsewhereTick(); + }); + return state.refreshing; +} + +/** Re-detect ownership for session ids whose files just changed. */ +export async function refreshElsewhereForSessionIds( + sessionIds: string[], + options: RefreshElsewhereOptions = {}, +): Promise { + const candidates: ElsewhereCandidate[] = []; + for (const id of sessionIds) { + const sessionFile = await resolveSessionPath(id).catch(() => null); + if (sessionFile) candidates.push({ id, sessionFile }); + } + if (candidates.length === 0) return getElsewhereSessions(); + return refreshElsewhereSessions(candidates, options); +} + +/** + * Register the broadcaster that must run when the snapshot changes on its own + * (an entry expiring, or a terminal `omp` exiting). rpc-manager registers + * `notifyRunningChange` on every broadcast, so the two modules stay free of an + * import cycle. + */ +export function setElsewhereChangeNotifier(notify: () => void): void { + elsewhereState().notifier = notify; +} + +function scheduleElsewhereTick(): void { + const state = elsewhereState(); + clearTimeout(state.timer); + state.timer = undefined; + if (state.entries.size === 0) return; + let at = Date.now() + ELSEWHERE_REFRESH_MS; + for (const entry of state.entries.values()) { + if (entry.state.source !== "transcript" || entry.state.lastActivityAt === undefined) continue; + at = Math.min(at, entry.state.lastActivityAt + ELSEWHERE_ACTIVE_WINDOW_MS); + } + const timer = setTimeout(() => { + state.timer = undefined; + // Re-check ownership, then broadcast whatever changed: a process that + // exited or a transcript that stopped growing disappears from the badge. + void refreshElsewhereSessions([...state.entries.values()].map((entry) => ({ + id: entry.id, + sessionFile: entry.sessionFile, + }))).then(() => { + state.notifier?.(); + }).catch(() => { + // A failed re-check (a throwing ownership callback, a scan that rejects + // outside its soft-failure path) must not become an unhandled rejection: + // Node ends the process on those. The previous snapshot stays, and the + // tick armed in `finally` retries it. + }); + }, Math.max(0, at - Date.now())); + timer.unref?.(); + state.timer = timer; +} + +/** Reset the snapshot (tests). */ +export function resetElsewhereSessions(): void { + const state = elsewhereState(); + state.entries.clear(); + clearTimeout(state.timer); + state.timer = undefined; + state.refreshing = null; + state.pending.clear(); + state.pendingOptions = null; +} diff --git a/lib/session-resume.ts b/lib/session-resume.ts index 157c93b7d..7b00267c9 100644 --- a/lib/session-resume.ts +++ b/lib/session-resume.ts @@ -111,6 +111,51 @@ function interruptedPath(): string { return resolve(getAgentDir(), `omp-web-interrupted-sessions-${process.pid}.json`); } +export interface ForeignRunningList { + /** The other omp-web instance that wrote the list. */ + pid: number; + ids: string[]; +} + +/** + * The per-instance running lists of OTHER live omp-web instances sharing this + * agent dir. Read-only: the caller must never rename or claim these — that is + * `readLeftover()`'s job for its own start, and claiming one here would drop + * another instance's resume list. A session listed here is being run by that + * instance right now. + */ +export function readForeignRunningLists(): ForeignRunningList[] { + const dir = getAgentDir(); + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return []; + } + const lists: ForeignRunningList[] = []; + for (const name of names) { + const match = LIST_NAME.exec(name); + // The unsuffixed list predates per-instance lists and has no owner pid. + if (!match?.[1]) continue; + const pid = Number(match[1]); + if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue; + const path = resolve(dir, name); + if (!ownedByLiveInstance(path, pid)) continue; + try { + const raw: unknown = JSON.parse(readFileSync(path, "utf8")); + const entries = isRecord(raw) && Array.isArray(raw.sessions) ? raw.sessions : []; + const ids: string[] = []; + for (const entry of entries) { + if (isRecord(entry) && typeof entry.id === "string" && isValidSessionId(entry.id)) ids.push(entry.id); + } + if (ids.length > 0) lists.push({ pid, ids }); + } catch { + // Unreadable mid-write: the next refresh sees the finished file. + } + } + return lists; +} + function writeInterrupted(sessions: InterruptibleSession[]): void { const path = interruptedPath(); try { diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5d966ed28..554f9df04 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -18,9 +18,14 @@ const contextRoute = await jiti.import("../app/api/sessions/[id]/context/route.t const importRoute = await jiti.import("../app/api/sessions/import/route.ts"); const stateRoute = await jiti.import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/route.ts"); +const newAgentRoute = await jiti.import("../app/api/agent/new/route.ts"); 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 +78,145 @@ 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, + // The state route always carries the ownership verdict (null = nobody else + // holds the session), so clients can act on it without an extra request. + elsewhere: null, 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"); +}); + +test("a timed-out preset on ensure_session destroys the child nobody can adopt", async (t) => { + // `ensure_session` only asks for a runtime, so a `session_slow` there can only + // be set_model/set_thinking_level timing out: no run was dispatched, the + // client (`ensureNewSession`) throws before it reads the returned id, and the + // child would sit in the registry until the watchdog reaped it. + const cwd = mkdtempSync(join(tmpdir(), "omp-web-new-session-")); + const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + const destroyed = []; + const wrapper = { + isAlive: () => true, + isRunning: () => false, + isEditingHistory: () => false, + advisorSpawned: false, + sessionId: "ensure-session", + sessionFile: "", + send: async (command) => { + if (command.type === "set_model") throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + return {}; + }, + destroyAndWait: async () => { destroyed.push(true); }, + }; + const previousSessions = globalThis.__ompSessions; + // The route starts every session under a fresh temp key it generates itself, + // so answer every key with this wrapper and let startRpcSession reuse it. + const registry = new Map(); + registry.get = () => wrapper; + registry.set = () => registry; + globalThis.__ompSessions = registry; + t.after(() => { + globalThis.__ompSessions = previousSessions; + rmSync(cwd, { recursive: true, force: true }); + }); + + const response = await newAgentRoute.POST(new Request("http://localhost/api/agent/new", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ cwd, type: "ensure_session", provider: "october", modelId: "gpt-6.1" }), + })); + const body = await response.json(); + + assert.equal(response.status, 400); + assert.equal(body.code, "session_slow"); + assert.equal(body.sessionId, undefined, "a destroyed child is not advertised as adoptable"); + assert.equal(destroyed.length, 1, "the preset-only child is destroyed instead of orphaned"); +}); + function writeSessionFile(dir, name, header, entries = []) { const filePath = join(dir, name); const lines = [JSON.stringify({ type: "session", version: 3, ...header })]; @@ -667,6 +807,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"; diff --git a/lib/session-tail.test.mjs b/lib/session-tail.test.mjs new file mode 100644 index 000000000..b71abb1ed --- /dev/null +++ b/lib/session-tail.test.mjs @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, truncateSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const { readSessionTailState } = await jiti.import("./session-owner.ts"); + +const dir = mkdtempSync(join(tmpdir(), "omp-web-session-tail-")); +test.after(() => rmSync(dir, { recursive: true, force: true })); + +let counter = 0; +function fileWith(lines) { + counter += 1; + const path = join(dir, `session-${counter}.jsonl`); + writeFileSync(path, lines.join("\n")); + return path; +} + +const userMessage = (text) => JSON.stringify({ type: "message", id: `u${counter}`, parentId: null, message: { role: "user", content: text } }); +const assistantText = () => JSON.stringify({ type: "message", id: `a${counter}`, parentId: null, message: { role: "assistant", content: [{ type: "text", text: "done" }] } }); +const assistantToolCall = () => JSON.stringify({ + type: "message", + id: `t${counter}`, + parentId: null, + message: { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "ls" } }] }, +}); +const toolResult = () => JSON.stringify({ + type: "message", + id: `r${counter}`, + parentId: null, + message: { role: "toolResult", toolCallId: "call-1", toolName: "bash", content: [{ type: "text", text: "ok" }] }, +}); +const liveToolStart = () => JSON.stringify({ + type: "custom", + customType: "tool_execution_start", + id: `e${counter}`, + parentId: null, + data: { toolCallId: "call-1", toolName: "bash" }, +}); +const sessionExit = () => JSON.stringify({ + type: "custom", + customType: "session_exit", + id: `x${counter}`, + parentId: null, + data: { reason: "dispose" }, +}); + +test("an empty session file is neither active nor closed", () => { + const state = readSessionTailState(fileWith([""])); + assert.ok(state); + assert.equal(state.hasTrailingExit, false); + assert.equal(state.looksActive, false); + assert.ok(state.mtimeMs > 0); +}); + +test("a missing file reads as unknown", () => { + assert.equal(readSessionTailState(join(dir, "does-not-exist.jsonl")), null); +}); + +test("an unfinished tool call or tool result reads as an active turn", () => { + assert.equal(readSessionTailState(fileWith([userMessage("go"), assistantToolCall()])).looksActive, true); + assert.equal(readSessionTailState(fileWith([userMessage("go"), assistantToolCall(), toolResult()])).looksActive, true); + // A running tool writes its own record and no result yet. + assert.equal(readSessionTailState(fileWith([userMessage("go"), liveToolStart()])).looksActive, true); +}); + +test("a finished turn (trailing assistant text) is not active", () => { + const state = readSessionTailState(fileWith([userMessage("go"), assistantToolCall(), toolResult(), assistantText()])); + assert.equal(state.looksActive, false); + assert.equal(state.hasTrailingExit, false); +}); + +test("a trailing session_exit means the writer closed the file", () => { + const state = readSessionTailState(fileWith([userMessage("go"), assistantText(), sessionExit()])); + assert.equal(state.hasTrailingExit, true); + assert.equal(state.looksActive, false); +}); + +test("a torn last line is skipped instead of hiding the real end", () => { + const path = fileWith([userMessage("go"), assistantText(), '{"type":"message","id":"torn"']); + const state = readSessionTailState(path); + assert.equal(state.hasTrailingExit, false); + assert.equal(state.looksActive, false, "the last complete record is finished text"); +}); + +test("a last line larger than the tail window does not throw", () => { + const huge = JSON.stringify({ + type: "message", + id: "huge", + parentId: null, + message: { role: "assistant", content: [{ type: "text", text: "x".repeat(70 * 1024) }] }, + }); + const path = fileWith([userMessage("go"), huge]); + const state = readSessionTailState(path); + assert.ok(state); + assert.equal(state.hasTrailingExit, false); +}); + +test("a truncated file still reports its mtime", () => { + const path = fileWith([userMessage("go"), assistantToolCall()]); + truncateSync(path, 10); + const state = readSessionTailState(path); + // The first 10 bytes are a partial record: no parseable message, no crash. + assert.ok(state); + assert.equal(state.looksActive, false); + assert.ok(state.mtimeMs > 0); +}); diff --git a/lib/types.ts b/lib/types.ts index bf269c130..4a57c310f 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -456,6 +456,31 @@ export interface SessionInfo { worktreeBranch?: string; } +/** + * Who holds a session that this omp-web instance does not run. omp ≥ 18.5 gives + * one process the write lease; a second writer silently forks the conversation + * into a copy. Reported by GET /api/sessions, the `running` event frame, and + * the per-session state routes (409/`elsewhere`). + */ +export interface SessionElsewhere { + /** Another omp-web instance, or a terminal/harness omp. */ + kind: "omp-web" | "terminal"; + /** How it was detected, strongest first. */ + source: "instance-list" | "process" | "transcript"; + /** Mid-turn right now. */ + running: boolean; + /** A writer is (or was, within the activity window) present. */ + active: boolean; + /** Last write to the session file, epoch ms — only when the server read the + * transcript tail; absent for an old file that only a live process explains. */ + lastActivityAt?: number; +} + +/** One entry of `elsewhereSessions` on the session list and running frames. */ +export interface ElsewhereSessionInfo extends SessionElsewhere { + id: string; +} + /** Metadata for a gzip-compressed session in OMP's archive tree. */ export interface ArchivedSessionInfo { key: string; diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index 114b7a42a..a9568cada 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -149,6 +149,32 @@ test("getWindowsExecutionEnv includes System32 and PowerShell paths in PATH on W } }); +test("getWindowsExecutionEnv never hands omp-web's secrets to a child", () => { + // The ownership scan spawns `ps`/PowerShell from a PATH-resolved location on + // some hosts; every spawned service child gets this env, so the login hash + // must never travel with it (issue #239). + const secrets = { + OMP_WEB_PASSWORD: "plain", + OMP_WEB_PASSWORD_HASH: "hash", + OMP_WEB_TRUSTED_HEADER_SECRET: "secret", + OMP_WEB_TRUSTED_HEADER_SHA256: "digest", + }; + const previous = {}; + for (const [name, value] of Object.entries(secrets)) { + previous[name] = process.env[name]; + process.env[name] = value; + } + try { + const env = getWindowsExecutionEnv(); + for (const name of Object.keys(secrets)) assert.equal(env[name], undefined, `${name} leaked to a child`); + } finally { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } +}); + test("isTrayProcessRunning caches status and refreshes on invalidateTrayRunningCache", async () => { invalidateTrayRunningCache(); const running1 = await isTrayProcessRunning(); diff --git a/lib/windows-service.ts b/lib/windows-service.ts index ec8d78301..648343b70 100644 --- a/lib/windows-service.ts +++ b/lib/windows-service.ts @@ -122,7 +122,10 @@ export function resolveTaskkillBin(): string { export function getWindowsExecutionEnv(): NodeJS.ProcessEnv { if (process.platform !== "win32") { - return process.env; + // Same rule as on Windows: a spawned service/scan child must never see + // omp-web's own secrets (issue #239) — `ps`, `tailscale` and friends would + // otherwise inherit the login hash through PATH-resolved binaries. + return createChildProcessEnvironment(); } const sysRoot = getSystemRoot(); const system32 = path.join(sysRoot, "System32");