Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion lib/hosts/session-ops.test.mjs
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -117,6 +117,42 @@ 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");

// 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;
// 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({
projectId: "registered-project", creationId: "creation-1",
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 () => {
for (const query of ["", " ", '""', "z".repeat(500)]) {
assert.deepEqual(await sessionOps.searchSessions(query), { ok: true, value: {} });
Expand Down
10 changes: 10 additions & 0 deletions lib/hosts/session-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -802,6 +804,14 @@ 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 (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(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;
}
return preparePoolProject(input);
},
};
14 changes: 14 additions & 0 deletions lib/pooled-projects.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
13 changes: 13 additions & 0 deletions lib/pooled-projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -81,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<string> {
const { stdout } = await exec("git", ["-C", cwd, ...args], {
encoding: "utf8",
Expand Down Expand Up @@ -157,6 +167,8 @@ 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.
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 });
Expand Down Expand Up @@ -218,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 });
Expand Down
214 changes: 211 additions & 3 deletions lib/rpc-manager.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1087,14 +1087,222 @@ 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();
// 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();
assert.equal(wrapper.isRunning(), false);
await wrapper.destroyAndWait();
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, its output and its grace window", async (t) => {
const { wrapper, emit, held } = heldPromptSession(t, false);
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 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");

// Between continuation turns pi reports idle; the grace window must still hold the run after a refusal.
emit({ type: "agent_end", isTerminal: false });
const between = wrapper.send({ type: "prompt", message: "between turns" });
held[1].reject(new Error(REFUSAL));
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 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" });
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 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);

// 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");

// 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 b2 = later.wrapper.send({ type: "prompt", message: "b" });
later.emit({ type: "agent_end", isTerminal: true });
const c2 = later.wrapper.send({ type: "prompt", message: "c" });
later.held[1].resolve({ agentInvoked: true });
await c2;
later.held[0].reject(new Error(REFUSAL));
await assert.rejects(b2, /already processing/);
assert.equal((await later.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited");
});

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("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);
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(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) => {
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 {};
});
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) => {
let sessionId = "identity-before";
const { wrapper, emit } = snapshotSession(t, async (command) => {
Expand Down Expand Up @@ -1242,14 +1450,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);
Expand Down
Loading
Loading