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): suppress recoverable overflow error cards
joyawang6d2ca96981aa
diff --git a/apps/desktop/test/context-compaction.test.mjs b/apps/desktop/test/context-compaction.test.mjsindex cb4bd3399..0a61bf63f 100644--- a/apps/desktop/test/context-compaction.test.mjs+++ b/apps/desktop/test/context-compaction.test.mjs@@ -101,6 +101,15 @@ test("the hard boundary is enforced by the host, with a model-side escape hatch"/checkpoint truncated: this message crossed the retained context budget/,);assert.match(runtime, /pendingOverflow/);+ assert.match(runtime, /overflowRecoveryInProgress/);+ assert.match(+ runtime,+ /const canRecoverOverflow =[\s\S]*?status: "streaming"[\s\S]*?message_update[\s\S]*?this\.pendingOverflow = true;/,+ );+ assert.match(+ runtime,+ /CONTEXT_COMPACTION_FAILED[\s\S]*?finalizeCurrentAssistant\("error", error\)/,+ );assert.match(runtime, /runCompaction\(\s*"overflow",\s*true,\s*"active_turn",?\s*\)/);assert.match(runtime, /fallback: "retained_tail"/);// Codex's tool, verbatim and parameterless, plus its two-tier reminder.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a2da35f07..a925c1896 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6233,8 +6233,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.before a checkpoint boundary drops that record specifically; recordsanchored on surviving messages are preserved/remapped.- The exact provider overflow removes only the failed assistant from model- context, retries once after compaction, and does not loop on a second- overflow.+ context, keeps the visible assistant bubble in a running state while+ compaction/retry is pending, retries once after compaction, and does not+ loop on a second overflow. A recoverable first overflow emits no terminal+ error message or `error` event; only a failed retry (or failed compaction)+ closes the bubble with `CONTEXT_TOO_LARGE` / the actual terminal error.- If automatic summary generation fails, a durable retained-tail fallbackcheckpoint is appended, the run stays active, and one warning explainsthat older model context was reduced; the transcript row for thatdiff --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 4e8caff87..07ee1ad14 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@@ -3654,8 +3654,9 @@ IPC 请求无法关闭。压缩行仍被绘制。检查点之前的 regenerate/fork 具体记录的边界被丢弃;以幸存消息为锚点的记录被保留/重新映射。- 确切的提供程序溢出仅从模型中删除失败的助手- 上下文,压缩后重试一次,并且不会在第二次循环- 溢出。+ 上下文;压缩/重试等待期间,界面保留同一个助手气泡并保持运行态;+ 压缩后只重试一次,第二次溢出不循环。第一次可恢复溢出不发终态错误消息或+ `error` 事件;只有重试/压缩失败时才以 `CONTEXT_TOO_LARGE` 或真实终态错误收口。- 如果自动摘要生成失败,则持久保留尾部回退附加检查点,运行保持活动状态,并有一个警告解释旧模型上下文被减少;该检查点的转录行显示diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 2f4dc3fe8..f0b06014e 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -4183,7 +4183,7 @@ describe("DesktopAgentRuntime assistant thinking events", () => {await runtime.dispose();});- it("recognizes the Bedrock prompt-too-long response and defers the terminal error", async () => {+ it("keeps recoverable overflow streaming while compaction is pending", async () => {const onEvent = vi.fn();const runtime = createRuntime({ onEvent });const handleAgentEvent = (runtime as any).handleAgentEvent.bind(runtime);@@ -4206,6 +4206,124 @@ describe("DesktopAgentRuntime assistant thinking events", () => {await 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 () => {+ 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",+ });++ agent.prompt = vi.fn(async () => {+ 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 () => {+ expect((runtime as any).overflowRecoveryInProgress).toBe(true);+ expect(agent.state.messages.filter((message: any) => message.role !== "system")).toEqual([user]);+ 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",@@ -4215,9 +4333,12 @@ describe("DesktopAgentRuntime assistant thinking events", () => {}),}),);- 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);+ expect(events).toContainEqual(+ expect.objectContaining({+ type: "error",+ error: expect.objectContaining({ code: "CONTEXT_TOO_LARGE" }),+ }),+ );await runtime.dispose();});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 51745e99a..33b63019b 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1807,6 +1807,7 @@ export class DesktopAgentRuntime {private pendingSteering = new Map<AgentMessage, string>();private pendingOverflow = false;private overflowRecoveryAttempted = false;+ private overflowRecoveryInProgress = false;private suppressOverflowRunEnd = false;private turnHadError = false;/** Bumped at the start of each parent `prompt()` / `executeApprovedPlan()`. */@@ -5823,6 +5824,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate resetRunRecoveryState(): void {this.pendingOverflow = false;this.overflowRecoveryAttempted = false;+ this.overflowRecoveryInProgress = false;this.suppressOverflowRunEnd = false;this.pendingProviderRetry = undefined;this.providerTransientRetryAttempt = 0;@@ -5982,39 +5984,43 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.pendingOverflow = false;this.suppressOverflowRunEnd = false;this.overflowRecoveryAttempted = true;- const messages = [...this.agent.state.messages];- while (messages.at(-1)?.role === "assistant") messages.pop();- 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();+ 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,- },- });- return false;+ } satisfies ReturnType<typeof classifyAgentError>;+ this.finalizeCurrentAssistant("error", error);+ this.emit({ type: "error", error });+ return false;+ }+ this.turnHadError = false;+ this.requestStartedAt = Date.now();+ await this.agent.continue();+ await this.waitForIdleAndSteering();+ } finally {+ this.overflowRecoveryInProgress = false;}- this.turnHadError = false;- this.requestStartedAt = Date.now();- await this.agent.continue();- await this.waitForIdleAndSteering();continue;}if (this.pendingSilentTurnRerun) {@@ -7406,6 +7412,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (this.steeringContinuation) break;if (this.providerRetryInProgress ||+ this.overflowRecoveryInProgress ||this.silentTurnRerunInProgress ||this.progressTurnRerunInProgress) {@@ -7416,6 +7423,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thecase "turn_start":if (this.providerRetryInProgress ||+ this.overflowRecoveryInProgress ||this.silentTurnRerunInProgress ||this.progressTurnRerunInProgress) {@@ -7430,6 +7438,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst content = assistantContent((event.message as any).content);const retryingAssistant =this.providerRetryInProgress ||+ this.overflowRecoveryInProgress ||this.silentTurnRerunInProgress ||this.progressTurnRerunInProgress? this.currentAssistant@@ -7437,7 +7446,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst initialText =content.hasText && content.text.length > 0? content.text- : this.progressTurnRerunInProgress+ : this.progressTurnRerunInProgress || this.overflowRecoveryInProgress? retryingAssistant?.content ?? "": content.text;this.currentAssistant = {@@ -7458,6 +7467,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// duplicate error row when the second request succeeds. The same// applies to a silent-turn re-run: one bubble, no empty row.this.providerRetryInProgress = false;+ this.overflowRecoveryInProgress = false;this.silentTurnRerunInProgress = false;this.progressTurnRerunInProgress = false;this.emit({ type: "message_update", message: this.currentAssistant });@@ -7719,6 +7729,33 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.streamStartedAt = undefined;break;}+ const canRecoverOverflow =+ this.compactionEnabled &&+ overflow &&+ !this.overflowRecoveryAttempted;+ if (canRecoverOverflow) {+ // Keep the failed response inside the same visible assistant bubble+ // while compaction prepares the retry. A provider overflow is an+ // internal recovery transition, not a terminal user-facing error.+ this.currentAssistant = {+ ...this.currentAssistant,+ content: nextText,+ ...(nextThinking+ ? { thinking: nextThinking }+ : content.hasThinking+ ? { thinking: undefined }+ : {}),+ status: "streaming",+ modelId: this.provider.modelId,+ providerId: this.provider.id,+ ...(usage ? { usage } : {}),+ };+ this.emit({ type: "message_update", message: this.currentAssistant });+ this.streamStartedAt = undefined;+ this.pendingOverflow = true;+ this.suppressOverflowRunEnd = true;+ break;+ }const emptyResponse = silentTurn;const diagnosticError = classifiedError;const retryProviderAttempt =@@ -7790,10 +7827,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.activeProviderRetryAttempt = 0;this.streamStartedAt = undefined;this.currentAssistant = undefined;- const canRecoverOverflow =- this.compactionEnabled &&- overflow &&- !this.overflowRecoveryAttempted;if (exemptSilence) {// Accepted silence is still nothing worth resending: keep it out// of the runtime entries, exactly as a restored transcript would,@@ -7810,10 +7843,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the} else {this.turnHadError = true;}- if (canRecoverOverflow) {- this.pendingOverflow = true;- this.suppressOverflowRunEnd = true;- } else if (diagnosticError) {+ if (diagnosticError) {this.terminateParentTurn();this.emit({ type: "error", error: diagnosticError });}