From e23d404de1d36a61c5c30a1b8c56eda60b33922f Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 20 Nov 2026 11:57:33 +0000 Subject: [PATCH 1/5] fix: keep the active run when pi refuses a prompt, and guard pool clone roots pi refuses a bare prompt while a run is active ("already processing"). The wrapper's failure path reset the run state and cleared the live snapshot, so the chat showed an idle session while pi kept working. A refusal now keeps the state of the run that was active, unless frames that arrived meanwhile ended it. A pool workspace clone root inside pi's agent directory or ~/.pi is now refused with 403 agent_dir_read_only, as the Files panel and worktree removal already are. --- lib/hosts/session-ops.test.mjs | 10 +++++++++ lib/hosts/session-ops.ts | 7 +++++++ lib/rpc-manager.test.mjs | 38 +++++++++++++++++++++++++++++++++- lib/rpc-manager.ts | 22 ++++++++++++++++++++ 4 files changed, 76 insertions(+), 1 deletion(-) diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index ac0d0b97..ba407def 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -117,6 +117,16 @@ test("preparePoolProject rejects malformed authenticated inputs without a launch } }); +test("preparePoolProject refuses a clone root inside pi's agent directory", () => withAgentDir(async () => { + const result = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: join(process.env.PI_CODING_AGENT_DIR, "skills", "repo"), + }); + assert.equal(result.ok, false); + assert.equal(result.status, 403); + assert.equal(result.code, "agent_dir_read_only"); +})); + test("searchSessions accepts the exact query limit and empty queries", () => withAgentDir(async () => { for (const query of ["", " ", '""', "z".repeat(500)]) { assert.deepEqual(await sessionOps.searchSessions(query), { ok: true, value: {} }); diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 000a30c0..e2cb1a0f 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -29,6 +29,8 @@ import { writeSessionFileAtomicSync, } from "../pi/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; +import { HostOpError } from "./link-protocol"; +import { assertOutsideAgentDir } from "./workspace-roots"; import { projectIdentityKey, sessionPathKey } from "../paths"; import { hideProject, @@ -802,6 +804,11 @@ export const sessionOps: SessionOps = { || (input.ref !== undefined && typeof input.ref !== "string")) { return fail(400, "invalid_request", "Invalid pool project preparation input"); } + // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration. + try { assertOutsideAgentDir(input.cloneRoot); } catch (error) { + if (error instanceof HostOpError) return fail(error.status, error.code, error.message); + throw error; + } return preparePoolProject(input); }, }; diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 4e53b636..ad29a6c3 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1087,14 +1087,50 @@ test("terminal failures, new runs, aborts and idle reconciliation cannot revive await wrapper.send({ type: "get_state" }); assertCleared(); assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); - seed(); failPrompt = true; await assert.rejects(wrapper.send({ type: "prompt", message: "retry" }), /prompt rejected/); assertCleared(); + assert.equal(wrapper.isRunning(), false); await wrapper.destroyAndWait(); assert.equal(wrapper.getStreamSnapshot().isStreaming, false); }); +test("pi refusing a prompt during a run (already processing) keeps that run and its output", async (t) => { + let refuse = true; + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type === "prompt" && refuse) throw new Error("Agent is already processing."); + if (command.type === "get_state") return { sessionId: "snapshot-life", isStreaming: true, isCompacting: false }; + return {}; + }); + emit({ type: "agent_start" }); + emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); + emit({ type: "tool_execution_start", toolCallId: "live-tool", toolName: "bash" }); + await assert.rejects(wrapper.send({ type: "prompt", message: "too soon" }), /already processing/); + const snapshot = wrapper.getStreamSnapshot(); + assert.equal(wrapper.isRunning(), true); + assert.equal(snapshot.isStreaming, true); + assert.equal(snapshot.isPromptRunning, true); + assert.equal(snapshot.responseObserved, true); + assert.equal(snapshot.toolEvents[0].toolCallId, "live-tool"); + + // A refusal whose run ended while the prompt was in flight leaves the session idle. + let finish; + refuse = false; + const late = snapshotSession(t, (command) => { + if (command.type === "prompt") return new Promise((_, reject) => { finish = () => reject(new Error("Agent is already processing.")); }); + if (command.type === "get_state") return Promise.resolve({ sessionId: "snapshot-life", isStreaming: false, isCompacting: false }); + return Promise.resolve({}); + }); + late.emit({ type: "agent_start" }); + const pending = late.wrapper.send({ type: "prompt", message: "too soon" }); + late.emit({ type: "agent_end", isTerminal: true }); + finish(); + await assert.rejects(pending, /already processing/); + assert.equal(late.wrapper.isRunning(), false); + assert.equal(late.wrapper.getStreamSnapshot().isPromptRunning, false); +}); + test("session identity changes invalidate the stream epoch and all prior partial output", async (t) => { let sessionId = "identity-before"; const { wrapper, emit } = snapshotSession(t, async (command) => { diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8a5a88f..e1c29328 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2101,6 +2101,11 @@ export class AgentSessionWrapper { switch (type) { case "prompt": { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; + // pi refuses a bare prompt while a run is active ("already processing"): that refusal must not end the run. + const runBefore = this.streaming || this.promptRunning + ? { streaming: this.streaming, awaitingAgentStart: this.awaitingAgentStart, awaitingAgentStartDeadline: this.awaitingAgentStartDeadline, + responseObserved: this.responseObserved, responseRunActive: this.responseRunActive } + : null; if (!streamingBehavior) { this.responseObserved = false; this.responseRunActive = false; @@ -2143,6 +2148,23 @@ export class AgentSessionWrapper { if (preserveUnknownDelivery && error instanceof RpcCommandTimeoutError) { throw new WebRpcError("The initial prompt may have reached its session; check that session before sending it again.", "host_offline", "unknown"); } + // Frames that arrived meanwhile win: a run that ended is reset below, one that started kept its own state. + if (runBefore && !streamingBehavior && !(error instanceof RpcCommandTimeoutError)) { + if (this.streaming) { + if (runBefore.streaming && !this.responseRunActive) { + this.responseObserved = runBefore.responseObserved; + this.responseRunActive = runBefore.responseRunActive; + } + throw error; + } + if (!runBefore.streaming && this.promptRunning) { + this.awaitingAgentStart = runBefore.awaitingAgentStart; + this.awaitingAgentStartDeadline = runBefore.awaitingAgentStartDeadline; + this.responseObserved = runBefore.responseObserved; + this.responseRunActive = runBefore.responseRunActive; + throw error; + } + } this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; From 4e12abce6fa48041e00361ff6bb4ce4deff0f38f Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 20 Nov 2026 12:15:37 +0000 Subject: [PATCH 2/5] fix: decide a failed prompt's run state from what changed while it was in flight A failed prompt now leaves the run alone unless the run ended while the prompt was in flight: a run that was active keeps its state, with the response evidence, continuation grace and pending start it had (or newer values a concurrent prompt set); a run that started meanwhile keeps the state its agent_start set; a streamingBehavior prompt never touches run state. Run boundaries and visible output are counted so the comparison needs no snapshot of frame timing. A timeout still recycles the child. The pool clone root check now also refuses a root that would hold a missing agent directory, and leaves malformed roots to the existing 400. --- lib/hosts/session-ops.test.mjs | 14 +++++ lib/hosts/session-ops.ts | 7 ++- lib/rpc-manager.test.mjs | 109 ++++++++++++++++++++++++++++----- lib/rpc-manager.ts | 54 ++++++++++------ 4 files changed, 144 insertions(+), 40 deletions(-) diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index ba407def..ca3bee23 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -125,6 +125,20 @@ test("preparePoolProject refuses a clone root inside pi's agent directory", () = assert.equal(result.ok, false); assert.equal(result.status, 403); assert.equal(result.code, "agent_dir_read_only"); + + // A root that would hold a not-yet-created agent directory: a cloned `agent/` would become pi's configuration. + const previous = process.env.PI_CODING_AGENT_DIR; + const missingParent = join(previous, "missing-pi"); + process.env.PI_CODING_AGENT_DIR = join(missingParent, "agent"); + try { + const holding = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: missingParent, + }); + assert.equal(holding.code, "agent_dir_read_only"); + } finally { + process.env.PI_CODING_AGENT_DIR = previous; + } })); test("searchSessions accepts the exact query limit and empty queries", () => withAgentDir(async () => { diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index e2cb1a0f..e2c2f1e2 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -30,7 +30,7 @@ import { } from "../pi/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; import { HostOpError } from "./link-protocol"; -import { assertOutsideAgentDir } from "./workspace-roots"; +import { assertRemovableOutsideAgentDir } from "./workspace-roots"; import { projectIdentityKey, sessionPathKey } from "../paths"; import { hideProject, @@ -804,8 +804,9 @@ export const sessionOps: SessionOps = { || (input.ref !== undefined && typeof input.ref !== "string")) { return fail(400, "invalid_request", "Invalid pool project preparation input"); } - // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration. - try { assertOutsideAgentDir(input.cloneRoot); } catch (error) { + // A clone root inside pi's agent directory or ~/.pi, or holding a missing one, would let a pool clone write + // pi's configuration. A malformed root is left to preparePoolProject's 400. + try { if (isAbsolute(input.cloneRoot) && resolve(input.cloneRoot) === input.cloneRoot) assertRemovableOutsideAgentDir(input.cloneRoot); } catch (error) { if (error instanceof HostOpError) return fail(error.status, error.code, error.message); throw error; } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index ad29a6c3..49170719 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1087,6 +1087,9 @@ test("terminal failures, new runs, aborts and idle reconciliation cannot revive await wrapper.send({ type: "get_state" }); assertCleared(); assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); + // A failed prompt from an idle session clears output left from before it (no run owns it). + emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "old" }] } }); + emit({ type: "tool_execution_start", toolCallId: "old-tool", toolName: "bash" }); failPrompt = true; await assert.rejects(wrapper.send({ type: "prompt", message: "retry" }), /prompt rejected/); assertCleared(); @@ -1095,11 +1098,23 @@ test("terminal failures, new runs, aborts and idle reconciliation cannot revive assert.equal(wrapper.getStreamSnapshot().isStreaming, false); }); +const REFUSAL = "Agent is already processing."; + +/** A session whose prompts stay unanswered until the test settles them through `held`; frames can arrive meanwhile. */ +function heldPromptSession(t, isStreaming = true) { + const held = []; + const session = snapshotSession(t, (command) => { + if (command.type === "prompt") return new Promise((resolve, reject) => { held.push({ resolve, reject }); }); + if (command.type === "get_state") return Promise.resolve({ sessionId: "refusal", isStreaming, isCompacting: false }); + return Promise.resolve({}); + }); + return { ...session, held }; +} + test("pi refusing a prompt during a run (already processing) keeps that run and its output", async (t) => { - let refuse = true; const { wrapper, emit } = snapshotSession(t, async (command) => { - if (command.type === "prompt" && refuse) throw new Error("Agent is already processing."); - if (command.type === "get_state") return { sessionId: "snapshot-life", isStreaming: true, isCompacting: false }; + if (command.type === "prompt") throw new Error(REFUSAL); + if (command.type === "get_state") return { sessionId: "refusal", isStreaming: true, isCompacting: false }; return {}; }); emit({ type: "agent_start" }); @@ -1113,22 +1128,82 @@ test("pi refusing a prompt during a run (already processing) keeps that run and assert.equal(snapshot.isPromptRunning, true); assert.equal(snapshot.responseObserved, true); assert.equal(snapshot.toolEvents[0].toolCallId, "live-tool"); + // A prompt that joins the run (the outbox's slash command during a run) never set run state, so its failure keeps it. + await assert.rejects(wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }), /already processing/); + assert.equal(wrapper.isRunning(), true); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); +}); - // A refusal whose run ended while the prompt was in flight leaves the session idle. - let finish; - refuse = false; - const late = snapshotSession(t, (command) => { - if (command.type === "prompt") return new Promise((_, reject) => { finish = () => reject(new Error("Agent is already processing.")); }); - if (command.type === "get_state") return Promise.resolve({ sessionId: "snapshot-life", isStreaming: false, isCompacting: false }); - return Promise.resolve({}); +test("a refused prompt keeps what the run produced, and the grace window it was in, while the prompt was in flight", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "agent_start" }); + const first = wrapper.send({ type: "prompt", message: "too soon" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "answer" }] } }); + held[0].reject(new Error(REFUSAL)); + await assert.rejects(first, /already processing/); + assert.equal(wrapper.getStreamSnapshot().responseObserved, true); + + emit({ type: "agent_end", isTerminal: false }); + const second = wrapper.send({ type: "prompt", message: "between turns" }); + held[1].reject(new Error(REFUSAL)); + await assert.rejects(second, /already processing/); + // pi reports idle between continuation turns; the grace window must still hold the run. + assert.equal((await wrapper.send({ type: "get_state" })).isPromptRunning, true); +}); + +test("a refused prompt leaves a run that started meanwhile, ends one that ended, and keeps an earlier prompt's pending start", async (t) => { + // Idle when sent; another tab's run starts before pi refuses this prompt. + const started = heldPromptSession(t); + const raced = started.wrapper.send({ type: "prompt", message: "raced" }); + started.emit({ type: "agent_start" }); + started.emit({ type: "tool_execution_start", toolCallId: "other-tab", toolName: "bash" }); + started.held[0].reject(new Error(REFUSAL)); + await assert.rejects(raced, /already processing/); + assert.equal(started.wrapper.isRunning(), true); + assert.equal(started.wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "other-tab"); + + // Running when sent; the run ends and a new one starts before the refusal: the new run keeps its own state. + const restarted = heldPromptSession(t); + restarted.emit({ type: "agent_start" }); + restarted.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "old run" }] } }); + const during = restarted.wrapper.send({ type: "prompt", message: "too soon" }); + restarted.emit({ type: "agent_end", isTerminal: true }); + restarted.emit({ type: "agent_start" }); + restarted.held[0].reject(new Error(REFUSAL)); + await assert.rejects(during, /already processing/); + assert.equal(restarted.wrapper.isRunning(), true); + assert.equal(restarted.wrapper.getStreamSnapshot().responseObserved, false, "the old run's answer is not the new run's"); + + // Running when sent; the run ends before the refusal: the session is idle. + const ended = heldPromptSession(t, false); + ended.emit({ type: "agent_start" }); + const afterEnd = ended.wrapper.send({ type: "prompt", message: "too soon" }); + ended.emit({ type: "agent_end", isTerminal: true }); + ended.held[0].reject(new Error(REFUSAL)); + await assert.rejects(afterEnd, /already processing/); + assert.equal(ended.wrapper.isRunning(), false); + assert.equal(ended.wrapper.getStreamSnapshot().isPromptRunning, false); + + // Prompt A is acked and waits for agent_start when B, sent meanwhile, is refused: A's pending start stays. + const pending = heldPromptSession(t, false); + const a = pending.wrapper.send({ type: "prompt", message: "a" }); + const b = pending.wrapper.send({ type: "prompt", message: "b" }); + pending.held[0].resolve({ agentInvoked: true }); + await a; + pending.held[1].reject(new Error(REFUSAL)); + await assert.rejects(b, /already processing/); + assert.equal((await pending.wrapper.send({ type: "get_state" })).isPromptRunning, true, "A's agent_start is still awaited"); +}); + +test("a prompt ack timeout during a run still recycles the unresponsive child", async (t) => { + const { RpcCommandTimeoutError } = await import("./pi/rpc-process.ts"); + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30000); + return {}; }); - late.emit({ type: "agent_start" }); - const pending = late.wrapper.send({ type: "prompt", message: "too soon" }); - late.emit({ type: "agent_end", isTerminal: true }); - finish(); - await assert.rejects(pending, /already processing/); - assert.equal(late.wrapper.isRunning(), false); - assert.equal(late.wrapper.getStreamSnapshot().isPromptRunning, false); + emit({ type: "agent_start" }); + await assert.rejects(wrapper.send({ type: "prompt", message: "lost" }), (error) => error.code === "session_unresponsive"); + assert.equal(wrapper.isAlive(), false); }); test("session identity changes invalidate the stream epoch and all prior partial output", async (t) => { diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index e1c29328..74648d5b 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -411,6 +411,9 @@ export class AgentSessionWrapper { /** Positive evidence for this run, retained after native completion but before disk append. */ private responseObserved = false; private responseRunActive = false; + /** Counts run boundaries (agent_start/agent_end/prompt_*) and visible assistant output, so a refused prompt can tell what changed meanwhile. */ + private runBoundaries = 0; + private visibleOutputs = 0; private idleTimer: ReturnType | null = null; /** Lazily-armed deadline for tearing down a session nobody is watching. */ private reapTimer: ReturnType | null = null; @@ -1304,11 +1307,13 @@ export class AgentSessionWrapper { delete event.web; switch (event.type) { case "agent_start": + this.runBoundaries += 1; this.responseObserved = false; this.responseRunActive = true; this.clearLiveSnapshots(); break; case "agent_end": + this.runBoundaries += 1; if (event.isTerminal === false) break; this.responseRunActive = false; this.streaming = false; @@ -1319,6 +1324,7 @@ export class AgentSessionWrapper { break; case "prompt_error": case "prompt_result": + this.runBoundaries += 1; this.responseRunActive = false; this.streaming = false; this.compacting = false; @@ -1349,12 +1355,18 @@ export class AgentSessionWrapper { this.streamingMessage = message; this.streamingMessageId = messageId; } - if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; + if (hasVisibleAssistantContent(message)) { + this.visibleOutputs += 1; + if (this.responseRunActive) this.responseObserved = true; + } break; } case "message_end": { const message = event.message as Partial | undefined; - if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; + if (hasVisibleAssistantContent(message)) { + this.visibleOutputs += 1; + if (this.responseRunActive) this.responseObserved = true; + } if (typeof event.messageId === "string") this.openMessages.delete(event.messageId); if (message?.role && message.role === this.streamingMessage?.role) { this.streamingMessage = null; @@ -2101,11 +2113,12 @@ export class AgentSessionWrapper { switch (type) { case "prompt": { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; - // pi refuses a bare prompt while a run is active ("already processing"): that refusal must not end the run. - const runBefore = this.streaming || this.promptRunning - ? { streaming: this.streaming, awaitingAgentStart: this.awaitingAgentStart, awaitingAgentStartDeadline: this.awaitingAgentStartDeadline, - responseObserved: this.responseObserved, responseRunActive: this.responseRunActive } - : null; + // What this dispatch resets, kept so a failure can hand an active run back untouched. + const before = streamingBehavior ? null : { + active: this.streaming || this.promptRunning, runBoundaries: this.runBoundaries, visibleOutputs: this.visibleOutputs, + responseObserved: this.responseObserved, responseRunActive: this.responseRunActive, continuationGraceUntil: this.continuationGraceUntil, + awaitingAgentStart: this.awaitingAgentStart, awaitingAgentStartDeadline: this.awaitingAgentStartDeadline, + }; if (!streamingBehavior) { this.responseObserved = false; this.responseRunActive = false; @@ -2148,22 +2161,23 @@ export class AgentSessionWrapper { if (preserveUnknownDelivery && error instanceof RpcCommandTimeoutError) { throw new WebRpcError("The initial prompt may have reached its session; check that session before sending it again.", "host_offline", "unknown"); } - // Frames that arrived meanwhile win: a run that ended is reset below, one that started kept its own state. - if (runBefore && !streamingBehavior && !(error instanceof RpcCommandTimeoutError)) { - if (this.streaming) { - if (runBefore.streaming && !this.responseRunActive) { - this.responseObserved = runBefore.responseObserved; - this.responseRunActive = runBefore.responseRunActive; + // A failed prompt never ends a run it did not start: pi refuses a bare prompt during a run ("already + // processing"), and a streamingBehavior prompt never touched the run state. A timeout keeps its recycle below. + if (!(error instanceof RpcCommandTimeoutError)) { + if (!before) throw error; + const unchanged = this.runBoundaries === before.runBoundaries; + if (unchanged && before.active) { + this.responseRunActive = before.responseRunActive; + this.responseObserved = before.responseObserved || (before.responseRunActive && this.visibleOutputs !== before.visibleOutputs); + this.continuationGraceUntil = Math.max(this.continuationGraceUntil, before.continuationGraceUntil); + if (!this.awaitingAgentStart) { + this.awaitingAgentStart = before.awaitingAgentStart; + this.awaitingAgentStartDeadline = before.awaitingAgentStartDeadline; } throw error; } - if (!runBefore.streaming && this.promptRunning) { - this.awaitingAgentStart = runBefore.awaitingAgentStart; - this.awaitingAgentStartDeadline = runBefore.awaitingAgentStartDeadline; - this.responseObserved = runBefore.responseObserved; - this.responseRunActive = runBefore.responseRunActive; - throw error; - } + // A run that started meanwhile (another tab or server) owns the state its agent_start set. + if (this.streaming) throw error; } this.promptRunning = false; this.awaitingAgentStart = false; From 33216703523bffb25943ca3b5d85bfaf540c8dcb Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 20 Nov 2026 12:24:38 +0000 Subject: [PATCH 3/5] fix: count resets as run boundaries, keep a later prompt's pending start, and allow existing pool checkouts that hold ~/.pi Every live-snapshot clear and a restart now count as a run boundary, so a refused prompt restores nothing over an abort, exit, restart or identity change made while it was in flight. A refusal also leaves the state of a prompt still in flight or acked and awaiting its agent_start, and treats compaction as an active run. The pool clone root check refuses a root that would hold a missing agent directory only when the clone would create it; an existing checkout gets the plain inside-the-agent-directory check. --- lib/hosts/session-ops.test.mjs | 11 +++++++++++ lib/hosts/session-ops.ts | 17 ++++++++++++----- lib/rpc-manager.test.mjs | 33 +++++++++++++++++++++++++++++++++ lib/rpc-manager.ts | 13 +++++++------ 4 files changed, 63 insertions(+), 11 deletions(-) diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index ca3bee23..64869789 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -136,9 +136,20 @@ test("preparePoolProject refuses a clone root inside pi's agent directory", () = origin: "https://fixture.invalid/repo.git", cloneRoot: missingParent, }); assert.equal(holding.code, "agent_dir_read_only"); + // An existing checkout that holds it (a dotfiles repository at $HOME) only gets sibling worktrees: not refused here. + mkdirSync(missingParent); + const existing = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: missingParent, + }); + assert.notEqual(existing.code, "agent_dir_read_only"); } finally { process.env.PI_CODING_AGENT_DIR = previous; } + const root = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", origin: "https://fixture.invalid/repo.git", cloneRoot: "/", + }); + assert.equal(root.status, 400, "a filesystem root is invalid, not read-only"); })); test("searchSessions accepts the exact query limit and empty queries", () => withAgentDir(async () => { diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index e2c2f1e2..8744d5f2 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -5,7 +5,7 @@ // No `next/*` or `@/` imports: the daemon loads this through plain jiti. import { randomUUID } from "crypto"; import { execFile } from "child_process"; -import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, realpathSync, rmSync, statSync, type Stats } from "fs"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, realpathSync, rmSync, statSync, type Stats } from "fs"; import * as fsRuntime from "fs"; import { homedir, tmpdir } from "os"; import { basename, dirname, isAbsolute, join, resolve } from "path"; @@ -30,7 +30,7 @@ import { } from "../pi/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; import { HostOpError } from "./link-protocol"; -import { assertRemovableOutsideAgentDir } from "./workspace-roots"; +import { assertOutsideAgentDir, assertRemovableOutsideAgentDir } from "./workspace-roots"; import { projectIdentityKey, sessionPathKey } from "../paths"; import { hideProject, @@ -804,9 +804,16 @@ export const sessionOps: SessionOps = { || (input.ref !== undefined && typeof input.ref !== "string")) { return fail(400, "invalid_request", "Invalid pool project preparation input"); } - // A clone root inside pi's agent directory or ~/.pi, or holding a missing one, would let a pool clone write - // pi's configuration. A malformed root is left to preparePoolProject's 400. - try { if (isAbsolute(input.cloneRoot) && resolve(input.cloneRoot) === input.cloneRoot) assertRemovableOutsideAgentDir(input.cloneRoot); } catch (error) { + // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration, and so would a + // clone that creates a root holding a missing one. An existing checkout only gets sibling worktrees. A malformed + // root is left to preparePoolProject's 400. + const root = input.cloneRoot; + try { + if (isAbsolute(root) && resolve(root) === root) { + if (existsSync(root)) assertOutsideAgentDir(root); + else assertRemovableOutsideAgentDir(root); + } + } catch (error) { if (error instanceof HostOpError) return fail(error.status, error.code, error.message); throw error; } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 49170719..c48fc43e 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1195,6 +1195,39 @@ test("a refused prompt leaves a run that started meanwhile, ends one that ended, assert.equal((await pending.wrapper.send({ type: "get_state" })).isPromptRunning, true, "A's agent_start is still awaited"); }); +test("a refused prompt restores nothing over a reset made while it was in flight, nor clears a later prompt's pending start", async (t) => { + // Abort during the flight resets the run's evidence: the refusal must not bring it back. + const aborted = heldPromptSession(t); + aborted.emit({ type: "agent_start" }); + const during = aborted.wrapper.send({ type: "prompt", message: "too soon" }); + await aborted.wrapper.send({ type: "abort" }); + aborted.held[0].reject(new Error(REFUSAL)); + await assert.rejects(during, /already processing/); + aborted.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "after abort" }] } }); + assert.equal(aborted.wrapper.getStreamSnapshot().responseObserved, false); + + // The run ends while B is in flight, then C is acked: B's refusal leaves C's pending start. + const later = heldPromptSession(t, false); + later.emit({ type: "agent_start" }); + const b = later.wrapper.send({ type: "prompt", message: "b" }); + later.emit({ type: "agent_end", isTerminal: true }); + const c = later.wrapper.send({ type: "prompt", message: "c" }); + later.held[1].resolve({ agentInvoked: true }); + await c; + later.held[0].reject(new Error(REFUSAL)); + await assert.rejects(b, /already processing/); + assert.equal((await later.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); + + // A prompt refused during compaction keeps the live state. + const compacting = heldPromptSession(t, false); + compacting.emit({ type: "auto_compaction_start" }); + compacting.emit({ type: "tool_execution_start", toolCallId: "compaction-tool", toolName: "bash" }); + const refused = compacting.wrapper.send({ type: "prompt", message: "while compacting" }); + compacting.held[0].reject(new Error(REFUSAL)); + await assert.rejects(refused, /already processing/); + assert.equal(compacting.wrapper.getStreamSnapshot().toolEvents[0]?.toolCallId, "compaction-tool"); +}); + test("a prompt ack timeout during a run still recycles the unresponsive child", async (t) => { const { RpcCommandTimeoutError } = await import("./pi/rpc-process.ts"); const { wrapper, emit } = snapshotSession(t, async (command) => { diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 74648d5b..775f45eb 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -411,7 +411,7 @@ export class AgentSessionWrapper { /** Positive evidence for this run, retained after native completion but before disk append. */ private responseObserved = false; private responseRunActive = false; - /** Counts run boundaries (agent_start/agent_end/prompt_*) and visible assistant output, so a refused prompt can tell what changed meanwhile. */ + /** Counts run boundaries and resets (every live-snapshot clear, agent_end, a restart) and visible assistant output, so a refused prompt can tell what changed meanwhile. */ private runBoundaries = 0; private visibleOutputs = 0; private idleTimer: ReturnType | null = null; @@ -632,6 +632,7 @@ export class AgentSessionWrapper { this.openMessages.clear(); this.liveToolEvents.clear(); this.streamSequence += 1; + this.runBoundaries += 1; } private resetStream(): void { @@ -1307,7 +1308,6 @@ export class AgentSessionWrapper { delete event.web; switch (event.type) { case "agent_start": - this.runBoundaries += 1; this.responseObserved = false; this.responseRunActive = true; this.clearLiveSnapshots(); @@ -1324,7 +1324,6 @@ export class AgentSessionWrapper { break; case "prompt_error": case "prompt_result": - this.runBoundaries += 1; this.responseRunActive = false; this.streaming = false; this.compacting = false; @@ -1875,6 +1874,7 @@ export class AgentSessionWrapper { this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; + this.runBoundaries += 1; this.bashRunning = false; this.streaming = false; this.compacting = false; @@ -2115,7 +2115,7 @@ export class AgentSessionWrapper { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; // What this dispatch resets, kept so a failure can hand an active run back untouched. const before = streamingBehavior ? null : { - active: this.streaming || this.promptRunning, runBoundaries: this.runBoundaries, visibleOutputs: this.visibleOutputs, + active: this.streaming || this.promptRunning || this.compacting, runBoundaries: this.runBoundaries, visibleOutputs: this.visibleOutputs, responseObserved: this.responseObserved, responseRunActive: this.responseRunActive, continuationGraceUntil: this.continuationGraceUntil, awaitingAgentStart: this.awaitingAgentStart, awaitingAgentStartDeadline: this.awaitingAgentStartDeadline, }; @@ -2176,8 +2176,9 @@ export class AgentSessionWrapper { } throw error; } - // A run that started meanwhile (another tab or server) owns the state its agent_start set. - if (this.streaming) throw error; + // A run that started meanwhile (another tab or server) owns the state its agent_start set, and a prompt + // still in flight or acked and awaiting its agent_start owns the pending state. + if (this.streaming || this.awaitingAgentStart || this.promptDispatchPendingCount > 1) throw error; } this.promptRunning = false; this.awaitingAgentStart = false; From 37de890da19db6657a5e81ac17fb3613902646d2 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 20 Nov 2026 12:39:06 +0000 Subject: [PATCH 4/5] fix: a prompt sent during a run leaves the run's state alone Replace the snapshot-and-restore handling of a failed prompt with a simpler rule. A bare prompt sent while a run, a compaction or another prompt is active no longer touches the run state before sending, and its failure touches nothing; only pi taking it (the run it joined had ended) starts its own bookkeeping, unless its run already started. An idle prompt's failure leaves the state to a run that started meanwhile, a compaction, or another prompt in flight or awaiting its agent_start. A failed prompt finally clears a promptRunning that nothing owns any more (two prompts refused in turn). The pool clone root's check against a root that would hold a missing agent directory moves to just before the clone, decided by the same existence check that chooses clone or worktree. --- lib/hosts/session-ops.ts | 15 ++-- lib/pooled-projects.ts | 7 ++ lib/rpc-manager.test.mjs | 181 +++++++++++++++++++++++++-------------- lib/rpc-manager.ts | 75 ++++++++-------- 4 files changed, 167 insertions(+), 111 deletions(-) diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 8744d5f2..6414ef6a 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -5,7 +5,7 @@ // No `next/*` or `@/` imports: the daemon loads this through plain jiti. import { randomUUID } from "crypto"; import { execFile } from "child_process"; -import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, realpathSync, rmSync, statSync, type Stats } from "fs"; +import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, realpathSync, rmSync, statSync, type Stats } from "fs"; import * as fsRuntime from "fs"; import { homedir, tmpdir } from "os"; import { basename, dirname, isAbsolute, join, resolve } from "path"; @@ -30,7 +30,7 @@ import { } from "../pi/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; import { HostOpError } from "./link-protocol"; -import { assertOutsideAgentDir, assertRemovableOutsideAgentDir } from "./workspace-roots"; +import { assertOutsideAgentDir } from "./workspace-roots"; import { projectIdentityKey, sessionPathKey } from "../paths"; import { hideProject, @@ -804,15 +804,10 @@ export const sessionOps: SessionOps = { || (input.ref !== undefined && typeof input.ref !== "string")) { return fail(400, "invalid_request", "Invalid pool project preparation input"); } - // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration, and so would a - // clone that creates a root holding a missing one. An existing checkout only gets sibling worktrees. A malformed - // root is left to preparePoolProject's 400. - const root = input.cloneRoot; + // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration (a clone that + // would create a root holding a missing one is refused where it clones). A malformed root is left to the 400. try { - if (isAbsolute(root) && resolve(root) === root) { - if (existsSync(root)) assertOutsideAgentDir(root); - else assertRemovableOutsideAgentDir(root); - } + if (isAbsolute(input.cloneRoot) && resolve(input.cloneRoot) === input.cloneRoot) assertOutsideAgentDir(input.cloneRoot); } catch (error) { if (error instanceof HostOpError) return fail(error.status, error.code, error.message); throw error; diff --git a/lib/pooled-projects.ts b/lib/pooled-projects.ts index b10d5ae3..d2cbb800 100644 --- a/lib/pooled-projects.ts +++ b/lib/pooled-projects.ts @@ -7,6 +7,8 @@ import { cloneDirectoryName, repositoryKey } from "./git-clone"; import { cloneRepository, withProjectReservation } from "./project-clone"; import { createGitEnvironment } from "./project-command-env"; import type { OpResult } from "./hosts/session-ops"; +import { HostOpError } from "./hosts/link-protocol"; +import { assertRemovableOutsideAgentDir } from "./hosts/workspace-roots"; export interface PreparedPoolProject { cwd: string; @@ -157,6 +159,11 @@ async function prepare(input: { } if (!existingClone) { + // A new root that would hold a missing agent directory or ~/.pi: a cloned `agent/` would become pi's configuration. + try { assertRemovableOutsideAgentDir(cloneRoot); } catch (error) { + if (error instanceof HostOpError) throw new PreparationError(error.code, error.message, error.status); + throw error; + } // Clone into the helper's exclusively mkdir-acquired final root. A rename // cannot publish safely here: POSIX rename may replace somebody else's empty reservation. const cloned = await cloneRepository({ origin, target: cloneRoot }); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c48fc43e..6a88c4e2 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1111,47 +1111,89 @@ function heldPromptSession(t, isStreaming = true) { return { ...session, held }; } -test("pi refusing a prompt during a run (already processing) keeps that run and its output", async (t) => { - const { wrapper, emit } = snapshotSession(t, async (command) => { - if (command.type === "prompt") throw new Error(REFUSAL); - if (command.type === "get_state") return { sessionId: "refusal", isStreaming: true, isCompacting: false }; - return {}; - }); +test("pi refusing a prompt during a run (already processing) keeps that run, its output and its grace window", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); emit({ type: "agent_start" }); - emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); emit({ type: "tool_execution_start", toolCallId: "live-tool", toolName: "bash" }); - await assert.rejects(wrapper.send({ type: "prompt", message: "too soon" }), /already processing/); + const refused = wrapper.send({ type: "prompt", message: "too soon" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "while in flight" }] } }); + held[0].reject(new Error(REFUSAL)); + await assert.rejects(refused, /already processing/); const snapshot = wrapper.getStreamSnapshot(); assert.equal(wrapper.isRunning(), true); assert.equal(snapshot.isStreaming, true); assert.equal(snapshot.isPromptRunning, true); assert.equal(snapshot.responseObserved, true); assert.equal(snapshot.toolEvents[0].toolCallId, "live-tool"); - // A prompt that joins the run (the outbox's slash command during a run) never set run state, so its failure keeps it. - await assert.rejects(wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }), /already processing/); - assert.equal(wrapper.isRunning(), true); - assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); -}); - -test("a refused prompt keeps what the run produced, and the grace window it was in, while the prompt was in flight", async (t) => { - const { wrapper, emit, held } = heldPromptSession(t, false); - emit({ type: "agent_start" }); - const first = wrapper.send({ type: "prompt", message: "too soon" }); - emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "answer" }] } }); - held[0].reject(new Error(REFUSAL)); - await assert.rejects(first, /already processing/); - assert.equal(wrapper.getStreamSnapshot().responseObserved, true); + // Between continuation turns pi reports idle; the grace window must still hold the run after a refusal. emit({ type: "agent_end", isTerminal: false }); - const second = wrapper.send({ type: "prompt", message: "between turns" }); + const between = wrapper.send({ type: "prompt", message: "between turns" }); held[1].reject(new Error(REFUSAL)); - await assert.rejects(second, /already processing/); - // pi reports idle between continuation turns; the grace window must still hold the run. + await assert.rejects(between, /already processing/); assert.equal((await wrapper.send({ type: "get_state" })).isPromptRunning, true); + // The idle read above left only promptRunning and the grace window; a refusal now must not settle the run either. + const afterRead = wrapper.send({ type: "prompt", message: "after the read" }); + held[2].reject(new Error(REFUSAL)); + await assert.rejects(afterRead, /already processing/); + assert.equal(wrapper.getStreamSnapshot().isPromptRunning, true); +}); + +test("a failed prompt that joins a run (streamingBehavior) or runs an extension command beside it leaves the run alone", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t); + emit({ type: "agent_start" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); + emit({ type: "tool_execution_start", toolCallId: "live-tool", toolName: "bash" }); + const joined = wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }); + held[0].reject(new Error("request_too_large")); + await assert.rejects(joined, /request_too_large/); + assert.equal(wrapper.isRunning(), true); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); + + const command = wrapper.send({ type: "prompt", message: "/extension-command" }); + held[1].resolve({ agentInvoked: false }); + assert.deepEqual(await command, { agentInvoked: false }); + assert.equal(wrapper.isRunning(), true); + assert.equal(wrapper.getStreamSnapshot().responseObserved, true, "the run's evidence stays"); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); + + // An idle prompt still in flight owns promptRunning: a failed streamingBehavior prompt must not settle it. + const idle = heldPromptSession(t, false); + const first = idle.wrapper.send({ type: "prompt", message: "first" }); + const queued = idle.wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }); + idle.held[1].reject(new Error("request_too_large")); + await assert.rejects(queued, /request_too_large/); + assert.equal(idle.wrapper.isRunning(), true); + idle.held[0].resolve({ agentInvoked: true }); + await first; }); -test("a refused prompt leaves a run that started meanwhile, ends one that ended, and keeps an earlier prompt's pending start", async (t) => { +test("a prompt pi takes after the run it joined ended starts its own run: the old run's answer is not its evidence", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "agent_start" }); + const next = wrapper.send({ type: "prompt", message: "next question" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "late old answer" }] } }); + emit({ type: "agent_end", isTerminal: true }); + held[0].resolve({ agentInvoked: true }); + await next; + const state = await wrapper.send({ type: "get_state" }); + assert.equal(state.responseObserved, false); + assert.equal(state.isPromptRunning, true, "its agent_start is awaited"); + + // Its run starts and answers before the ack arrives: the ack must not reset that run's evidence. + const early = heldPromptSession(t); + early.emit({ type: "agent_start" }); + const taken = early.wrapper.send({ type: "prompt", message: "next question" }); + early.emit({ type: "agent_end", isTerminal: true }); + early.emit({ type: "agent_start" }); + early.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "new answer" }] } }); + early.held[0].resolve({ agentInvoked: true }); + await taken; + assert.equal(early.wrapper.getStreamSnapshot().responseObserved, true); +}); + +test("a refused prompt leaves a run that started meanwhile, ends with one that ended, and keeps an earlier prompt's pending start", async (t) => { // Idle when sent; another tab's run starts before pi refuses this prompt. const started = heldPromptSession(t); const raced = started.wrapper.send({ type: "prompt", message: "raced" }); @@ -1162,18 +1204,6 @@ test("a refused prompt leaves a run that started meanwhile, ends one that ended, assert.equal(started.wrapper.isRunning(), true); assert.equal(started.wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "other-tab"); - // Running when sent; the run ends and a new one starts before the refusal: the new run keeps its own state. - const restarted = heldPromptSession(t); - restarted.emit({ type: "agent_start" }); - restarted.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "old run" }] } }); - const during = restarted.wrapper.send({ type: "prompt", message: "too soon" }); - restarted.emit({ type: "agent_end", isTerminal: true }); - restarted.emit({ type: "agent_start" }); - restarted.held[0].reject(new Error(REFUSAL)); - await assert.rejects(during, /already processing/); - assert.equal(restarted.wrapper.isRunning(), true); - assert.equal(restarted.wrapper.getStreamSnapshot().responseObserved, false, "the old run's answer is not the new run's"); - // Running when sent; the run ends before the refusal: the session is idle. const ended = heldPromptSession(t, false); ended.emit({ type: "agent_start" }); @@ -1182,7 +1212,6 @@ test("a refused prompt leaves a run that started meanwhile, ends one that ended, ended.held[0].reject(new Error(REFUSAL)); await assert.rejects(afterEnd, /already processing/); assert.equal(ended.wrapper.isRunning(), false); - assert.equal(ended.wrapper.getStreamSnapshot().isPromptRunning, false); // Prompt A is acked and waits for agent_start when B, sent meanwhile, is refused: A's pending start stays. const pending = heldPromptSession(t, false); @@ -1193,39 +1222,63 @@ test("a refused prompt leaves a run that started meanwhile, ends one that ended, pending.held[1].reject(new Error(REFUSAL)); await assert.rejects(b, /already processing/); assert.equal((await pending.wrapper.send({ type: "get_state" })).isPromptRunning, true, "A's agent_start is still awaited"); -}); - -test("a refused prompt restores nothing over a reset made while it was in flight, nor clears a later prompt's pending start", async (t) => { - // Abort during the flight resets the run's evidence: the refusal must not bring it back. - const aborted = heldPromptSession(t); - aborted.emit({ type: "agent_start" }); - const during = aborted.wrapper.send({ type: "prompt", message: "too soon" }); - await aborted.wrapper.send({ type: "abort" }); - aborted.held[0].reject(new Error(REFUSAL)); - await assert.rejects(during, /already processing/); - aborted.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "after abort" }] } }); - assert.equal(aborted.wrapper.getStreamSnapshot().responseObserved, false); // The run ends while B is in flight, then C is acked: B's refusal leaves C's pending start. const later = heldPromptSession(t, false); later.emit({ type: "agent_start" }); - const b = later.wrapper.send({ type: "prompt", message: "b" }); + const b2 = later.wrapper.send({ type: "prompt", message: "b" }); later.emit({ type: "agent_end", isTerminal: true }); - const c = later.wrapper.send({ type: "prompt", message: "c" }); + const c2 = later.wrapper.send({ type: "prompt", message: "c" }); later.held[1].resolve({ agentInvoked: true }); - await c; + await c2; later.held[0].reject(new Error(REFUSAL)); - await assert.rejects(b, /already processing/); + await assert.rejects(b2, /already processing/); assert.equal((await later.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); +}); - // A prompt refused during compaction keeps the live state. - const compacting = heldPromptSession(t, false); - compacting.emit({ type: "auto_compaction_start" }); - compacting.emit({ type: "tool_execution_start", toolCallId: "compaction-tool", toolName: "bash" }); - const refused = compacting.wrapper.send({ type: "prompt", message: "while compacting" }); - compacting.held[0].reject(new Error(REFUSAL)); +test("an idle prompt's refusal leaves a later prompt that is in flight, or acked and awaiting its start", async (t) => { + const inFlight = heldPromptSession(t, false); + const b = inFlight.wrapper.send({ type: "prompt", message: "b" }); + const c = inFlight.wrapper.send({ type: "prompt", message: "c" }); + inFlight.held[0].reject(new Error("No API key")); + await assert.rejects(b, /No API key/); + assert.equal(inFlight.wrapper.isRunning(), true, "C is still in flight"); + inFlight.held[1].resolve({ agentInvoked: true }); + await c; + + const acked = heldPromptSession(t, false); + const b2 = acked.wrapper.send({ type: "prompt", message: "b" }); + const c2 = acked.wrapper.send({ type: "prompt", message: "c" }); + acked.held[1].resolve({ agentInvoked: true }); + await c2; + acked.held[0].reject(new Error("No API key")); + await assert.rejects(b2, /No API key/); + assert.equal((await acked.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); +}); + +test("two prompts refused in turn, in either order, leave the session idle", async (t) => { + for (const order of [[0, 1], [1, 0]]) { + const { wrapper, held } = heldPromptSession(t, false); + const sent = [wrapper.send({ type: "prompt", message: "b" }), wrapper.send({ type: "prompt", message: "c" })]; + for (const index of order) { + held[index].reject(new Error("No API key")); + await assert.rejects(sent[index], /No API key/); + } + assert.equal(wrapper.isRunning(), false, `order ${order}`); + } +}); + +test("a prompt refused during compaction leaves the session idle once compaction ends", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "auto_compaction_start" }); + emit({ type: "tool_execution_start", toolCallId: "compaction-tool", toolName: "bash" }); + const refused = wrapper.send({ type: "prompt", message: "while compacting" }); + held[0].reject(new Error(REFUSAL)); await assert.rejects(refused, /already processing/); - assert.equal(compacting.wrapper.getStreamSnapshot().toolEvents[0]?.toolCallId, "compaction-tool"); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0]?.toolCallId, "compaction-tool"); + assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); + emit({ type: "auto_compaction_end" }); + assert.equal(wrapper.isRunning(), false); }); test("a prompt ack timeout during a run still recycles the unresponsive child", async (t) => { @@ -1386,14 +1439,14 @@ test("a new prompt cannot reuse old response evidence before agent_start", async emit({ type: "agent_start" }); emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "old answer" }] } }); assert.equal(wrapper.getStreamSnapshot().responseObserved, true); + // Sent during the run, the prompt leaves that run's evidence until pi takes it (pi refuses it while the run lasts). const pending = wrapper.send({ type, message: "next question" }); - assert.equal(wrapper.getStreamSnapshot().responseObserved, false); // An old completion while the prompt is in flight belongs to the earlier turn. emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "late old answer" }] } }); emit({ type: "agent_end", isTerminal: true }); - assert.equal(wrapper.getStreamSnapshot().responseObserved, false); release(); await pending; + assert.equal(wrapper.getStreamSnapshot().responseObserved, false); emit({ type: "agent_start" }); emit({ type: "agent_end", isTerminal: true }); assert.equal((await wrapper.send({ type: "get_state" })).responseObserved, false); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 775f45eb..7bc7594a 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -411,9 +411,8 @@ export class AgentSessionWrapper { /** Positive evidence for this run, retained after native completion but before disk append. */ private responseObserved = false; private responseRunActive = false; - /** Counts run boundaries and resets (every live-snapshot clear, agent_end, a restart) and visible assistant output, so a refused prompt can tell what changed meanwhile. */ - private runBoundaries = 0; - private visibleOutputs = 0; + /** agent_start frames seen: a prompt acknowledged after one arrived knows its run already started. */ + private runStarts = 0; private idleTimer: ReturnType | null = null; /** Lazily-armed deadline for tearing down a session nobody is watching. */ private reapTimer: ReturnType | null = null; @@ -632,7 +631,6 @@ export class AgentSessionWrapper { this.openMessages.clear(); this.liveToolEvents.clear(); this.streamSequence += 1; - this.runBoundaries += 1; } private resetStream(): void { @@ -934,6 +932,7 @@ export class AgentSessionWrapper { switch (event.type) { case "agent_start": + this.runStarts += 1; this.unsettled = true; this.promptRunning = true; this.streaming = true; @@ -1313,7 +1312,6 @@ export class AgentSessionWrapper { this.clearLiveSnapshots(); break; case "agent_end": - this.runBoundaries += 1; if (event.isTerminal === false) break; this.responseRunActive = false; this.streaming = false; @@ -1354,18 +1352,12 @@ export class AgentSessionWrapper { this.streamingMessage = message; this.streamingMessageId = messageId; } - if (hasVisibleAssistantContent(message)) { - this.visibleOutputs += 1; - if (this.responseRunActive) this.responseObserved = true; - } + if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; break; } case "message_end": { const message = event.message as Partial | undefined; - if (hasVisibleAssistantContent(message)) { - this.visibleOutputs += 1; - if (this.responseRunActive) this.responseObserved = true; - } + if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; if (typeof event.messageId === "string") this.openMessages.delete(event.messageId); if (message?.role && message.role === this.streamingMessage?.role) { this.streamingMessage = null; @@ -1874,7 +1866,6 @@ export class AgentSessionWrapper { this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; - this.runBoundaries += 1; this.bashRunning = false; this.streaming = false; this.compacting = false; @@ -2099,6 +2090,15 @@ export class AgentSessionWrapper { } } + /** A failed prompt's last word: `promptRunning` with no run, compaction, pending start, continuation window or other + * prompt in flight belongs to nobody (two prompts refused in turn leave it so), and would keep the session running. */ + private settleOrphanedPrompt(ownDispatches: number): void { + if (!this.promptRunning || this.streaming || this.compacting || this.awaitingAgentStart + || this.promptDispatchPendingCount > ownDispatches || Date.now() < this.continuationGraceUntil) return; + this.promptRunning = false; + notifyRunningChange(); + } + private async dispatchCommand(command: Record, preserveUnknownDelivery = false, correlationKey: object = command): Promise { const type = command.type as string; @@ -2113,19 +2113,17 @@ export class AgentSessionWrapper { switch (type) { case "prompt": { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; - // What this dispatch resets, kept so a failure can hand an active run back untouched. - const before = streamingBehavior ? null : { - active: this.streaming || this.promptRunning || this.compacting, runBoundaries: this.runBoundaries, visibleOutputs: this.visibleOutputs, - responseObserved: this.responseObserved, responseRunActive: this.responseRunActive, continuationGraceUntil: this.continuationGraceUntil, - awaitingAgentStart: this.awaitingAgentStart, awaitingAgentStartDeadline: this.awaitingAgentStartDeadline, - }; - if (!streamingBehavior) { + // pi refuses a bare prompt during a run ("already processing"). Sent while a run, compaction or another + // prompt is active, the prompt leaves that state alone; only pi taking it (the run had ended) starts its own. + const joinsRun = !streamingBehavior && (this.streaming || this.promptRunning || this.compacting); + const runStarts = this.runStarts; + if (!streamingBehavior) this.promptDispatchPendingCount += 1; + if (!streamingBehavior && !joinsRun) { this.responseObserved = false; this.responseRunActive = false; if (!this.isRunning()) this.clearLiveSnapshots(); this.streamSequence += 1; this.promptRunning = true; - this.promptDispatchPendingCount += 1; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; @@ -2142,6 +2140,19 @@ export class AgentSessionWrapper { ...(isClientMessageId(command.clientMessageId) ? { clientMessageId: command.clientMessageId } : {}), ...(isRecord(command.origin) ? { origin: command.origin } : {}), }, PROMPT_ACK_TIMEOUT_MS, correlationKey); + if (joinsRun) { + // An extension command ran beside the run (agentInvoked:false), or a run already started: nothing to start. + if (ack?.agentInvoked !== false && this.runStarts === runStarts) { + this.responseObserved = false; + this.responseRunActive = false; + this.promptRunning = true; + this.awaitingAgentStart = true; + this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; + this.continuationGraceUntil = 0; + notifyRunningChange(); + } + return ack?.agentInvoked === false ? ack : null; + } // Slash commands fully consumed by a builtin report agentInvoked:false // in the ack itself — no prompt_result frame follows. if (ack?.agentInvoked === false && !streamingBehavior) { @@ -2161,24 +2172,14 @@ export class AgentSessionWrapper { if (preserveUnknownDelivery && error instanceof RpcCommandTimeoutError) { throw new WebRpcError("The initial prompt may have reached its session; check that session before sending it again.", "host_offline", "unknown"); } - // A failed prompt never ends a run it did not start: pi refuses a bare prompt during a run ("already - // processing"), and a streamingBehavior prompt never touched the run state. A timeout keeps its recycle below. if (!(error instanceof RpcCommandTimeoutError)) { - if (!before) throw error; - const unchanged = this.runBoundaries === before.runBoundaries; - if (unchanged && before.active) { - this.responseRunActive = before.responseRunActive; - this.responseObserved = before.responseObserved || (before.responseRunActive && this.visibleOutputs !== before.visibleOutputs); - this.continuationGraceUntil = Math.max(this.continuationGraceUntil, before.continuationGraceUntil); - if (!this.awaitingAgentStart) { - this.awaitingAgentStart = before.awaitingAgentStart; - this.awaitingAgentStartDeadline = before.awaitingAgentStartDeadline; - } + // A prompt that joined a run never touched its state. An idle prompt leaves the state to a run that started + // meanwhile (another tab or server), a compaction, or a prompt still in flight or awaiting its agent_start. + const inFlight = streamingBehavior ? 0 : 1; + if (streamingBehavior || joinsRun || this.streaming || this.compacting || this.awaitingAgentStart || this.promptDispatchPendingCount > inFlight) { + this.settleOrphanedPrompt(inFlight); throw error; } - // A run that started meanwhile (another tab or server) owns the state its agent_start set, and a prompt - // still in flight or acked and awaiting its agent_start owns the pending state. - if (this.streaming || this.awaitingAgentStart || this.promptDispatchPendingCount > 1) throw error; } this.promptRunning = false; this.awaitingAgentStart = false; From 14451e2c3855d30182a6720ab535c10f899cc6e0 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 20 Nov 2026 12:50:48 +0000 Subject: [PATCH 5/5] fix: check the pool session worktree path and settle after a joined command Pool preparation also refuses a session worktree path that is, lies in or would hold pi's agent directory, before fetching or checking out. An extension command acked after the prompt it joined failed now clears the promptRunning nobody owns. The session-ops test resolves its temp directory, which macOS keeps under the /var symlink that pool preparation refuses first. --- lib/hosts/session-ops.test.mjs | 5 +++-- lib/pooled-projects.test.mjs | 14 ++++++++++++++ lib/pooled-projects.ts | 14 ++++++++++---- lib/rpc-manager.test.mjs | 11 +++++++++++ lib/rpc-manager.ts | 5 ++++- 5 files changed, 42 insertions(+), 7 deletions(-) diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index 64869789..8e7e7295 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -128,7 +128,8 @@ test("preparePoolProject refuses a clone root inside pi's agent directory", () = // A root that would hold a not-yet-created agent directory: a cloned `agent/` would become pi's configuration. const previous = process.env.PI_CODING_AGENT_DIR; - const missingParent = join(previous, "missing-pi"); + // macOS temp directories sit under the /var symlink, which pool preparation refuses before this check. + const missingParent = join(realpathSync(previous), "missing-pi"); process.env.PI_CODING_AGENT_DIR = join(missingParent, "agent"); try { const holding = await sessionOps.preparePoolProject({ diff --git a/lib/pooled-projects.test.mjs b/lib/pooled-projects.test.mjs index 25ae43b2..9931ac79 100644 --- a/lib/pooled-projects.test.mjs +++ b/lib/pooled-projects.test.mjs @@ -151,6 +151,20 @@ test("fetches pushed refs from another clone without resetting a dirty checkout" assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); })); +test("a session worktree that would hold pi's agent directory is refused before checkout", () => fixture(async (f) => { + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = join(worktree(f), "agent"); + try { + const result = await preparePoolProject(f.input); + rejected(result); + assert.equal(result.code, "agent_dir_read_only"); + assert.equal(existsSync(worktree(f)), false); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + } +})); + test("same creation is idempotent and preserves its dirty worktree", () => fixture(async (f) => { const first = prepared(await preparePoolProject(f.input)); writeFileSync(join(first.cwd, "tracked.txt"), "session edit\n"); diff --git a/lib/pooled-projects.ts b/lib/pooled-projects.ts index d2cbb800..c391cbc1 100644 --- a/lib/pooled-projects.ts +++ b/lib/pooled-projects.ts @@ -83,6 +83,14 @@ function hasHttpsCredentials(origin: string): boolean { } } +/** Refuses a path that is, lies in, or would hold pi's agent directory or ~/.pi, as a preparation error. */ +function outsideAgentDir(path: string): void { + try { assertRemovableOutsideAgentDir(path); } catch (error) { + if (error instanceof HostOpError) throw new PreparationError(error.code, error.message, error.status); + throw error; + } +} + async function git(cwd: string, ...args: string[]): Promise { const { stdout } = await exec("git", ["-C", cwd, ...args], { encoding: "utf8", @@ -160,10 +168,7 @@ async function prepare(input: { if (!existingClone) { // A new root that would hold a missing agent directory or ~/.pi: a cloned `agent/` would become pi's configuration. - try { assertRemovableOutsideAgentDir(cloneRoot); } catch (error) { - if (error instanceof HostOpError) throw new PreparationError(error.code, error.message, error.status); - throw error; - } + outsideAgentDir(cloneRoot); // Clone into the helper's exclusively mkdir-acquired final root. A rename // cannot publish safely here: POSIX rename may replace somebody else's empty reservation. const cloned = await cloneRepository({ origin, target: cloneRoot }); @@ -225,6 +230,7 @@ async function prepare(input: { } // Fetch the remote ref itself, not a possibly unpublished local branch. Never reset or clean. + outsideAgentDir(cwd); // the session worktree is checked out at cwd: it must not land in or around the agent directory await fetchRemoteRef(cloneRoot, ref ?? "HEAD"); const baseCommit = await git(cloneRoot, "rev-parse", "--verify", "FETCH_HEAD^{commit}"); await mkdir(sessionRoot, { recursive: true }); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 6a88c4e2..cd2ad152 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1256,6 +1256,17 @@ test("an idle prompt's refusal leaves a later prompt that is in flight, or acked assert.equal((await acked.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); }); +test("an extension command acked after the prompt it joined failed leaves the session idle", async (t) => { + const { wrapper, held } = heldPromptSession(t, false); + const a = wrapper.send({ type: "prompt", message: "a" }); + const b = wrapper.send({ type: "prompt", message: "/extension-command" }); + held[0].reject(new Error("No API key")); + await assert.rejects(a, /No API key/); + held[1].resolve({ agentInvoked: false }); + assert.deepEqual(await b, { agentInvoked: false }); + assert.equal(wrapper.isRunning(), false); +}); + test("two prompts refused in turn, in either order, leave the session idle", async (t) => { for (const order of [[0, 1], [1, 0]]) { const { wrapper, held } = heldPromptSession(t, false); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 7bc7594a..a83d4c1d 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2151,7 +2151,10 @@ export class AgentSessionWrapper { this.continuationGraceUntil = 0; notifyRunningChange(); } - return ack?.agentInvoked === false ? ack : null; + if (ack?.agentInvoked !== false) return null; + // A command that ran beside a prompt which failed meanwhile is the last one out of a promptRunning nobody owns. + this.settleOrphanedPrompt(1); + return ack; } // Slash commands fully consumed by a builtin report agentInvoked:false // in the ack itself — no prompt_result frame follows.