diff --git a/lib/hosts/local-host-profile.test.mjs b/lib/hosts/local-host-profile.test.mjs index e1d3417bf..8342c91aa 100644 --- a/lib/hosts/local-host-profile.test.mjs +++ b/lib/hosts/local-host-profile.test.mjs @@ -34,6 +34,12 @@ test("the owning host refuses legacy configuration before starting omp", async ( [{ extraArgs: ["--resume=/tmp/other"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["--mode", "rpc-ui"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["rpc-ui"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--extension", "/evil/ext.mjs"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--extension=/evil/ext.mjs"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--hook", "/evil/hook.mjs"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["-e", "/evil/e.mjs"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--plugin-dir", "/evil/plugins"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--plugin-dir=/evil/plugins"] }, "stored_reserved_launch_arg"], ]) { writeFileSync(join(agentDir, "projects.json"), JSON.stringify({ version: 1, projects: [{ path: cwd, addedAt: "2026-01-01", hidden: false, launchConfig }] })); await assert.rejects(localHost.spawnRpc({ cwd, recordedCwd: cwd, sessionFile: "", advisor: false }), (error) => { diff --git a/lib/project-registry.test.mjs b/lib/project-registry.test.mjs index 4bee1b7e3..194c2a136 100644 --- a/lib/project-registry.test.mjs +++ b/lib/project-registry.test.mjs @@ -59,6 +59,16 @@ test("recognizes reserved launch arguments without filtering stored configuratio assert.equal(isReservedLaunchArg("--profile"), true); assert.equal(isReservedLaunchArg("--profile=nova insight"), true); assert.equal(isReservedLaunchArg("--profilex"), false); + // Extension/hook loaders are reserved too: omp loads them, and the daemon + // 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); + // --plugin-dir adds a directory to extension discovery. + assert.equal(isReservedLaunchArg("--plugin-dir"), true); + assert.equal(isReservedLaunchArg("--plugin-dir=/evil/plugins"), true); const config = { profile: "--evil", advisor: true, extraArgs: ["--verbose", "--cwd", "/evil", "--profile", "work", "--profile=work"] }; const registry = parseProjectRegistry(JSON.stringify({ projects: [{ path: "/one", launchConfig: config }] })); assert.deepEqual(registry.projects[0].launchConfig, config); diff --git a/lib/project-registry.ts b/lib/project-registry.ts index 7a850345d..e58142856 100644 --- a/lib/project-registry.ts +++ b/lib/project-registry.ts @@ -87,9 +87,14 @@ function canonicalProjectPath(value: string): string { * them (bare or `--flag=value`), or a stored config could hijack the session * boundary (`--cwd`/`--resume`/`--profile`) or the rpc-ui mode. `--profile` * is reserved too: it would bypass the validated `profile` field and could - * hand omp a name it rejects, failing every session in the workspace. */ -const RESERVED_LAUNCH_ARGS: Record = { "--mode": true, "rpc-ui": true, "--cwd": true, "--resume": true, "--profile": true }; -const RESERVED_LAUNCH_ARG_PREFIXES = ["--mode=", "--cwd=", "--resume=", "--profile="]; + * hand omp a name it rejects, failing every session in the workspace. + * `--extension`/`--hook` (and `-e`) are reserved too: omp loads those files + * (multiple allowed, headless in rpc-ui mode), and the daemon appends its own + * session-edit extension after these args — a config-carried one would load + * arbitrary extension code into every spawn for that workspace. `--plugin-dir` + * is reserved for the same reason: it adds a directory to extension discovery. */ +const RESERVED_LAUNCH_ARGS: Record = { "--mode": true, "rpc-ui": true, "--cwd": true, "--resume": true, "--profile": true, "--extension": true, "--hook": true, "-e": true, "--plugin-dir": true }; +const RESERVED_LAUNCH_ARG_PREFIXES = ["--mode=", "--cwd=", "--resume=", "--profile=", "--extension=", "--hook=", "-e=", "--plugin-dir="]; export function isReservedLaunchArg(arg: string): boolean { return RESERVED_LAUNCH_ARGS[arg] === true || RESERVED_LAUNCH_ARG_PREFIXES.some((prefix) => arg.startsWith(prefix)); } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c822eff43..025faed69 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1213,6 +1213,77 @@ test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", ); }); +test("mcp list output timeout keeps a retry blocked until the orphaned output drains", async (t) => { + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + let frameListener = null; + const fakeProc = { + isAlive: true, + onFrame: (listener) => { frameListener = listener; return () => { frameListener = null; }; }, + sendCommand: () => Promise.resolve({}), + sendFrame: () => {}, + dispose: async () => {}, + }; + + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + const seen = []; + const detach = wrapper.onEvent((event) => seen.push(event)); + t.after(detach); + + const first = wrapper.getMcpList(); + await Promise.resolve(); + t.mock.timers.tick(15000); + await assert.rejects(first, { code: "mcp_list_timeout" }); + + // A retry must not clear the orphan state and receive the earlier + // command's late output as its own result. + await assert.rejects(wrapper.getMcpList(), { code: "mcp_list_loading" }); + + // The orphaned output arrives: swallowed, never reaching chat listeners... + frameListener({ type: "command_output", text: "server-a enabled\nserver-b disabled" }); + assert.equal(seen.filter((event) => event.type === "command_output").length, 0); + + // ...and the drain unblocks a retry, whose own output resolves it. + const second = wrapper.getMcpList(); + await Promise.resolve(); + frameListener({ type: "command_output", text: "server-a enabled" }); + assert.equal(await second, "server-a enabled"); +}); + +test("mcp list output timeout clears at the next prompt boundary so a retry proceeds", async (t) => { + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + let frameListener = null; + const fakeProc = { + isAlive: true, + onFrame: (listener) => { frameListener = listener; return () => { frameListener = null; }; }, + sendCommand: () => Promise.resolve({}), + sendFrame: () => {}, + dispose: async () => {}, + }; + + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + + const first = wrapper.getMcpList(); + await Promise.resolve(); + t.mock.timers.tick(15000); + await assert.rejects(first, { code: "mcp_list_timeout" }); + + // The orphan never arrives, but the child moves on to a user prompt: in + // stream order any output it still owed precedes this boundary, so the + // suppression lifts and a retry is no longer blocked. + frameListener({ type: "agent_start" }); + frameListener({ type: "agent_end", isTerminal: true }); + const second = wrapper.getMcpList(); + await Promise.resolve(); + frameListener({ type: "command_output", text: "server-a enabled" }); + assert.equal(await second, "server-a enabled"); +}); + test("live snapshots restore quiet partial messages and tools, with ordered event metadata", async (t) => { const { wrapper, emit } = snapshotSession(t); const events = []; diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a8f562699..84b492fa0 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -608,6 +608,15 @@ export class AgentSessionWrapper { * concurrent callers can never both enter (the waiter/promptRunning * bookkeeping alone is not an atomic gate). */ private mcpListInFlight = false; + /** A /mcp command whose output wait timed out, but whose child may still + * deliver that command's output later. While set, command_output frames are + * swallowed instead of leaking into the chat stream, and a retry of the MCP + * command is refused (see runMcpCommand): the suppression belongs to the + * timed-out command, so a retry must not clear it and receive the earlier + * command's late output as its own. It clears when the orphaned output + * arrives (handleFrame) or at the next prompt boundary (emit), which in + * stream order follows any output the child still owes for that command. */ + private mcpListOutputDiscarded = false; private _alive = true; /** Host tools the web UI registered via set_host_tools (agent-callable). */ private hostToolNames: Set = new Set(); @@ -1364,6 +1373,16 @@ export class AgentSessionWrapper { notifyRunningChange(); return; } + // The output of a timed-out /mcp command, arriving late. Swallow it + // (and consume the suppression: one command_output frame is the whole + // output, matching the waiter contract) instead of leaking a Settings + // command's output into the chat stream. A retry cannot be running + // while this flag is set, so this frame is the orphan's, not the + // retry's — a fresh runMcpCommand never clears the flag. + if (this.mcpListOutputDiscarded) { + this.mcpListOutputDiscarded = false; + 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; @@ -1861,6 +1880,21 @@ export class AgentSessionWrapper { } private emit(nativeEvent: UnsequencedAgentEvent): void { + // A discarded /mcp list output is swallowed in handleFrame, but the flag + // itself also clears here, at the next prompt boundary: in stream order + // the child emits any output it still owes for the timed-out command + // before starting another prompt, so past this boundary the flag can only + // be stale — and leaving it set would swallow a later genuine + // command_output. This is what unblocks a retry when the orphan never + // arrives at all. + if ( + nativeEvent.type === "agent_start" || + nativeEvent.type === "agent_end" || + nativeEvent.type === "prompt_result" || + nativeEvent.type === "prompt_error" + ) { + this.mcpListOutputDiscarded = false; + } // Tool-result images go out (and into the replay snapshot) as media URLs: // big screenshots must never sit in the browser's chat state as base64. const event = eventWithToolResultImageUrls(nativeEvent); @@ -2232,7 +2266,7 @@ export class AgentSessionWrapper { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); if (!this.isAlive()) throw new Error("Session is no longer running"); if (this.isRunning() || this.historyEditInFlight || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0 || this.pendingHostUris.size > 0) throw new WebRpcError("Wait for the current operation to finish", "session_busy"); - if (this.mcpListWaiter || this.mcpListInFlight) throw new WebRpcError("MCP list is already loading", "mcp_list_loading"); + if (this.mcpListWaiter || this.mcpListInFlight || this.mcpListOutputDiscarded) throw new WebRpcError("MCP list is already loading", "mcp_list_loading"); // Dedicated synchronous mutex: promptRunning alone is not atomic — two // concurrent callers could both pass the isRunning() check, and the second @@ -2261,6 +2295,12 @@ 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 (or into a retry's waiter). A fresh runMcpCommand does + // NOT clear this flag — the retry stays blocked until the output + // drains or the next prompt boundary clears it. + 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