Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(runtime): own turns before file capability negotiation

cauliflowerbdc35fa126b4
diff --git a/apps/desktop/test/sidecar-history-restore.test.mjs b/apps/desktop/test/sidecar-history-restore.test.mjs
index 290375c28..dca42fb17 100644
--- a/apps/desktop/test/sidecar-history-restore.test.mjs
+++ b/apps/desktop/test/sidecar-history-restore.test.mjs
@@ -23,6 +23,11 @@ test("history restore failures cannot accept a clean prompt for stable or legacy
lines.on("line", (line) => {
const value = JSON.parse(line);
if (value.method === "host.proxy") {
+ if (value.params.method === "tools.fileBatchCapabilities") {
+ assert.equal(restoreFailure, "empty", "capability negotiation must follow successful history restoration");
+ send({ id: value.id, result: { version: 1, supported: false } });
+ return;
+ }
assert.equal(value.params.method, "session.get");
if (restoreFailure === "host") send({ id: value.id, error: { code: -32000, message: "corrupted persisted history", data: { errorCode: "HISTORY_CORRUPT" } } });
else if (restoreFailure === "empty") send({ id: value.id, result: { session: { messages: [] } } });
diff --git a/crates/host-core/src/file_resources.rs b/crates/host-core/src/file_resources.rs
index 94b954694..7315c8c39 100644
--- a/crates/host-core/src/file_resources.rs
+++ b/crates/host-core/src/file_resources.rs
@@ -70,7 +70,22 @@ impl FileResources {
// Execution still reports the original permission/path/I/O failure.
return Self::fence(exclusive);
};
- let Ok(file) = File::open(&address) else {
+ // Classification must never wait for a FIFO reader/writer or open a
+ // device. Recheck the opened object as the binding can change here.
+ if !std::fs::metadata(&address).is_ok_and(|metadata| metadata.is_file()) {
+ return Self::fence(exclusive);
+ }
+ #[cfg(unix)]
+ let opened = {
+ use std::os::unix::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NONBLOCK)
+ .open(&address)
+ };
+ #[cfg(not(unix))]
+ let opened = File::open(&address);
+ let Ok(file) = opened else {
return Self::fence(exclusive);
};
let Ok(metadata) = file.metadata() else {
@@ -264,4 +279,32 @@ mod tests {
)
.is_err());
}
+
+ #[cfg(unix)]
+ #[test]
+ fn fifo_identity_classification_does_not_wait_for_a_writer() {
+ use std::os::unix::ffi::OsStrExt;
+ use std::os::unix::fs::OpenOptionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let fifo = dir.path().join("pipe");
+ let name = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap();
+ assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);
+ let root = dir.path().to_owned();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let worker = std::thread::spawn(move || {
+ let resource = claims(&root, "Write", "pipe");
+ tx.send(resource.identity.is_none()).unwrap();
+ });
+ let result = rx.recv_timeout(std::time::Duration::from_secs(2));
+ // Unblock a regressed O_RDONLY open before joining, so a failing test
+ // cannot strand the test process on a FIFO indefinitely.
+ let _unblock = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .custom_flags(libc::O_NONBLOCK)
+ .open(&fifo)
+ .unwrap();
+ worker.join().unwrap();
+ assert!(result.unwrap());
+ }
}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 2f622b309..ada617d77 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -643,6 +643,22 @@ function assistantMessage(overrides: {
}
describe("parallel file batches", () => {
+ it("owns the turn during capability negotiation and honors Stop before provider dispatch", async () => {
+ let release: (value: unknown) => void = () => {};
+ const capability = new Promise((resolve) => { release = resolve; });
+ const runtime = createRuntime({ host: { call: vi.fn((method: string) => method === "tools.fileBatchCapabilities" ? capability : Promise.resolve(undefined)) } });
+ const agent = (runtime as unknown as { agent: Agent }).agent;
+ const prompt = vi.spyOn(agent, "prompt").mockResolvedValue();
+ const pending = runtime.prompt("Wait for capabilities", undefined, "held-capability-turn");
+ expect(runtime.getStatus()).toMatchObject({ currentTurnId: "held-capability-turn", isRunning: true });
+ const stopping = runtime.abort();
+ release({ version: 1, supported: true });
+ await pending.catch(() => undefined);
+ await stopping;
+ expect(prompt).not.toHaveBeenCalled();
+ expect(runtime.getStatus().isRunning).toBe(false);
+ await runtime.dispose();
+ });
it.each([false, true])("keeps hard-link aliases ordered without Host identity support (write first: %s)", async (writeFirst) => {
const root = await mkdtemp(join(tmpdir(), "pi-batch-alias-"));
await writeFile(join(root, "actual.txt"), "before");
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 5f75e5892..44b7f932d 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -9199,9 +9199,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
userMessageId: string | undefined,
durableTurnId: string,
): Promise<{ turnId: string }> {
- await this.batchPlanner.negotiate(Boolean(this.remoteWorkspace));
- this.rebuildToolCatalog();
- this.setAgentTools(this.activeTools());
const selectedTools = this.selectedMcpTools(input);
const modelInput = typeof input !== "string" && input.sessionMessage
? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }
@@ -9215,11 +9212,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.turnSubagentUsage = undefined;
// Capabilities and path-scoped instruction claims belong to one prompt.
this.subagentOverrideProviders = {};
- this.resetDeferredToolsForPrompt();
- if (selectedTools.length) {
- this.activateDeferredTools(selectedTools);
- this.setAgentTools(this.activeTools());
- }
this.pathInstructionClaims.clear();
this.pendingUserMessageId = userMessageId;
this.resetRunRecoveryState();
@@ -9237,6 +9229,14 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.requestStartedAt = Date.now();
this.setAgentActivity({ phase: "starting", since: Date.now() });
try {
+ // Publish turn ownership before the first await. Status polling and Stop
+ // must include capability negotiation, not observe a falsely idle turn.
+ await this.batchPlanner.negotiate(Boolean(this.remoteWorkspace));
+ if (this.runCancelled || this.disposed) throw turnAbortedError("Turn aborted during Host capability negotiation");
+ this.rebuildToolCatalog();
+ this.resetDeferredToolsForPrompt();
+ if (selectedTools.length) this.activateDeferredTools(selectedTools);
+ this.setAgentTools(this.activeTools());
const content = promptContent(modelInput);
const incomingUserMessage: AgentMessage = {
role: "user",