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(agent-runtime): keep restored tool calls on their assistant across system rows
Ali Teshnizif1778a19364a
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex e1c7441a7..3ac749981 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -790,7 +790,10 @@ criterion-by-criterion report of what was met and the evidence observed.instead of collapsing to bare chat text (D127). An interrupted tool rowrestores as an errored result; a tool row whose assistant row was lostgets a synthesized call-only assistant carrier so call/result pairs stay- well-formed for every provider API.+ well-formed for every provider API. A model system record saved while a+ call ran restores between that call and its result without ending the+ assistant's calls, so the call stays on the assistant that made it, as in+ the live request.Vision runtimes hydrate persisted image refs only from the session-boundattachment, scratch, and project roots. Each image remains subject to the 10 MBsafety bound, and restored history has a 30 MB aggregate raw-byte budget.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 7459ee380..e7ab96716 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -10038,6 +10038,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.| F — Persistence (stored model binding array) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry || Quality (stored model binding array) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry || Quality (unique tool-call ids) | E2E-RUNTIME-unique-tool-call-ids-per-request |+| C — Conversation & stream (system update during a tool call, restored) | E2E-RUNTIME-system-update-during-tool-call-restore |+| Quality (system update during a tool call, restored) | E2E-RUNTIME-system-update-during-tool-call-restore || C — Conversation & stream (loop context ownership) | E2E-RUNTIME-loop-context-ownership || Quality (loop context ownership) | E2E-RUNTIME-loop-context-ownership || G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |@@ -17116,6 +17118,31 @@ the latest destination. These assertions measure work counts, not device FPS.- **Status:** Unit-covered; no end-to-end driver issues a real provider requestagainst a duplicated transcript.+### E2E-RUNTIME-system-update-during-tool-call-restore++- **Preconditions:** A session transcript with a model system record saved+ while a tool call ran: it sits after the assistant row that made the call and+ before that call's tool row (`beforeMessageId` is the tool row id). Loaded+ into a recreated runtime against a deterministic Anthropic Messages fixture+ with mid-conversation system messages enabled. No real provider credentials.+- **Steps:** Send one prompt so the runtime assembles and issues a request. Read+ the outgoing request body the fixture received.+- **Expected:** The tool call stays on the assistant message that made it,+ next to that message's text, and no call-only assistant is synthesized. Every+ mid-conversation `system` message follows a `user` message, so the provider+ does not answer `role 'system' must follow a 'user' message or an 'assistant'+ message ending in a server tool result`.+- **Specs:** `03-runtime/02-agent-runtime.md` §5c and §7.0.0,+ `08-meta/decisions-log.md` D127.+- **Acceptance:** C (conversation and stream), Quality.+- **Milestone:** Post-MVP regression coverage.+- **Automation:** `packages/agent-runtime/src/system-transcript-runtime.test.ts`+ restores the rows into a real runtime and passes the captured request through+ Pi's Anthropic adapter.++- **Status:** Unit-covered; no end-to-end driver restores such a transcript+ against an Anthropic provider fixture.+### E2E-RUNTIME-loop-context-ownership- **Preconditions:** A deterministic provider fixture that answers the first twodiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 082c510d7..bc62d1abc 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -595,7 +595,8 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo而不是折叠成裸露的聊天文本(D127)。中断的刀具行恢复为错误结果;辅助行丢失的工具行获得合成的仅呼叫辅助运营商,以便 call/result 对保留-格式良好,适用于每个提供商 API。+格式良好,适用于每个提供商 API。工具执行期间保存的模型系统记录恢复在该调用与其结果之间,+ 不会结束助手的调用,因此调用仍挂在发出它的助手消息上,与实时请求一致。- 每个请求里的工具调用 id 必须唯一。转录是仅追加的快照流,容忍重试造成的重复追加,因此同一次调用可能两次进入组装后的上下文——同一个行 id(宿主按 keep-last 读取时已折叠),或者两个不同的行 id(宿主无法折叠)。因此上线前的最后一个视图对每个 `toolCall` id 只保留第一次出现,丢弃其后重复的调用或结果,使提供商校验的「一调用一结果」配对保持完整;没有重复的diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 44a7404d2..be3e89e1c 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5807,6 +5807,8 @@ eleven-tool-round desktop paths are verified by| C / F / 品质 —— 上下文估算保持安全(校准) | E2E-CONTEXT-estimate-calibration-stays-safe || C — 对话与流式(工具调用 id 唯一) | E2E-RUNTIME-unique-tool-call-ids-per-request || 品质(工具调用 id 唯一) | E2E-RUNTIME-unique-tool-call-ids-per-request |+| C — 对话与流式(工具执行期间的系统更新恢复) | E2E-RUNTIME-system-update-during-tool-call-restore |+| 品质(工具执行期间的系统更新恢复) | E2E-RUNTIME-system-update-during-tool-call-restore || C — 对话与流式(循环上下文归属) | E2E-RUNTIME-loop-context-ownership || 品质(循环上下文归属) | E2E-RUNTIME-loop-context-ownership || G — 插件宿主生命周期(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |@@ -9126,6 +9128,19 @@ Follow the [current S3 acceptance scenario](/spec/06-delivery/04-e2e-test-plan#e- **状态:** 单元测试覆盖;没有端到端驱动对重复转录发出真实提供商请求。+### E2E-RUNTIME-system-update-during-tool-call-restore++- **先决条件:** 一份会话转录,其中一条模型系统记录在工具调用执行期间保存:位于发出该调用的助手行之后、该调用的工具行之前+ (`beforeMessageId` 为工具行 id)。在启用对话中途系统消息的确定性 Anthropic Messages 夹具下加载进重新创建的运行时;不使用真实凭据。+- **步骤:** 发一条提示,使运行时组装并发出请求。读取夹具收到的出站请求体。+- **预期:** 工具调用仍挂在发出它的助手消息上、紧随该消息的文本,不合成只含调用的助手消息。每条对话中途的 `system` 消息都跟在+ `user` 消息之后,因此提供商不会回 `role 'system' must follow a 'user' message or an 'assistant' message ending in a server tool result`。+- **规格:** 03-runtime/02-agent-runtime §5c 与 §7.0.0、08-meta/decisions-log D127。**验收:** C(对话与流)、品质。+ **里程碑:** Post-MVP 回归覆盖。+- **自动化:** `packages/agent-runtime/src/system-transcript-runtime.test.ts` 把这些行恢复进真实运行时,并把捕获的请求交给 Pi 的 Anthropic 适配器。++- **状态:** 单元测试覆盖;没有端到端驱动对 Anthropic 提供商夹具恢复这类转录。+### E2E-RUNTIME-loop-context-ownership- **先决条件:** 一个确定性提供商夹具:前两轮各回一次工具调用,并在第二轮之后像用户 Stop 那样结束回合;不使用真实凭据。diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex b85d50697..351dc79bf 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -3052,7 +3052,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (m.parentToolCallId) continue;const timestamp = Date.parse(m.createdAt) || Date.now();if (m.role === "system" && m.modelSystem) {- toolCarrier = undefined;+ // An update recorded while a tool ran sits between the call and its+ // result. It keeps the carrier: Pi holds the update until the results+ // are written, which is the shape the live request had.append(m.id, this.systemJournal.restore(m));} else if (m.role === "user") {toolCarrier = undefined;diff --git a/packages/agent-runtime/src/system-transcript-runtime.test.ts b/packages/agent-runtime/src/system-transcript-runtime.test.tsindex 15ced3662..3e724fd13 100644--- a/packages/agent-runtime/src/system-transcript-runtime.test.ts+++ b/packages/agent-runtime/src/system-transcript-runtime.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import type { Agent } from "@earendil-works/pi-agent-core";-import { createAssistantMessageEventStream, getCurrentTools, getCurrentSystemPrompt, type AssistantMessage, type Message } from "@earendil-works/pi-ai";+import { createAssistantMessageEventStream, getCurrentTools, getCurrentSystemPrompt, normalizeContext, type AssistantMessage, type Message } from "@earendil-works/pi-ai";+import { streamSimple as streamAnthropic } from "@earendil-works/pi-ai/api/anthropic-messages";import type { UiMessage } from "@pi-desktop/shared";import { DesktopAgentRuntime, type RuntimeProviderConfig } from "./runtime.js";@@ -103,6 +104,49 @@ describe("system state through the Desktop user path", () => {} finally { await f.runtime.dispose(); }});+ it("keeps a restored tool call on its assistant when system state changed during the call", async () => {+ // An update made while a tool runs is recorded after the assistant row and before the tool row.+ const createdAt = new Date().toISOString();+ const update = { role: "system", content: "", sections: { context: "Updated while the tool ran" }, timestamp: 2 };+ const f = fixture([+ { id: "user-1", role: "user", content: "Read the notes", createdAt, status: "complete" },+ { id: "assistant-1", role: "assistant", content: "Checking.", createdAt, status: "complete" },+ { id: "call-1", role: "tool", content: "", createdAt, status: "complete", toolCallId: "call-1", toolName: "Read",+ toolArgs: { path: "notes.md" }, toolStatus: "success", toolResult: { content: [{ type: "text", text: "notes" }] } },+ { id: "update-1", role: "system", content: "", createdAt, modelSystem: {+ version: 1, messageJson: JSON.stringify(update), beforeMessageId: "call-1", afterMessageId: "assistant-1",+ } },+ { id: "assistant-2", role: "assistant", content: "Read it.", createdAt, status: "complete" },+ ]);+ try {+ await f.prompt("user-2");+ let body: { messages: { role: string; content: unknown }[] } | undefined;+ await streamAnthropic({+ id: "claude-fixture", name: "Claude fixture", api: "anthropic-messages", provider: "anthropic",+ baseUrl: "http://localhost", reasoning: false, input: ["text"], contextWindow: 100_000, maxTokens: 1000,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, compat: { supportsMidConvoSystemMessages: true },+ }, normalizeContext({ messages: f.requests[0] }), {+ apiKey: "test", maxRetries: 0, fetch: async (_input, init) => {+ body = JSON.parse(String(init?.body));+ return new Response(+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","model":"claude-fixture","usage":{"input_tokens":1,"output_tokens":0}}}\n\nevent: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n',+ { headers: { "content-type": "text/event-stream" } },+ );+ },+ }).result();+ const wire = body!.messages;+ expect(wire.find((message) => message.role === "assistant")?.content).toEqual([+ expect.objectContaining({ type: "text", text: "Checking." }),+ expect.objectContaining({ type: "tool_use", id: "call-1" }),+ ]);+ // Anthropic rejects a later system message unless a user turn precedes it.+ const preceding = wire.flatMap((message, index) => message.role === "system" ? [wire[index - 1]?.role] : []);+ expect(JSON.stringify(wire)).toContain("Updated while the tool ran");+ expect(preceding.length).toBeGreaterThan(0);+ expect(preceding.filter((role) => role !== "user")).toEqual([]);+ } finally { await f.runtime.dispose(); }+ });+it("stops before provider dispatch when the Host cannot save system state", async () => {const f = fixture();f.failPersistence();