From 7df876734350dbdd7efe33d09253dcb63c4c015d Mon Sep 17 00:00:00 2001 From: kahme247 <61059522+kahme247@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:28:01 +0000 Subject: [PATCH] =?UTF-8?q?fix(rpc):=20bug-hunt=20round=201=20=E2=80=94=20?= =?UTF-8?q?advisor=20gate,=20startup=20timeouts,=20internal=20waiters,=20s?= =?UTF-8?q?tale=20responses,=20orphaned=20mcp=20output,=20extension=20inje?= =?UTF-8?q?ction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Route advisor fast-path compares the effective advisor union (toggle OR workspace launch config), matching startRpcSession. - Startup bounds set_subagent_subscription and protocol negotiation with GET_STATE_TIMEOUT_MS so a wedged child cannot hang startup. - waitForTurnEnd uses internal listeners that do not count toward host-tool/host-URI routing or hasSubscribers(). - Unsolicited failed get_state responses are dropped instead of surfacing as spurious UI errors; prompt failures still surface. - Timed-out /mcp list output is swallowed until the next prompt boundary instead of leaking into chat. - Launch args reserve --extension/--hook/-e and strip their values at the spawn boundary so workspace configs cannot inject extension code into spawns. --- app/api/agent/[id]/route.ts | 9 +- lib/omp/rpc-process-runtime.test.mjs | 43 ++++++++++ lib/omp/rpc-process.ts | 9 +- lib/project-registry.test.mjs | 24 ++++++ lib/project-registry.ts | 36 +++++++- lib/rpc-manager.test.mjs | 124 ++++++++++++++++++++++++++- lib/rpc-manager.ts | 95 ++++++++++++++++++-- 7 files changed, 319 insertions(+), 21 deletions(-) diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 892d71293..ca786cb5f 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { readSessionHeader } from "@/lib/session-reader"; import { apiErrorResponse, resolveSessionPathOr404 } from "@/lib/api-utils"; -import { startRpcSession, getRpcSession, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager"; +import { startRpcSession, getRpcSession, launchConfigForCwd, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager"; 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"; @@ -69,7 +69,12 @@ export async function POST( const noSpawn = Object.hasOwn(NO_SPAWN_REPLIES, body.type); const liveOnly = LIVE_SESSION_ONLY.has(body.type); if (existing?.isAlive()) { - if (noSpawn || liveOnly || existing.advisorSpawned === advisor || existing.isRunning() || existing.isEditingHistory()) { + // Same effective-advisor union startRpcSession uses: a workspace + // whose launch config forces --advisor comes back advisorSpawned + // even with the per-chat toggle off, so comparing against the raw + // toggle would destroy+respawn the idle child on every command. + const effectiveAdvisor = advisor || launchConfigForCwd(existing.cwd)?.advisor === true; + if (noSpawn || liveOnly || existing.advisorSpawned === effectiveAdvisor || existing.isRunning() || existing.isEditingHistory()) { const result = await existing.send(body); return NextResponse.json({ success: true, data: result }); } diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 47c5be6ff..de7274748 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -222,3 +222,46 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { } }); } + +test("bug-hunt rpc-2: negotiate_protocol timeout fails startup instead of hanging", async () => { + const transport = makeTransport(); + // The child never answers negotiate_protocol. + const proc = startProcess(transport); + const ready = await proc.waitReady(); + // Race so the test fails (instead of hanging) if negotiation ever wedges. + const outcome = await Promise.race([ + proc.negotiateProtocol(ready, 50).then( + () => "ok", + (err) => `rejected:${err.name}:${err.command}`, + ), + new Promise((r) => setTimeout(() => r("hang"), 2000)), + ]); + assert.equal(outcome, "rejected:RpcCommandTimeoutError:negotiate_protocol"); + await proc.dispose(0); +}); + +test("bug-hunt rpc-4: async prompt failure after the ack still reaches frame listeners", async () => { + // Control for the stale-poll drop in the wrapper: prompt failures that + // reuse the original command id after its ack are intentional surfacing + // and must keep flowing. (Late responses for timed-out ids keep the + // existing RpcProcess contract: success responses reach listeners.) + const transport = makeTransport(); + transport.onCommand = (command) => { + if (command.type === "prompt") { + transport.send({ type: "response", id: command.id, command: "prompt", success: true, data: { accepted: true } }); + } + }; + const proc = startProcess(transport); + await proc.waitReady(); + const frames = []; + proc.onFrame((frame) => frames.push(frame)); + await proc.sendCommand({ type: "prompt", message: "hi" }); + while (transport.commands.length < 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + const promptCommand = transport.commands.find((c) => c.type === "prompt"); + transport.send({ type: "response", id: promptCommand.id, command: "prompt", success: false, error: "async boom" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.ok(frames.some((f) => f.type === "response" && f.command === "prompt" && f.success === false)); + await proc.dispose(0); +}); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 5c4c545bf..24201fa1f 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -227,11 +227,14 @@ export class RpcProcess { return Promise.race([this.readyPromise, timeout]); } - /** Enables bounded protocol-v2 framing when the ready frame advertises it. */ - async negotiateProtocol(ready: RpcFrame): Promise { + /** Enables bounded protocol-v2 framing when the ready frame advertises it. + * Pass a timeout for startup callers: a child that accepts the frame but + * never answers must fail startup instead of hanging it forever. Callers + * without a timeout keep the previous unbounded behavior. */ + async negotiateProtocol(ready: RpcFrame, timeoutMs?: number): Promise { const supported = Array.isArray(ready.supportedProtocolVersions) ? ready.supportedProtocolVersions : []; if (!supported.includes(2)) return this.protocolVersion; - const response = await this.sendCommand<{ protocolVersion?: unknown }>({ type: "negotiate_protocol", protocolVersion: 2 }); + const response = await this.sendCommand<{ protocolVersion?: unknown }>({ type: "negotiate_protocol", protocolVersion: 2 }, timeoutMs); if (response?.protocolVersion !== 2) throw new Error("OMP rejected RPC protocol v2 negotiation"); this.protocolVersion = 2; return this.protocolVersion; diff --git a/lib/project-registry.test.mjs b/lib/project-registry.test.mjs index 6db188b74..7f75f25ea 100644 --- a/lib/project-registry.test.mjs +++ b/lib/project-registry.test.mjs @@ -15,6 +15,7 @@ const { mergeProjects, parseProjectRegistry, saveProjectRegistry, + stripReservedLaunchArgs, upsertProject, updateProjectsPresentation, validateProjectPath, @@ -57,6 +58,14 @@ test("strips reserved and flag-smuggled launch args from disk configs", () => { assert.equal(isReservedLaunchArg("--mode=json"), true); assert.equal(isReservedLaunchArg("--resume=/tmp/x.jsonl"), true); assert.equal(isReservedLaunchArg("rpc-ui"), true); + // Extension/hook loaders are reserved too: omp loads them (multiple + // allowed, headless in rpc-ui), and rpc-manager appends its own + // session-edit extension after these args. + assert.equal(isReservedLaunchArg("--extension"), true); + assert.equal(isReservedLaunchArg("--extension=/evil/ext.mjs"), true); + assert.equal(isReservedLaunchArg("--hook"), true); + assert.equal(isReservedLaunchArg("--hook=/evil/hook.mjs"), true); + assert.equal(isReservedLaunchArg("-e"), true); assert.equal(isReservedLaunchArg("--verbose"), false); const registry = parseProjectRegistry(JSON.stringify({ version: 1, projects: [{ path: "/one", addedAt: "2026-01-01T00:00:00.000Z", hidden: false, @@ -65,6 +74,21 @@ test("strips reserved and flag-smuggled launch args from disk configs", () => { // Dash-leading profile and reserved args are dropped; advisor survives. assert.deepEqual(registry.projects[0].launchConfig, { profile: undefined, advisor: true, extraArgs: ["--verbose"] }); }); + +test("strips extension/hook args and their values from disk configs", () => { + // A hand-edited registry (bypassing the API's rejection) must not smuggle + // an extension path into spawns: the flag AND its value token are dropped, + // so no stray positional survives to omp's argv. + assert.deepEqual( + stripReservedLaunchArgs(["--extension", "/evil/ext.mjs", "--verbose", "--hook=/evil/hook.mjs", "-e", "/evil/e.mjs", "--cwd", "/evil"]), + ["--verbose"], + ); + const registry = parseProjectRegistry(JSON.stringify({ version: 1, projects: [{ + path: "/one", addedAt: "2026-01-01T00:00:00.000Z", hidden: false, + launchConfig: { extraArgs: ["--extension", "/evil/ext.mjs", "--verbose"] }, + }] })); + assert.deepEqual(registry.projects[0].launchConfig, { profile: undefined, advisor: undefined, extraArgs: ["--verbose"] }); +}); test("re-adding a workspace without config preserves its launch config", () => { const seeded = parseProjectRegistry(JSON.stringify({ version: 1, projects: [{ path: P("/one"), addedAt: "2026-01-01T00:00:00.000Z", hidden: true, diff --git a/lib/project-registry.ts b/lib/project-registry.ts index 2aa763ece..985792a11 100644 --- a/lib/project-registry.ts +++ b/lib/project-registry.ts @@ -63,13 +63,41 @@ function canonicalProjectPath(value: string): string { /** Launch args the web UI manages itself; a workspace config must never carry * them (bare or `--flag=value`), or a stored config could hijack the session - * boundary (`--cwd`/`--resume`) or the rpc-ui mode. */ -const RESERVED_LAUNCH_ARGS: Record = { "--mode": true, "rpc-ui": true, "--cwd": true, "--resume": true }; -const RESERVED_LAUNCH_ARG_PREFIXES = ["--mode=", "--cwd=", "--resume="]; + * boundary (`--cwd`/`--resume`) or the rpc-ui mode. `--extension`/`--hook` + * (and `-e`) are reserved too: omp loads extension/hook files (multiple + * allowed, headless in rpc-ui mode), and rpc-manager appends its own + * session-edit extension after these args — a config-carried one would + * load arbitrary extension code into every spawn for that workspace. */ +const RESERVED_LAUNCH_ARGS: Record = { + "--mode": true, "rpc-ui": true, "--cwd": true, "--resume": true, + "--extension": true, "--hook": true, "-e": true, +}; +const RESERVED_LAUNCH_ARG_PREFIXES = ["--mode=", "--cwd=", "--resume=", "--extension=", "--hook=", "-e="]; export function isReservedLaunchArg(arg: string): boolean { return RESERVED_LAUNCH_ARGS[arg] === true || RESERVED_LAUNCH_ARG_PREFIXES.some((prefix) => arg.startsWith(prefix)); } +/** Reserved flags that take a separate value token (`--cwd `). */ +const RESERVED_VALUE_FLAGS = new Set(["--mode", "--cwd", "--resume", "--extension", "--hook", "-e"]); + +/** Drop reserved args from a launch-arg list, including the value token + * following a bare reserved value-flag — otherwise the value survives as a + * stray positional (e.g. a config `--extension` path left behind after its + * flag was filtered). `--flag=value` forms are already caught by + * isReservedLaunchArg. */ +export function stripReservedLaunchArgs(args: string[]): string[] { + const out: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (!isReservedLaunchArg(arg)) { + out.push(arg); + continue; + } + if (RESERVED_VALUE_FLAGS.has(arg) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++; + } + return out; +} + /** Parse the on-disk registry's launch config; invalid fields are safely ignored. */ function parseLaunchConfig(item: Record): ProjectLaunchConfig | undefined { const raw = item.launchConfig; @@ -78,7 +106,7 @@ function parseLaunchConfig(item: Record): ProjectLaunchConfig | const profile = typeof value.profile === "string" && value.profile.trim() && !value.profile.trim().startsWith("-") ? value.profile.trim() : undefined; const advisor = value.advisor === true ? true : undefined; const extraArgs = Array.isArray(value.extraArgs) - ? value.extraArgs.filter((arg): arg is string => typeof arg === "string" && arg.length > 0 && arg.length <= 256 && !isReservedLaunchArg(arg)).slice(0, 32) + ? stripReservedLaunchArgs(value.extraArgs.filter((arg): arg is string => typeof arg === "string" && arg.length > 0 && arg.length <= 256)).slice(0, 32) : undefined; if (!profile && advisor === undefined && (!extraArgs || extraArgs.length === 0)) return undefined; return { profile, advisor, extraArgs }; diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index a153e829d..95ff6ca0a 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -21,7 +21,7 @@ test.after(() => { }); const runtimeJiti = createJiti(import.meta.url); -const { AgentSessionWrapper: SnapshotWrapper, subscribeHostToolCalls } = await runtimeJiti.import("./rpc-manager.ts"); +const { AgentSessionWrapper: SnapshotWrapper, buildSessionSpawnArgs, subscribeHostToolCalls } = await runtimeJiti.import("./rpc-manager.ts"); function snapshotSession(t, sendCommand = async () => ({}), Wrapper = SnapshotWrapper, sessionId = "", disconnectDestroyMs) { const frameListeners = new Set(); @@ -85,8 +85,10 @@ test("rpc-manager spawns omp via RpcProcess and has no SDK imports", async () => test("session startup negotiates RPC v2 when the installed OMP advertises it", async () => { const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); - assert.match(source, /await this\.proc\.negotiateProtocol\(ready\)/); - assert.match(source, /await proc\.negotiateProtocol\(ready\)/); + // Negotiation is bounded at startup/restart so a wedged child fails + // startup instead of hanging it forever (see the startup-timeout test). + assert.match(source, /await this\.proc\.negotiateProtocol\(ready, GET_STATE_TIMEOUT_MS\)/); + assert.match(source, /await proc\.negotiateProtocol\(ready, GET_STATE_TIMEOUT_MS\)/); }); test("registered host tools route to listeners; unknown ones are rejected", async () => { @@ -882,6 +884,16 @@ test("replace gate compares the union of toggle and workspace advisor", async () assert.match(source, /existing\.advisorSpawned === effectiveAdvisor/); }); +test("agent route fast-path gate compares the effective advisor union", async () => { + const source = await readFile(new URL("../app/api/agent/[id]/route.ts", import.meta.url), "utf8"); + // The route used to compare the live child's flag against the raw query + // toggle, so a workspace-advisor session with the per-chat toggle off + // was destroyed and respawned (with --advisor again) on every idle + // command. It must use the same union startRpcSession uses. + assert.match(source, /const effectiveAdvisor = advisor \|\| launchConfigForCwd\(existing\.cwd\)\?\.advisor === true;/); + assert.match(source, /existing\.advisorSpawned === effectiveAdvisor/); +}); + test("fresh spawns force a new session when omp resumes the cwd's latest session", async () => { const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); // startRpcSession: a bare spawn (no --resume) must never let omp's startup @@ -2659,3 +2671,109 @@ test("waitForTurnEnd resolves on terminal agent_end and rejects on timeout (#275 emit({ type: "prompt_result" }); await promptDone; }); + +// Bug-hunt round 1 (RPC) regression tests. The fake proc models the +// RpcProcess contract: sendCommand(cmd, timeoutMs) rejects after timeoutMs +// when the child never answers, and waitReady/negotiateProtocol resolve. +function huntFakeProc(sendCommand) { + const listeners = new Set(); + return { + isAlive: true, + onFrame(l) { listeners.add(l); return () => listeners.delete(l); }, + sendCommand, + sendFrame() {}, + dispose: async () => {}, + waitReady: async () => ({ type: "ready", supportedProtocolVersions: [] }), + negotiateProtocol: async () => 1, + _emit(frame) { for (const l of [...listeners]) l(frame); }, + }; +} + +function huntWrapper(t, sendCommand, sessionId = "hunt") { + const proc = huntFakeProc(sendCommand); + const wrapper = new SnapshotWrapper(proc, process.cwd(), null, false, sessionId, 0); + wrapper.start(); + t.after(() => wrapper.destroyAndWait()); + return { wrapper, proc }; +} + +test("bug-hunt rpc-2: startup degrades when set_subagent_subscription never answers", async (t) => { + const calls = []; + const { wrapper } = huntWrapper(t, (cmd, timeoutMs) => { + calls.push(cmd.type); + if (cmd.type === "set_subagent_subscription") { + // Models the RpcProcess contract faithfully: with a timeout the + // wedged child rejects after it; without one (the pre-fix call) the + // send never settles, so startup would hang forever. + if (timeoutMs === undefined) return new Promise(() => {}); + return new Promise((_, reject) => setTimeout(() => reject(new Error("wedged child")), timeoutMs)); + } + if (cmd.type === "get_state") return Promise.resolve({ sessionId: "hunt", sessionFile: "" }); + return Promise.resolve({}); + }); + // Race so the test fails (instead of hanging) if startup ever wedges. + const outcome = await Promise.race([ + wrapper.waitUntilReady().then(() => "ready"), + new Promise((r) => setTimeout(() => r("hang"), 8000)), + ]); + assert.equal(outcome, "ready"); + assert.ok(calls.includes("get_state"), "startup must proceed past the wedged subscription"); +}); + +test("bug-hunt rpc-4: late failed get_state response does not surface as a UI error", async (t) => { + const { wrapper, emit } = snapshotSession(t, undefined, SnapshotWrapper, "stale-response"); + const seen = []; + const detach = wrapper.onEvent((e) => seen.push(e)); + t.after(detach); + emit({ type: "response", id: "w99", command: "get_state", success: false, error: "stale boom" }); + assert.equal(seen.filter((e) => e.type === "error").length, 0, "stale poll failure must not toast"); + // Other unsolicited failures still surface. + emit({ type: "response", id: "w98", command: "rename", success: false, error: "rename boom" }); + assert.equal(seen.filter((e) => e.type === "error").length, 1); +}); + +test("bug-hunt rpc-3: turn-end waiter does not hijack host-tool routing", async (t) => { + const { wrapper, proc } = huntWrapper(t, (cmd) => { + if (cmd.type === "get_state") return Promise.resolve({ sessionId: "hunt", sessionFile: "" }); + return Promise.resolve({}); + }); + await wrapper.waitUntilReady(); + await wrapper.send({ type: "set_host_tools", tools: [{ name: "open_url" }] }); + const crossCalls = []; + const leave = subscribeHostToolCalls((call) => crossCalls.push(call)); + t.after(leave); + // Server-side waiter (agent-tool deliver with wait=true) attaches a + // listener, although no UI tab watches this session. + const waiter = wrapper.waitForTurnEnd(500); + waiter.catch(() => {}); + proc._emit({ type: "host_tool_call", id: "tool-1", toolName: "open_url", arguments: { url: "https://x.test" } }); + await new Promise((r) => setTimeout(r, 100)); + assert.equal(crossCalls.length, 1, "call must route cross-session, not sit as 'own' for the waiter"); + await waiter.catch(() => {}); +}); + +test("bug-hunt rpc-x: launch-config extension args never reach spawn argv", async () => { + const args = buildSessionSpawnArgs("/tmp/session.jsonl", undefined, false, { + extraArgs: ["--extension", "/evil/ext.mjs", "--verbose", "--hook=/evil/hook.mjs"], + }); + assert.deepEqual(args, ["--resume", "/tmp/session.jsonl", "--verbose"]); + assert.ok(!args.some((arg) => arg.includes("/evil/"))); +}); + +test("bug-hunt rpc-5: timed-out /mcp list output does not leak, and later output flows again", async (t) => { + const { wrapper, proc } = huntWrapper(t, (cmd) => { + if (cmd.type === "get_state") return Promise.resolve({ sessionId: "hunt", sessionFile: "" }); + return Promise.resolve({}); + }); + await wrapper.waitUntilReady(); + const seen = []; + const detach = wrapper.onEvent((e) => seen.push(e)); + t.after(detach); + await assert.rejects(wrapper.getMcpList(), /Timed out while loading MCP servers/); + proc._emit({ type: "command_output", text: "server-a enabled\nserver-b disabled" }); + assert.equal(seen.filter((e) => e.type === "command_output").length, 0, "orphaned /mcp output must not leak into chat"); + // The next prompt boundary clears the orphan flag. + proc._emit({ type: "agent_start" }); + proc._emit({ type: "command_output", text: "later output" }); + assert.equal(seen.filter((e) => e.type === "command_output").length, 1); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8e23cee8..12f9f7166 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -35,7 +35,7 @@ import { isRecord } from "./type-guards"; import { BLOCKING_UI_METHODS, createNotificationDetector } from "./notification-events"; import { publishNotification } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; -import { isReservedLaunchArg, loadProjectRegistry } from "./project-registry"; +import { loadProjectRegistry, stripReservedLaunchArgs } from "./project-registry"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, @@ -256,7 +256,7 @@ export function buildSessionSpawnArgs(sessionFile: string, toolNames?: string[], // args and dash-leading profiles at the spawn boundary even though the // API validates them on write. if (launchConfig?.profile && !launchConfig.profile.startsWith("-")) args.push("--profile", launchConfig.profile); - if (launchConfig?.extraArgs) args.push(...launchConfig.extraArgs.filter((arg) => !isReservedLaunchArg(arg))); + if (launchConfig?.extraArgs) args.push(...stripReservedLaunchArgs(launchConfig.extraArgs)); return args; } @@ -329,6 +329,12 @@ interface IdentityChangeOptions { export class AgentSessionWrapper { private listeners: EventListener[] = []; + /** Server-side waiters (waitForTurnEnd and future internal subscribers). + * They receive events through emit() but are NOT UI listeners: they must + * not count toward listeners.length in host-tool/host-URI routing, + * hasSubscribers(), or the last-listener detach side effects, or a + * server-side waiter would hijack routing for a session no tab watches. */ + private internalListeners: EventListener[] = []; private pendingUiRequests = new Map(); private uiExpiryTimers = new Map>(); private extensionStatuses = new Map(); @@ -380,6 +386,12 @@ export class AgentSessionWrapper { * concurrent callers can never both enter (the waiter/promptRunning * bookkeeping alone is not an atomic gate). */ private mcpListInFlight = false; + /** The /mcp list waiter timed out, but the child may still deliver the + * command's output later. While set, command_output frames are swallowed + * instead of leaking into the chat stream; the next prompt boundary + * (agent_start / agent_end / prompt_result / prompt_error, or a fresh + * runMcpCommand) clears it. */ + private mcpListOutputDiscarded = false; private _alive = true; /** Host tools the web UI registered via set_host_tools (agent-callable). */ private hostToolNames: Set = new Set(); @@ -563,11 +575,13 @@ export class AgentSessionWrapper { this.handshaking = true; try { const ready = await this.proc.waitReady(READY_TIMEOUT_MS); - await this.proc.negotiateProtocol(ready); + await this.proc.negotiateProtocol(ready, GET_STATE_TIMEOUT_MS); // 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(() => {}); + // Bounded like set_ask_dialog below so a child that never answers + // cannot stall startup (and hold the start lock) forever. + await this.proc.sendCommand({ 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. @@ -804,6 +818,11 @@ export class AgentSessionWrapper { notifyRunningChange(); return; } + // The /mcp waiter timed out, but the child may still deliver the + // command's output later. Swallow it instead of leaking a Settings + // command's output into the chat stream; the flag clears at the + // next prompt boundary (see emit()). + if (this.mcpListOutputDiscarded) return; // The output of a background `/rename` (see autoTitle) is not chat content. if (Date.now() < this.quietRenameUntil && typeof event.text === "string" && RENAME_OUTPUT_RE.test(event.text)) { this.quietRenameUntil = 0; @@ -886,6 +905,16 @@ export class AgentSessionWrapper { // versions omit `command` on that second response, so the active run // is also a terminal-failure signal. Otherwise this frame would be // ignored and the UI would stop with no explanation. + // Exception: a failed response for a routine poll like get_state + // that reaches here was never awaited — an awaited failure is + // delivered to its caller by RpcProcess and never reaches frame + // listeners. An unsolicited poll failure is therefore stale by + // construction (a poll that timed out, then retried fine), so + // emitting it would toast an error for a command that succeeded. + // Other commands still surface here (including async prompt + // failures), and late successful responses still reach listeners + // per the RpcProcess contract — only this poll failure is dropped. + if (event.success === false && event.command === "get_state") return; if (event.success === false) { const promptFailure = event.command === "prompt" || @@ -1211,6 +1240,17 @@ export class AgentSessionWrapper { if (typeof event.toolCallId === "string") this.liveToolEvents.delete(event.toolCallId); break; } + // A discarded /mcp list output is swallowed in handleFrame, but the flag + // itself clears here, at the next prompt boundary, so a later genuine + // command_output is not swallowed with it. + if ( + event.type === "agent_start" || + event.type === "agent_end" || + event.type === "prompt_result" || + event.type === "prompt_error" + ) { + this.mcpListOutputDiscarded = false; + } event.web = { streamId: this.streamId, sequence: ++this.streamSequence }; for (const l of this.listeners) { try { @@ -1221,6 +1261,14 @@ export class AgentSessionWrapper { // notifyRunningChange apply to their listener sets. } } + for (const l of this.internalListeners) { + try { + l(event as AgentEvent); + } catch { + // Same isolation as UI listeners: a throwing waiter must not starve + // the remaining subscribers. + } + } } private sessionFileSignalTimer: NodeJS.Timeout | null = null; @@ -1289,6 +1337,20 @@ export class AgentSessionWrapper { this.idleTimer.unref?.(); } + /** Server-side event subscription (waitForTurnEnd and future internal + * waiters). Internal listeners receive every emitted event but are not + * UI subscribers: attaching one must not route host tools/URIs to this + * session, must not count in hasSubscribers(), must not replay pending + * UI dialogs, and detaching one must not reject pending host tools or + * arm the disconnect reap clock. */ + onInternalEvent(listener: EventListener): () => void { + this.internalListeners.push(listener); + return () => { + const i = this.internalListeners.indexOf(listener); + if (i !== -1) this.internalListeners.splice(i, 1); + }; + } + onEvent(listener: EventListener): () => void { this.listeners.push(listener); this.noteActivity(); @@ -1337,7 +1399,10 @@ export class AgentSessionWrapper { let endsSeen = 0; const timer = setTimeout(() => finish(new Error("Timed out waiting for the target session's response.")), timeoutMs); timer.unref?.(); - const detach = this.onEvent((event) => { + // Internal listener, not a UI subscription: a waiter must not make + // host-tool routing treat this session as tab-attached (see + // onInternalEvent). + const detach = this.onInternalEvent((event) => { if (event.type === "agent_end" && event.isTerminal === false) return; if (event.type === "agent_end" || event.type === "prompt_result") { endsSeen += 1; @@ -1426,6 +1491,9 @@ export class AgentSessionWrapper { // would steal the waiter so the first hangs to timeout (or receives the // other's output). This flag is checked+set before any await. this.mcpListInFlight = true; + // A fresh waiter owns the next command_output; a previous timeout's + // orphan flag must not swallow it. + this.mcpListOutputDiscarded = false; this.historyMutationPendingCount += 1; this.promptRunning = true; @@ -1448,6 +1516,10 @@ export class AgentSessionWrapper { waiter.timer = setTimeout(() => { if (this.mcpListWaiter !== waiter) return; this.mcpListWaiter = null; + // The child may still deliver this command's output later; mark it + // orphaned so handleFrame swallows it instead of leaking it into + // the chat stream (cleared at the next prompt boundary). + this.mcpListOutputDiscarded = true; rejectOutput(new WebRpcError("Timed out while loading MCP servers", "mcp_list_timeout")); }, MCP_LIST_TIMEOUT_MS); // Don't pin the event loop if the caller never awaits (route aborted): the @@ -1745,10 +1817,13 @@ export class AgentSessionWrapper { this.unsubscribeFrames = proc.onFrame((frame) => this.handleFrame(frame)); try { const ready = await proc.waitReady(READY_TIMEOUT_MS); - await proc.negotiateProtocol(ready); + await proc.negotiateProtocol(ready, GET_STATE_TIMEOUT_MS); // 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(() => {}); + // Bounded like the startup handshake so a wedged child cannot leave + // restarting === true forever (later commands would all fail with + // session_restarting). + 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); @@ -2428,8 +2503,10 @@ export async function resumeInterruptedSessions(): Promise { })); } -/** Look up the workspace-registered launch config; unregistered projects attach none. */ -function launchConfigForCwd(cwd: string): ProjectLaunchConfig | undefined { +/** Look up the workspace-registered launch config; unregistered projects attach none. + * Exported for the agent route's fast-path advisor gate, which must compare + * against the same effective advisor value startRpcSession uses. */ +export function launchConfigForCwd(cwd: string): ProjectLaunchConfig | undefined { let canonical = cwd; try { canonical = realpathSync(cwd); } catch {} const key = comparableProjectPath(canonical);