Skip to content

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

fix(agent-runtime): harden continuation recovery

vastsa82ba0c328546
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index b4905bff8..1f2f22ec2 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -5526,8 +5526,9 @@ identify the platform validation still needed.
- Non-429 transient failures share one bounded budget of ten retries after
the initial attempt, for eleven provider attempts total, shared by request
setup and stream delivery. Each retry waits for an abortable bounded
- backoff, removes the failed assistant from model context, and produces no
- duplicate assistant bubble or terminal error notification.
+ backoff, removes the entire failed assistant suffix from model context,
+ and produces no duplicate assistant bubble or terminal error notification. A retry never
+ calls native continuation while an assistant remains the last model message.
- A mid-stream 502 is retried rather than surfacing immediately. The
mixed-phase fixture spends one counter across both phases and makes eleven
attempts in total, not one retry per phase. A complete successful response
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index c751511ef..fc87ab1e8 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -3838,6 +3838,19 @@ describe("DesktopAgentRuntime assistant thinking events", () => {
errorMessage: "terminated",
timestamp: 2,
};
+ const toolUseMessage = {
+ role: "assistant",
+ content: [{ type: "toolCall", id: "call-1", name: "Read", arguments: {} }],
+ stopReason: "toolUse",
+ timestamp: 1,
+ };
+ const toolResultMessage = {
+ role: "toolResult",
+ toolCallId: "call-1",
+ content: [{ type: "text", text: "result" }],
+ isError: false,
+ timestamp: 1,
+ };
const successfulMessage = {
role: "assistant",
content: [{ type: "text", text: "recovered response" }],
@@ -3859,6 +3872,9 @@ describe("DesktopAgentRuntime assistant thinking events", () => {
agent.prompt = vi.fn(async () => {
agent.state.messages = [
{ role: "user", content: "hello", timestamp: 1 },
+ toolUseMessage,
+ toolResultMessage,
+ failedMessage,
failedMessage,
];
await handleAgentEvent({ type: "message_start", message: failedMessage });
@@ -3868,7 +3884,8 @@ describe("DesktopAgentRuntime assistant thinking events", () => {
});
agent.waitForIdle = vi.fn(async () => undefined);
agent.continue = vi.fn(async () => {
- expect(agent.state.messages.filter((message: any) => message.role !== "system")).toHaveLength(1);
+ expect(agent.state.messages.filter((message: any) => message.role !== "system")).toHaveLength(3);
+ expect(agent.state.messages.at(-1)?.role).toBe("toolResult");
await handleAgentEvent({ type: "agent_start" });
await handleAgentEvent({ type: "turn_start" });
await handleAgentEvent({
@@ -3900,6 +3917,34 @@ describe("DesktopAgentRuntime assistant thinking events", () => {
await runtime.dispose();
});
+ it("does not continue steering after a recovery becomes pending", async () => {
+ const runtime = createRuntime({ onEvent: vi.fn() });
+ const agent = (runtime as any).agent;
+ agent.state.messages = [
+ { role: "user", content: "hello", timestamp: 1 },
+ { role: "assistant", content: [], timestamp: 2 },
+ ];
+ (runtime as any).acceptingSteering = true;
+ (runtime as any).pendingSteering = new Map([
+ [{ role: "user", content: "steer", timestamp: 3 }, "steer-1"],
+ ]);
+ const continueCalls: number[] = [];
+ agent.waitForIdle = vi.fn(async () => undefined);
+ agent.continue = vi.fn(async () => {
+ continueCalls.push(continueCalls.length + 1);
+ if (continueCalls.length === 1) {
+ (runtime as any).suppressProviderRetryRunEnd = true;
+ return;
+ }
+ throw new Error("Cannot continue from message role: assistant");
+ });
+
+ await expect((runtime as any).waitForIdleAndSteering()).resolves.toBeUndefined();
+
+ expect(continueCalls).toEqual([1]);
+ await runtime.dispose();
+ });
+
it("shares one bounded transient budget across setup and stream phases", async () => {
const runtime = createRuntime({ onEvent: vi.fn() });
const claim = (runtime as any).claimProviderRetry.bind(runtime);
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 894c431d6..9d05eaef4 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -5605,7 +5605,7 @@ Delegation rules:
// agentLoopContinue refuses a transcript ending in an assistant message,
// and this one carries nothing worth resending anyway.
const messages = [...this.agent.state.messages];
- if (messages.at(-1)?.role === "assistant") messages.pop();
+ while (messages.at(-1)?.role === "assistant") messages.pop();
this.setAgentMessages(messages);
const promptBefore = this.agent.state.systemPrompt;
@@ -5656,7 +5656,7 @@ Delegation rules:
this.suppressOverflowRunEnd = false;
this.overflowRecoveryAttempted = true;
const messages = [...this.agent.state.messages];
- if (messages.at(-1)?.role === "assistant") messages.pop();
+ while (messages.at(-1)?.role === "assistant") messages.pop();
this.setAgentMessages(messages);
const compacted = await this.runCompaction(
"overflow",
@@ -5713,7 +5713,7 @@ Delegation rules:
// assistant message. The progress text is already visible in the reused
// bubble, so it must not be sent back as model context.
const messages = [...this.agent.state.messages];
- if (messages.at(-1)?.role === "assistant") messages.pop();
+ while (messages.at(-1)?.role === "assistant") messages.pop();
this.setAgentMessages(messages);
const promptBefore = this.agent.state.systemPrompt;
@@ -7696,6 +7696,15 @@ Delegation rules:
try {
await this.agent.continue();
await this.agent.waitForIdle();
+ // The steering continuation may itself finish with a recoverable
+ // provider/silent/overflow/progress failure. Let runPendingRecoveries
+ // repair that assistant tail before another steering continuation.
+ if (
+ this.suppressOverflowRunEnd ||
+ this.suppressProviderRetryRunEnd ||
+ this.suppressSilentTurnRunEnd ||
+ this.suppressProgressTurnRunEnd
+ ) return;
} finally {
this.steeringContinuation = false;
}
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index e4aca6d57..842e9e256 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -742,6 +742,53 @@ describe("SubagentRun context budget (ADR 0299)", () => {
});
describe("SubagentRun retries before fallback", () => {
+ it("removes every trailing failed assistant before retrying", async () => {
+ const { run } = createRun();
+ const user = { role: "user", content: "task", timestamp: 1 };
+ const toolUse = {
+ ...assistantMessage({ content: [{ type: "toolCall", id: "call-1", name: "Read", arguments: {} }], stopReason: "toolUse" }),
+ };
+ const toolResult = {
+ role: "toolResult",
+ toolCallId: "call-1",
+ content: [{ type: "text", text: "result" }],
+ isError: false,
+ timestamp: 2,
+ };
+ const failed = {
+ ...assistantMessage({ content: [{ type: "text", text: "partial" }], stopReason: "error" }),
+ errorMessage: "stream terminated",
+ };
+ const continued = vi.fn(async () => {
+ if (run.agent.state.messages.at(-1)?.role === "assistant") {
+ throw new Error("Cannot continue from message role: assistant");
+ }
+ });
+ run.agent = {
+ state: { ...run.agent.state, messages: [user, toolUse, toolResult, failed, failed] },
+ continue: continued,
+ waitForIdle: async () => {},
+ };
+ run.pendingProviderRetry = {
+ code: "PROVIDER_ERROR",
+ message: "stream terminated",
+ retriable: true,
+ };
+ run.providerTransientRetryAttempt = 1;
+
+ vi.useFakeTimers();
+ try {
+ const retry = run.retryPendingProviderFailure();
+ await vi.runAllTimersAsync();
+ await retry;
+ } finally {
+ vi.useRealTimers();
+ }
+
+ expect(run.agent.state.messages).toEqual([user, toolUse, toolResult]);
+ expect(continued).toHaveBeenCalledOnce();
+ });
+
it.each([429, 503])("exhausts the shared retry budget before switching after HTTP %s", async (status) => {
const fallback = { ...provider, id: "backup", modelId: "backup-model" };
const { run } = createRun({ fallbackModels: [{ key: "backup/backup-model", provider: fallback }] });
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 8cf018397..60390bc79 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -494,7 +494,9 @@ export class SubagentRun {
if (messages.at(-1)?.role !== "assistant") {
throw new Error("Cannot retry a subagent provider stream without its failed assistant message");
}
- messages.pop();
+ // A failed provider stream can leave more than one assistant row after a
+ // tool round. Remove the entire failed suffix before continuing.
+ while (messages.at(-1)?.role === "assistant") messages.pop();
this.agent.state.messages = messages;
this.providerRetryInProgress = true;
try {