Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(runtime): preserve restored tool pairs across compaction boundaries
Seraph-x4a663eaafb73
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 4ab983de7..70155677e 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -489,6 +489,16 @@ The complete visible transcript and the model context are separate views ofthe same session. A durable checkpoint summarizes older model context whilethe renderer continues to show every original user, assistant, and tool row.+When restoring a checkpoint, tool-call reconstruction respects its+`throughMessageId` boundary. A surviving tool row must not attach its call to+an assistant that the checkpoint removes. Legacy checkpoints can cut through+a tool batch; the surviving rows reconstruct a carrier after the boundary from+their stored call ids, names, and arguments, retaining the original carrier's+provider/model identity and function-call signatures. A call-only assistant+with no remaining content still anchors the checkpoint. This changes only the+model projection: stored history is not rewritten, results are not discarded,+and historical tools are not executed again (issue #2306).+PI-Desktop uses pi-agent-core for the agent loop and stable agent/event/tooltypes, and pi-ai for provider-facing requests and message estimation. Theruntime owns its context projection, LLM-message conversion, token-estimationdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 284bf03e9..1d4aceb69 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -18936,6 +18936,29 @@ the latest destination. These assertions measure work counts, not device FPS.- **Status:** Unit-covered (`context-calibration.test.ts`, including the CJK andboundary cases); desktop E2E pending+### E2E-CONTEXT-restored-checkpoint-tool-pairs++- **Preconditions:** A production sidecar, isolated Host fixture with serialized+ session history/checkpoint, and a loopback Chat Completions gateway that+ rejects tool results without matching preceding calls; no live credentials.+- **Steps:** Restore a checkpoint through an assistant call carrier, then+ through the first of two results. Send two prompts, stop the sidecar, start+ a fresh process and repeat. Compare with a boundary after the full batch and+ a session without a checkpoint.+- **Expected:** All prompts complete. Only post-boundary tool results reach+ the gateway, paired with their original ids, names and arguments; their+ contents survive, historical tools never execute, and the stored fixture+ stays unchanged. Empty call-only boundary rows still apply the summary.+ Signed function calls retain their signatures. A retained-tail carrier is+ deduplicated with the reconstructed call, rather than replayed twice.+- **Automation:** `node scripts/e2e-compaction-restore-tool-pairs.mjs` after+ shared/runtime build and production sidecar bundling. Adapter regressions in+ `compaction-restore-tool-pairs.test.ts` cover empty boundaries, absent+ boundaries, retained tails and signed Gemini calls through public prompts.+- **Specs linked:** `03-runtime/02-agent-runtime.md` §5.1, issue #2306.+- **Limits:** Serialized Host data and the real sidecar/HTTP boundary are+ exercised; this is not a native Windows UI reproduction or a paid-provider run.+### E2E-CONTEXT-reported-occupancy-drives-compaction- **Preconditions:** A production sidecar, isolated Host fixture and localhostdiff --git a/packages/agent-runtime/src/compaction-restore-tool-pairs.test.ts b/packages/agent-runtime/src/compaction-restore-tool-pairs.test.tsnew file mode 100644index 000000000..af761e602--- /dev/null+++ b/packages/agent-runtime/src/compaction-restore-tool-pairs.test.ts@@ -0,0 +1,162 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AgentEventEnvelope, ContextCompactionRecord, UiMessage } from "@pi-desktop/shared";+import { DesktopAgentRuntime } from "./runtime.js";+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import { captureAssistantProviderReplay } from "./assistant-provider-replay.js";++const timestamp = "2026-11-13T00:00:00.000Z";+const history: UiMessage[] = [+ { id: "user", role: "user", content: "Read the two files", createdAt: timestamp, status: "complete" },+ { id: "assistant", role: "assistant", content: "Reading files", createdAt: timestamp, status: "complete" },+ ...["a", "b"].map((id): UiMessage => ({+ id: `tool-${id}`, role: "tool", content: `contents of ${id}`,+ createdAt: timestamp, status: "complete", toolCallId: `call-${id}`,+ toolName: "Read", toolArgs: { path: `${id}.txt` },+ toolResult: { content: `contents of ${id}` }, toolStatus: "success",+ })),+];++type WireMessage = {+ role: string;+ content?: unknown;+ tool_call_id?: string;+ tool_calls?: Array<{ id: string; function: { name: string; arguments: string } }>;+};++function orphanResult(messages: WireMessage[]): string | undefined {+ let pending = new Set<string>();+ for (const message of messages) {+ if (message.role === "tool") {+ if (!message.tool_call_id || !pending.delete(message.tool_call_id)) return message.tool_call_id ?? "missing-id";+ } else {+ pending = new Set(message.tool_calls?.map(call => call.id) ?? []);+ }+ }+ return undefined;+}++afterEach(() => vi.unstubAllGlobals());++describe("restored compaction boundaries preserve tool pairs (#2306)", () => {+ it("preserves function-call signatures when a compacted carrier must be rebuilt", async () => {+ const stored = structuredClone(history);+ stored[1]!.providerReplay = captureAssistantProviderReplay([+ { type: "text", text: stored[1]!.content },+ ...["a", "b"].map(id => ({ type: "toolCall" as const, id: `call-${id}`, name: "Read",+ arguments: { path: `${id}.txt` }, thoughtSignature: Buffer.from(`signature-${id}`).toString("base64") })),+ ]);+ const requests: Array<{ contents: Array<{ role: string; parts: Array<Record<string, unknown>> }> }> = [];+ vi.stubGlobal("fetch", async (_url: unknown, init?: RequestInit) => {+ requests.push(JSON.parse(String(init?.body)));+ return new Response(`data: ${JSON.stringify({ candidates: [{ index: 0,+ content: { role: "model", parts: [{ text: "Done: restored context accepted." }] }, finishReason: "STOP",+ }] })}\n\n`, { headers: { "content-type": "text/event-stream" } });+ });+ const runtime = new DesktopAgentRuntime({+ sessionId: "signed-restore", mode: "agent", thinkingLevel: "off", history: stored,+ compaction: { id: "checkpoint", throughMessageId: "assistant", summary: "Earlier file work",+ retainedTail: [], tokensBefore: 100, createdAt: timestamp },+ provider: { id: "google", name: "Google", vendorKey: "google", modelId: "gemini-3.8-flash",+ apiStyle: "google_generative_ai", baseUrl: "https://generativelanguage.googleapis.com/v1beta",+ apiKey: "fixture-only", supportsReasoning: false, supportedThinkingLevels: ["off"] },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ host: { async call<T>(method: string): Promise<T> {+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;+ if (method === "session.appendMessage") return undefined as T;+ throw new Error(`Unexpected Host call: ${method}`);+ } },+ onEvent: () => {},+ });+ try {+ await runtime.prompt("Continue using the file contents.");+ expect(requests).toHaveLength(1);+ const calls = requests[0]!.contents.flatMap(message => message.parts).filter(part => part.functionCall);+ expect(calls.map(part => part.thoughtSignature)).toEqual([+ Buffer.from("signature-a").toString("base64"), Buffer.from("signature-b").toString("base64"),+ ]);+ } finally { await runtime.dispose(); }+ });++ it.each([+ { throughMessageId: "assistant" },+ { throughMessageId: "tool-a" },+ { throughMessageId: "tool-b" },+ { throughMessageId: undefined },+ { throughMessageId: "missing-boundary" },+ { throughMessageId: "assistant", withRetainedCall: true },+ { throughMessageId: "assistant", emptyAssistant: true },+ ])(+ "continues from $throughMessageId with retained call $withRetainedCall",+ async ({ throughMessageId, withRetainedCall, emptyAssistant }) => {+ const requests: WireMessage[][] = [];+ vi.stubGlobal("fetch", async (_url: unknown, init?: RequestInit) => {+ const { messages } = JSON.parse(String(init?.body)) as { messages: WireMessage[] };+ requests.push(messages);+ if (orphanResult(messages)) return new Response(JSON.stringify({ error: {+ message: "Messages with role 'tool' must be a response to a preceding message with 'tool_calls'",+ type: "invalid_request_error",+ } }), { status: 400, headers: { "content-type": "application/json" } });+ return new Response(`data: ${JSON.stringify({ choices: [{ index: 0,+ delta: { content: "Done: restored context accepted." }, finish_reason: "stop",+ }] })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } });+ });+ const events: AgentEventEnvelope[] = [];+ const retainedCall: AgentMessage = {+ role: "assistant", api: "openai-completions", provider: "fixture", model: "fixture",+ content: ["a", "b"].map(id => ({ type: "toolCall" as const, id: `call-${id}`, name: "Read", arguments: { path: `${id}.txt` } })),+ stopReason: "toolUse", timestamp: 1,+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },+ };+ const checkpoint: ContextCompactionRecord | undefined = throughMessageId ? {+ id: "checkpoint", summary: "Earlier file work", throughMessageId,+ firstKeptMessageId: "user", retainedTail: withRetainedCall ? [retainedCall] : [], tokensBefore: 100,+ details: { retainedTailMode: "completed_turn", ...(withRetainedCall ? { retainedTailShape: "recent_window" } : {}) }, createdAt: timestamp,+ } : undefined;+ const originalHistory = structuredClone(history);+ if (emptyAssistant) originalHistory[1]!.content = "";+ const storedHistory = structuredClone(originalHistory);+ const hostCalls: string[] = [];+ const runtime = new DesktopAgentRuntime({+ sessionId: "restored-session", mode: "agent", thinkingLevel: "off",+ history: originalHistory, compaction: checkpoint,+ provider: {+ id: "fixture", name: "Fixture", modelId: "fixture", apiKey: "fixture",+ apiStyle: "chat_completions", baseUrl: "https://fixture.invalid/v1",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ host: { async call<T>(method: string): Promise<T> {+ hostCalls.push(method);+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;+ if (method === "session.appendMessage") return undefined as T;+ throw new Error(`Unexpected Host call: ${method}`);+ } },+ onEvent: event => events.push(event),+ });+ try {+ await runtime.prompt("Continue using the file contents.");+ await runtime.prompt("Report once more.");+ expect(events.filter(({ event }) => event.type === "error")).toEqual([]);+ expect(requests).toHaveLength(2);+ for (const messages of requests) {+ expect(orphanResult(messages)).toBeUndefined();+ if (throughMessageId && throughMessageId !== "missing-boundary") {+ expect(JSON.stringify(messages)).toContain("Earlier file work");+ expect(JSON.stringify(messages)).not.toContain("Read the two files");+ }+ const expectedIds = throughMessageId === "tool-b" ? []+ : throughMessageId === "tool-a" ? ["call-b"] : ["call-a", "call-b"];+ expect(messages.filter(message => message.role === "tool").map(message => message.tool_call_id)).toEqual(expectedIds);+ for (const id of expectedIds) {+ expect(messages.flatMap(message => message.tool_calls ?? []).find(call => call.id === id)?.function).toEqual({+ name: "Read", arguments: JSON.stringify({ path: `${id.slice(-1)}.txt` }),+ });+ }+ }+ expect(hostCalls).not.toContain("tools.execute");+ expect(originalHistory).toEqual(storedHistory);+ } finally { await runtime.dispose(); }+ },+ );+});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex c1af20d1c..fc18934c7 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -2130,7 +2130,7 @@ export class DesktopAgentRuntime {const runtimeApiKey = providerRequestKey(this.provider);this.transcriptHistory = [...(opts.history ?? [])];- this.fullEntries = this.historyToEntries(this.transcriptHistory);+ this.fullEntries = this.historyToEntries(this.transcriptHistory, opts.compaction?.throughMessageId);this.uniqueToolCalls = createToolCallIdentity(this.fullEntries.map((entry) => entry.message));this.activeCompaction = opts.compaction;this.delegationChains.hydrate(@@ -3123,7 +3123,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the* turns after a restart. Losing either (the pre-D120 tool behavior)* collapsed a reseeded session to bare chat text. Failed assistant turns* stay transcript-only. */- private historyToEntries(history: UiMessage[]): MessageEntry[] {+ private historyToEntries(history: UiMessage[], compactionThroughMessageId?: string): MessageEntry[] {const api = apiBindingForProviderModel(this.provider).api;const deepSeekCompletionsReplay =api === "openai-completions" &&@@ -3151,7 +3151,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when thelet toolCarrier: AssistantMessage | undefined;// Function-call signatures of the carrier's row, restored by call id.let carrierToolSignatures = new Map<string, string>();+ let compactedCarrier: AssistantMessage | undefined;+ let previousRowId: string | undefined;for (const m of orderSystemRows(history)) {+ // A carrier before this boundary is removed by context compaction. Tool+ // rows after it must reconstruct their calls on a surviving carrier.+ if (compactionThroughMessageId && previousRowId === compactionThroughMessageId) {+ compactedCarrier = toolCarrier;+ toolCarrier = undefined;+ }+ previousRowId = m.id;// Subagent rows belong to the transcript and to review, never to the// parent's model context (ADR 0062): the parent only ever saw the `Task`// report, and replaying a delegate's messages would both contradict that@@ -3165,6 +3174,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theappend(m.id, this.systemJournal.restore(m));} else if (m.role === "user") {toolCarrier = undefined;+ compactedCarrier = undefined;const attachments = (m.attachments ?? []).map((attachment) =>runtimeAttachmentFromMessage(attachment,@@ -3184,6 +3194,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theappend(m.id, { role: "user", content, timestamp });} else if (m.role === "assistant") {toolCarrier = undefined;+ compactedCarrier = undefined;// Failed provider responses belong in the transcript for diagnosis,// but must never become model context on the next turn.if (m.status === "error" || m.isError || m.error) continue;@@ -3249,15 +3260,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolCarrier = {role: "assistant",content: [],- api,- provider: this.model.provider,- model: this.model.id,+ api: compactedCarrier?.api ?? api,+ provider: compactedCarrier?.provider ?? this.model.provider,+ model: compactedCarrier?.model ?? this.model.id,usage: usageToPi(undefined),stopReason: "toolUse",timestamp,};append(`${m.id}:carrier`, toolCarrier);- carrierToolSignatures = new Map();+ if (!compactedCarrier) carrierToolSignatures = new Map();+ compactedCarrier = undefined;}const thoughtSignature = carrierToolSignatures.get(m.toolCallId);toolCarrier.content.push({@@ -3273,6 +3285,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}return entries.filter((entry) =>+ // An empty call-only boundary still anchors the persisted checkpoint.+ entry.id === compactionThroughMessageId ||entry.message.role !== "assistant" || entry.message.content.length > 0,);}diff --git a/scripts/e2e-compaction-restore-tool-pairs.mjs b/scripts/e2e-compaction-restore-tool-pairs.mjsnew file mode 100644index 000000000..0626357cb--- /dev/null+++ b/scripts/e2e-compaction-restore-tool-pairs.mjs@@ -0,0 +1,128 @@+/** Production sidecar restart + strict loopback Chat Completions gateway (#2306). */+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";+import { OfflineSidecar, fixtureHost } from "./e2e/hosted-search-sidecar.mjs";++const root = fileURLToPath(new URL("../", import.meta.url));+const { values } = parseArgs({ options: { bundle: { type: "string" } } });+const bundle = values.bundle ? resolve(values.bundle) : join(root, "packages/agent-runtime/dist-bundle/sidecar.js");+const temporary = await mkdtemp(join(tmpdir(), "pi-restored-tool-pairs-"));+const createdAt = "2026-11-13T00:00:00.000Z";++function unpairedResult(messages) {+ let calls = new Set();+ for (const message of messages) {+ if (message.role === "tool") {+ if (!calls.delete(message.tool_call_id)) return true;+ } else calls = new Set((message.tool_calls ?? []).map(call => call.id));+ }+ return false;+}++async function scenario(boundary) {+ const dir = join(temporary, boundary ?? "no-checkpoint");+ await mkdir(dir, { recursive: true });+ const history = [+ { id: "user", role: "user", content: "Read two files", createdAt, status: "complete" },+ { id: "assistant", role: "assistant", content: "Reading", createdAt, status: "complete" },+ ...["a", "b"].map(id => ({+ id: `tool-${id}`, role: "tool", content: `file-${id}-result`, createdAt,+ status: "complete", toolName: "Read", toolCallId: `call-${id}`,+ toolArgs: { path: `${id}.txt` }, toolStatus: "success",+ toolResult: { content: [{ type: "text", text: `file-${id}-result` }] },+ })),+ ];+ const compaction = boundary ? {+ id: "checkpoint", summary: "Earlier file work", throughMessageId: boundary,+ firstKeptMessageId: "user", retainedTail: [], tokensBefore: 100,+ details: { retainedTailMode: "completed_turn" }, createdAt,+ } : undefined;+ // This JSON fixture is the Host persistence boundary, never a user profile.+ const path = join(dir, "persisted-session.json");+ await writeFile(path, JSON.stringify({ messages: history, compaction }));+ const original = await readFile(path, "utf8");+ const requests = [];+ const server = createServer(async (request, response) => {+ let raw = "";+ for await (const chunk of request) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ if (unpairedResult(body.messages)) {+ response.writeHead(400, { "content-type": "application/json" });+ response.end(JSON.stringify({ error: { message: "Messages with role 'tool' must be a response to a preceding message with 'tool_calls'", type: "invalid_request_error" } }));+ return;+ }+ response.writeHead(200, { "content-type": "text/event-stream" });+ response.end(`data: ${JSON.stringify({ choices: [{ index: 0,+ delta: { content: "Done: restored context accepted." }, finish_reason: "stop",+ }] })}\n\ndata: [DONE]\n\n`);+ });+ await new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", resolve);+ });+ let sidecar;+ let toolExecutions = 0;+ const params = {+ sessionId: "restored-session", mode: "agent", thinkingLevel: "off", scratchDir: dir,+ pluginTools: [], pluginSkills: [], trustedExtensions: [],+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ provider: {+ id: "fixture", name: "Fixture", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ modelId: "fixture", apiKey: "fixture-only", apiStyle: "chat_completions",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ },+ };+ try {+ // Two fresh processes each recover the same Host-owned history.+ for (let restart = 0; restart < 2; restart++) {+ const baseHost = fixtureHost();+ const host = async (method, args) => {+ if (method === "session.get") return { session: { id: params.sessionId, ...JSON.parse(await readFile(path, "utf8")) } };+ if (method === "tools.execute") { toolExecutions++; throw new Error("Historical tools must not execute again"); }+ return baseHost(method, args);+ };+ sidecar = await OfflineSidecar.start(bundle, dir, host, 20_000);+ for (const content of ["Continue the file task.", "Report once more."]) {+ const events = await sidecar.prompt(params, content);+ assert.ok(events.some(({ event }) => event.type === "message_end" &&+ event.message.role === "assistant" && event.message.status === "complete" &&+ event.message.content === "Done: restored context accepted."));+ }+ sidecar.check();+ await sidecar.stop();+ sidecar = undefined;+ }+ assert.equal(requests.length, 4);+ const expected = boundary === "tool-b" ? [] : boundary === "tool-a" ? ["call-b"] : ["call-a", "call-b"];+ for (const { messages } of requests) {+ assert.equal(unpairedResult(messages), false);+ if (boundary) {+ assert.ok(JSON.stringify(messages).includes("Earlier file work"));+ assert.ok(!JSON.stringify(messages).includes("Read two files"));+ }+ assert.deepEqual(messages.filter(message => message.role === "tool").map(message => message.tool_call_id), expected);+ for (const id of expected) {+ assert.deepEqual(messages.flatMap(message => message.tool_calls ?? []).find(call => call.id === id)?.function,+ { name: "Read", arguments: JSON.stringify({ path: `${id.slice(-1)}.txt` }) });+ assert.ok(JSON.stringify(messages.find(message => message.tool_call_id === id)?.content).includes(`file-${id.slice(-1)}-result`));+ }+ }+ assert.equal(toolExecutions, 0);+ assert.equal(await readFile(path, "utf8"), original);+ console.log(JSON.stringify({ boundary: boundary ?? "none", restarts: 2, completedTurns: requests.length, passed: true }));+ } finally {+ await sidecar?.stop();+ server.closeAllConnections();+ await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ }+}++try {+ for (const boundary of ["assistant", "tool-a", "tool-b", undefined]) await scenario(boundary);+} finally { await rm(temporary, { recursive: true, force: true }); }