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): reconcile overflow recovery with system updates
zszz3ea990d745240
diff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex 1407badc2,9bf080ab8..a0d2af6ef--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -16279,69 -16346,3 +16346,75 @@@ renderer's durable transcript reads. N- Installed Electron, real account/paid API and cross-version rollback areseparate release qualification. No MCP, Codemode or virtual-router migrationis included. See `docs/project/pi-0991-adoption.md` for candidate evidence.++### E2E-SYSTEM-TRANSCRIPT: Ordered model state survives restart and compaction++- Fixture: isolated Host data directory, production AgentSidecar transport and+ separate Node runtime/Pi process, local SSE provider; no real provider+ credentials or user's Desktop process. The harness persists completed+ messages; it does not exercise Electron's UI or persistence outbox.+- Send a prompt, activate BrowserPreview through ToolSearch, and verify the next+ request includes the schema. Confirm the baseline and delta are acknowledged+ by Host and survive stopping/restarting both processes without duplicate rows.+- Resume the session, update a skill catalog on the same runtime, and confirm the+ next request uses the new catalog while keeping a second unchanged entry.+ Runtime/adapter tests verify the native delta contains only the modified entry,+ and fallback models receive the complete current catalog with removals applied.+ Invoke Skill through the actual sidecar+ bridge with a fixture body supplied by the embedding host. Compact, restart+ the sidecar, and verify current skills and active tools survive without+ replaying old tool results. Remove the final skill and verify its catalog and+ executable schema disappear without recreating the runtime.+- Automated: `node scripts/e2e-system-transcript.mjs` with+ `PI_DESKTOP_HOST_BIN` pointing to the candidate Host binary. Requires built+ shared/host-runtime/agent-runtime packages. Renderer projection tests ensure+ model-state records stay hidden while ordinary system notices remain visible.+- Adapter contract tests cover exact model/API/endpoint capability binding,+ partial support, unverified relay fallback, removals/redefinitions and model+ switching without canonical-history mutation. Real cache-hit improvement is+ a separately authorized provider experiment, not an offline-test claim.++- Flash regression: load the pinned Pi `deepseek-flash` model, serialize its+ Desktop projection, and pass skill updates/removals through the real adapter.+ The official binding preserves the earlier wire prefix; changed bindings+ retain the folded fallback. Covered by `flash-transcript.test.ts`.+- Authorized live Flash acceptance: use isolated development sessions with+ short and long contexts. Alternate unchanged turns and single-skill updates,+ confirm current Skill bodies execute, and compare actual outgoing prefixes+ plus reported usage. After restart, verify no duplicate system updates and+ same-model assistant reasoning remains separate from visible content. Adapter+ regressions also cover legacy identities and genuine account/model changes. Cache+ percentages are observations, not deterministic pass thresholds.++### E2E-FIXED-TOOL-DECLARATIONS: Stable Flash schemas with independent activation++- Fixture: production AgentSidecar and isolated Host, official Pi Flash binding,+ and a child-process fetch boundary redirected to local HTTP/SSE. Credentials+ are dummy values and synthetic tools have no external side effects.+- Prompt, search Alpha, execute Alpha, search Beta and execute Beta. HTTP payload+ tests assert identical ordered `tools` and unchanged prior message prefixes.+ Directly calling a declared but inactive tool must fail before the Host.+- Restart both processes, then compact and restart again: Alpha stays activated,+ Beta remains inactive despite its declaration. Activate Beta, then remove it+ from the catalog and verify it cannot execute. New schema/route epochs must+ not restore old grants. Host rejection and Plan guards remain effective.+- Runtime contracts additionally cover legacy migration, interrupted activation,+ malformed metadata, temporary prompt replacement, deterministic catalog order,+ the 128-tool boundary and insufficient-context fallback.+- Automated: `node scripts/e2e-fixed-tool-declarations.mjs` with built+ shared/host-runtime/agent-runtime and `PI_DESKTOP_HOST_BIN` set to the candidate+ Host binary; `fixed-tool-runtime.test.ts` and `fixed-tool-declarations.test.ts`+ cover HTTP payload and policy contracts. Electron UI/outbox is outside this+ fixture's scope.+- Separately authorized official Flash experiments compare several independent+ on-demand/fixed sessions with the same synthetic catalog and call sequence.+ Record cold requests, both activations, follow-up cache hits/misses and+ cumulative input cost. Report the larger first request and possible short-chat+ cost increase, alongside any longer-conversation benefit. Offline test success+ alone is not evidence of provider cache behavior.++++- Overflow/system-update integration: recover a provider context overflow with++ a system delta after the failed assistant message. Keep that delta, remove the++ failed assistant before compaction, and reuse one visible assistant message++ through successful recovery. Terminal failure and Stop retain their existing++ closure behavior. Covered by the parameterized runtime overflow user-path test.diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex c48a69498,2b4e41fb3..00ad8d8f1--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@@ -9219,30 -9249,3 +9249,36 @@@ the latest destination. These assertion- **验收:** 缓存路径、迁移和清理单测通过;Windows task-candidate 验证应覆盖更新源传输、安装器交接和文件系统行为,且不连接真实发布源。- **里程碑:** M6+- **状态:** 单测和源码契约覆盖(`update-cache.test.mjs`、`auto-update.test.mjs`);仍需 Windows 安装器/E2E 验证。++### E2E-FIXED-TOOL-DECLARATIONS: Stable Flash schemas with independent activation++- Fixture: production AgentSidecar and isolated Host, official Pi Flash binding,+ and a child-process fetch boundary redirected to local HTTP/SSE. Credentials+ are dummy values and synthetic tools have no external side effects.+- Prompt, search Alpha, execute Alpha, search Beta and execute Beta. HTTP payload+ tests assert identical ordered `tools` and unchanged prior message prefixes.+ Directly calling a declared but inactive tool must fail before the Host.+- Restart both processes, then compact and restart again: Alpha stays activated,+ Beta remains inactive despite its declaration. Activate Beta, then remove it+ from the catalog and verify it cannot execute. New schema/route epochs must+ not restore old grants. Host rejection and Plan guards remain effective.+- Runtime contracts additionally cover legacy migration, interrupted activation,+ malformed metadata, temporary prompt replacement, deterministic catalog order,+ the 128-tool boundary and insufficient-context fallback.+- Automated: `node scripts/e2e-fixed-tool-declarations.mjs` with built+ shared/host-runtime/agent-runtime and `PI_DESKTOP_HOST_BIN` set to the candidate+ Host binary; `fixed-tool-runtime.test.ts` and `fixed-tool-declarations.test.ts`+ cover HTTP payload and policy contracts. Electron UI/outbox is outside this+ fixture's scope.+- Separately authorized official Flash experiments compare several independent+ on-demand/fixed sessions with the same synthetic catalog and call sequence.+ Record cold requests, both activations, follow-up cache hits/misses and+ cumulative input cost. Report the larger first request and possible short-chat+ cost increase, alongside any longer-conversation benefit. Offline test success+ alone is not evidence of provider cache behavior.++++- Overflow/system-update integration: recover a provider context overflow with++ a system delta after the failed assistant message. Keep that delta, remove the++ failed assistant before compaction, and reuse one visible assistant message++ through successful recovery. Terminal failure and Stop retain their existing++ closure behavior. Covered by the parameterized runtime overflow user-path test.diff --cc packages/agent-runtime/src/runtime.test.tsindex 111337276,638c3497f..f4d2dec13--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@@ -4078,6 -4252,124 +4250,126 @@@ describe("DesktopAgentRuntime assistanawait handleAgentEvent({ type: "agent_end", messages: [] });const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);+ const messageUpdates = events.filter((event) => event.type === "message_update");+ expect(messageUpdates).toHaveLength(1);+ expect(messageUpdates[0].message).toMatchObject({ status: "streaming" });+ expect(messageUpdates[0].message.error).toBeUndefined();+ expect(events.some((event) => event.type === "message_end")).toBe(false);+ expect(events.some((event) => event.type === "error")).toBe(false);+ expect(events.some((event) => event.type === "agent_end")).toBe(false);+ expect((runtime as any).pendingOverflow).toBe(true);++ await runtime.dispose();+ });+- it("reuses one assistant bubble across a successful overflow recovery", async () => {++ it.each([false, true])("reuses one assistant bubble across overflow recovery (trailing system update: %s)", async (trailingSystem) => {+ const onEvent = vi.fn();+ const runtime = createRuntime({ onEvent });+ const agent = (runtime as any).agent;+ const handleAgentEvent = (runtime as any).handleAgentEvent.bind(runtime);+ const user = { role: "user", content: "hello", timestamp: 1 };+ const failed = {+ ...assistantMessage({+ content: [{ type: "text", text: "partial response" }],+ stopReason: "error",+ }),+ errorMessage: "400: prompt is too long: 1077172 tokens > 1000000 maximum",+ timestamp: 2,+ };+ const recovered = assistantMessage({+ content: [{ type: "text", text: "recovered response" }],+ stopReason: "stop",+ });+++ const systemUpdate = { role: "system", content: "", timestamp: 3, sections: { context_budget: null } };+ agent.prompt = vi.fn(async () => {- agent.state.messages = [user, failed];++ agent.state.messages = [user, failed, ...(trailingSystem ? [systemUpdate] : [])];+ await handleAgentEvent({ type: "message_start", message: failed });+ await handleAgentEvent({ type: "message_end", message: failed });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });+ agent.waitForIdle = vi.fn(async () => undefined);+ (runtime as any).runCompaction = vi.fn(async () => true);+ agent.continue = vi.fn(async () => {+ expect((runtime as any).overflowRecoveryInProgress).toBe(true);+ expect(agent.state.messages.filter((message: any) => message.role !== "system")).toEqual([user]);++ if (trailingSystem) expect(agent.state.messages).toContain(systemUpdate);+ await handleAgentEvent({ type: "agent_start" });+ await handleAgentEvent({ type: "turn_start" });+ await handleAgentEvent({+ type: "message_start",+ message: { role: "assistant", content: [] },+ });+ await handleAgentEvent({ type: "message_end", message: recovered });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });++ await runtime.prompt("hello", "user-1");++ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);+ const messageEvents = events.filter((event) =>+ ["message_start", "message_update", "message_end"].includes(event.type),+ );+ expect(agent.continue).toHaveBeenCalledOnce();+ expect(new Set(messageEvents.map((event) => event.message.id)).size).toBe(1);+ expect(events.filter((event) => event.type === "message_end")).toHaveLength(1);+ expect(events).toContainEqual(+ expect.objectContaining({+ type: "message_end",+ message: expect.objectContaining({+ status: "complete",+ content: "recovered response",+ }),+ }),+ );+ expect(events.some((event) => event.type === "error")).toBe(false);+ expect(events.filter((event) => event.type === "agent_end")).toHaveLength(1);++ await runtime.dispose();+ });++ it("surfaces a terminal error when the overflow retry also exceeds the context", async () => {+ const onEvent = vi.fn();+ const runtime = createRuntime({ onEvent });+ const agent = (runtime as any).agent;+ const handleAgentEvent = (runtime as any).handleAgentEvent.bind(runtime);+ const user = { role: "user", content: "hello", timestamp: 1 };+ const overflowMessage = (timestamp: number) => ({+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage: "400: prompt is too long: 1077172 tokens > 1000000 maximum",+ timestamp,+ });++ agent.prompt = vi.fn(async () => {+ const failed = overflowMessage(2);+ agent.state.messages = [user, failed];+ await handleAgentEvent({ type: "message_start", message: failed });+ await handleAgentEvent({ type: "message_end", message: failed });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });+ agent.waitForIdle = vi.fn(async () => undefined);+ (runtime as any).runCompaction = vi.fn(async () => true);+ agent.continue = vi.fn(async () => {+ const failed = overflowMessage(3);+ await handleAgentEvent({ type: "agent_start" });+ await handleAgentEvent({ type: "turn_start" });+ await handleAgentEvent({+ type: "message_start",+ message: { role: "assistant", content: [] },+ });+ await handleAgentEvent({ type: "message_end", message: failed });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });++ await runtime.prompt("hello", "user-1");++ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);+ expect(events.filter((event) => event.type === "message_start")).toHaveLength(1);+ expect(events.filter((event) => event.type === "message_end")).toHaveLength(1);expect(events).toContainEqual(expect.objectContaining({type: "message_end",diff --cc packages/agent-runtime/src/runtime.tsindex fbb689fd4,40ebe27f9..a3f1cdc62--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@@ -1,5 -1,4 +1,6 @@@+import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";+import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";+ import { planWorkspaceRequiredResult } from "./plan-workspace-error.js";import { accountModelStream } from "./request-usage.js";import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";import { restoreHostedSearchReplay } from "./hosted-search-replay.js";@@@ -6063,27 -6028,28 +6112,27 @@@ Do not invent objections or turn speculthis.pendingOverflow = false;this.suppressOverflowRunEnd = false;this.overflowRecoveryAttempted = true;- const messages = removeTrailingAssistantMessages(this.agent.state.messages);- this.setAgentMessages(messages);- const compacted = await this.runCompaction(- "overflow",- true,- "active_turn",- );- if (!compacted) {- this.terminateParentTurn();- if (this.compactionAborted) {- // The user stopped the turn while the checkpoint was being written.- // That is an aborted turn, not a compaction failure: close it the- // way a stopped stream closes, with no error row.- this.finalizeCurrentAssistant("aborted");- this.emit({ type: "turn_end" });- this.emit({ type: "agent_end", messageIds: [] });- return false;- }- this.emit({- type: "error",- error: {+ this.overflowRecoveryInProgress = true;+ try {- const messages = [...this.agent.state.messages];- while (messages.at(-1)?.role === "assistant") messages.pop();++ const messages = removeTrailingAssistantMessages(this.agent.state.messages);+ this.setAgentMessages(messages);+ const compacted = await this.runCompaction(+ "overflow",+ true,+ "active_turn",+ );+ if (!compacted) {+ this.terminateParentTurn();+ if (this.compactionAborted) {+ // The user stopped the turn while the checkpoint was being written.+ // That is an aborted turn, not a compaction failure: close it the+ // way a stopped stream closes, with no error row.+ this.finalizeCurrentAssistant("aborted");+ this.emit({ type: "turn_end" });+ this.emit({ type: "agent_end", messageIds: [] });+ return false;+ }+ const error = {code: "CONTEXT_COMPACTION_FAILED",message: "Context overflow recovery could not create a checkpoint",retriable: false,