Skip to content

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

fix(agent-runtime): exclude retry backoff from stream idle time

FuYukiH1c339e1f5cd8
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index aaa0bc144..eab8cb2e0 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -214,6 +214,13 @@ server or calculated value is capped at 30 seconds. The runtime captures the
failed response status and headers from fetch because pi-ai's ordinary response
callback only covers an established response.
+The main turn's idle watchdog measures each active provider attempt separately;
+retry backoff is outside that clock. Its default is 180 seconds with no provider
+events. `PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS` keeps the 30-second positive minimum,
+and `0` disables the watchdog. A genuine stall aborts that attempt before recovery
+starts another one. It does not abort the retry loop's user-owned signal or spend
+an additional retry merely because a requested backoff elapsed.
+
Non-429 transient failures share their own bounded response-recovery budget of ten
retries after the initial attempt, for eleven provider attempts total. The budget
is shared by request setup and stream delivery, so a fault that moves between
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 3880debb0..7f57bbb6b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -40,6 +40,23 @@
## 1. Goals
+### E2E-PROVIDER-retry-backoff-is-not-idle
+
+- **Entry:** Build shared and the production sidecar bundle, then run
+ `node scripts/e2e-provider-retry-idle.mjs` (about one minute).
+- **Sequence:** Use the supported 30-second idle setting. Return one HTTP 429
+ with a 30-second retry delay, then succeed. Separately hold an HTTP request
+ silent until its idle deadline, then let the retry succeed. Stop another
+ turn during its rate-limit backoff.
+- **Expected:** The planned wait consumes exactly one retry; the successful
+ follow-up is sent. A real stalled request closes before its replacement
+ begins, and Stop prevents a later retry request.
+- **Coverage:** Real production sidecar, provider adapter and localhost HTTP
+ server with fixture Host responses. Real-clock process checks are supplemented
+ by real Agent-loop tests under a controlled clock, including all ten allowed
+ rate-limit retries and exhaustion after eleven genuinely stalled attempts.
+- **Specs:** `03-runtime/02-agent-runtime.md` provider retry behavior.
+
### E2E-TRANSCRIPT-scroll-interruption
- **Preconditions:** Real Chromium with the production transcript scroll hook;
diff --git a/packages/agent-runtime/src/provider-recovery-flow.test.ts b/packages/agent-runtime/src/provider-recovery-flow.test.ts
index 23d529818..b700b0552 100644
--- a/packages/agent-runtime/src/provider-recovery-flow.test.ts
+++ b/packages/agent-runtime/src/provider-recovery-flow.test.ts
@@ -17,21 +17,36 @@ const provider: RuntimeProviderConfig = {
};
type Failure = "network" | "rate-limit" | "stream";
-type Step = Failure | "tool" | "success";
+type Step = Failure | "tool" | "success" | "stall";
/** Real provider adapter and agent loop; replace only fetch and the host edge. */
-function fixture(steps: Step[]) {
+function fixture(steps: Step[], retryAfterMs = 1) {
let requests = 0;
let reads = 0;
+ let abortedRequests = 0;
+ const startedAborted: boolean[] = [];
const events: AgentEventEnvelope[] = [];
- const fetch = vi.fn(async (): Promise<Response> => {
+ const fetch = vi.fn(async (_input: unknown, init?: RequestInit): Promise<Response> => {
+ startedAborted.push(init?.signal?.aborted === true);
const step = steps[requests++];
if (!step) throw new Error("Unexpected provider request");
+ if (step === "stall") {
+ const signal = init?.signal;
+ if (!signal) throw new Error("The fixture request needs an abort signal");
+ return new Promise<Response>((_resolve, reject) => {
+ const abort = () => {
+ abortedRequests++;
+ reject(new DOMException("Request aborted", "AbortError"));
+ };
+ if (signal.aborted) abort();
+ else signal.addEventListener("abort", abort, { once: true });
+ });
+ }
if (step === "network") throw new TypeError("fetch failed");
if (step === "rate-limit")
return new Response("Rate limited", {
status: 429,
- headers: { "retry-after-ms": "1" },
+ headers: { "retry-after-ms": String(retryAfterMs) },
});
const delta =
step === "tool"
@@ -122,10 +137,11 @@ function fixture(steps: Step[]) {
],
onEvent: (event) => events.push(event),
});
- return { runtime, subagent, events, requests: () => requests, reads: () => reads };
+ return { runtime, subagent, events, requests: () => requests, reads: () => reads,
+ abortedRequests: () => abortedRequests, startedAborted };
}
-async function settle<T>(promise: Promise<T>): Promise<T> {
+async function settle<T>(promise: Promise<T>, seconds = 180): Promise<T> {
let settled = false;
// Attach handlers before advancing clocks so expected terminal rejections
// never become unhandled rejections in the test process.
@@ -136,7 +152,7 @@ async function settle<T>(promise: Promise<T>): Promise<T> {
void observed.then(() => {
settled = true;
});
- for (let tick = 0; tick < 180 && !settled; tick++)
+ for (let tick = 0; tick < seconds && !settled; tick++)
await vi.advanceTimersByTimeAsync(1000);
expect(settled, "run settles inside the bounded recovery window").toBe(true);
const result = await observed;
@@ -146,10 +162,69 @@ async function settle<T>(promise: Promise<T>): Promise<T> {
afterEach(() => {
vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
vi.useRealTimers();
});
describe("provider recovery through real agent loops (#699)", () => {
+ for (const [idleTimeout, failures] of [[180_000, 10], [30_000, 1]] as const) {
+ it(`keeps ${failures} rate-limit waits outside the ${idleTimeout}ms stream idle budget`, async () => {
+ vi.useFakeTimers();
+ vi.stubEnv("PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS", String(idleTimeout));
+ const f = fixture([...Array<Step>(failures).fill("rate-limit"), "success"], 30_000);
+ try {
+ await settle(f.runtime.prompt("Report after the provider becomes available."), 400);
+ expect(f.requests()).toBe(failures + 1);
+ expect(f.events.filter((event) => event.event.type === "error")).toHaveLength(0);
+ expect(f.events.some(({ event }) => event.type === "message_end" &&
+ event.message.content === "Recovered" && event.message.status === "complete")).toBe(true);
+ const attempts = f.events.flatMap(({ event }) =>
+ event.type === "status" && event.status.activity?.phase === "retrying"
+ ? [event.status.activity.attempt] : []);
+ expect(attempts).toEqual(Array.from({ length: failures }, (_, index) => index + 1));
+ } finally {
+ await f.runtime.dispose();
+ }
+ });
+ }
+
+ it("aborts a silent attempt and retries with a fresh request signal", async () => {
+ vi.useFakeTimers();
+ vi.stubEnv("PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS", "30000");
+ const f = fixture(["stall", "success"]);
+ try {
+ await settle(f.runtime.prompt("Recover from a silent provider."));
+ expect(f.requests()).toBe(2);
+ expect(f.abortedRequests()).toBe(1);
+ expect(f.startedAborted).toEqual([false, false]);
+ expect(f.events.filter(({ event }) => event.type === "error")).toHaveLength(0);
+ expect(f.events.some(({ event }) => event.type === "message_end" &&
+ event.message.content === "Recovered" && event.message.status === "complete")).toBe(true);
+ } finally {
+ await f.runtime.dispose();
+ }
+ });
+
+ it("keeps repeated idle timeouts inside the shared retry budget", async () => {
+ vi.useFakeTimers();
+ vi.stubEnv("PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS", "30000");
+ const f = fixture(Array<Step>(11).fill("stall"));
+ try {
+ await settle(f.runtime.prompt("Report."), 450);
+ expect(f.requests()).toBe(11);
+ expect(f.abortedRequests()).toBe(11);
+ const errors = f.events.filter(({ event }) => event.type === "error");
+ expect(errors).toHaveLength(1);
+ expect(errors[0]?.event).toMatchObject({
+ type: "error", error: { code: "STREAM_FAILED", details: { retryAttempt: 10 } },
+ });
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(f.requests()).toBe(11);
+ } finally {
+ await f.runtime.dispose();
+ }
+ });
+
for (const owner of ["session", "subagent"] as const) {
for (const failure of ["network", "rate-limit", "stream"] as const) {
it(`${owner} recovers independent ${failure} outages across eleven successful tool rounds`, async () => {
@@ -235,9 +310,9 @@ describe("provider recovery through real agent loops (#699)", () => {
});
}
- it("cancels the retry wait without opening another provider request", async () => {
+ it.each(["network", "rate-limit"] as const)("cancels a %s retry wait without opening another provider request", async (failure) => {
vi.useFakeTimers();
- const f = fixture(["network"]);
+ const f = fixture([failure], 30_000);
try {
const prompt = f.runtime.prompt("Report.").catch((error) => error);
await vi.waitFor(() =>
@@ -250,7 +325,7 @@ describe("provider recovery through real agent loops (#699)", () => {
);
await f.runtime.abort();
await settle(prompt);
- await vi.advanceTimersByTimeAsync(10000);
+ await vi.advanceTimersByTimeAsync(60_000);
expect(f.requests()).toBe(1);
expect(f.events.filter((e) => e.event.type === "agent_end")).toHaveLength(1);
expect(
diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.ts
index 3c2136a4f..2d86ac355 100644
--- a/packages/agent-runtime/src/provider-retry.test.ts
+++ b/packages/agent-runtime/src/provider-retry.test.ts
@@ -1088,12 +1088,10 @@ describe("stream idle watchdog", () => {
}
});
- it("clamps a positive override up to the retry backoff floor", () => {
+ it("clamps a positive override up to the supported idle minimum", () => {
const previous = process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
try {
- // The watchdog wraps the retry adapter, so a budget under the largest
- // retry delay would end a turn that is backing off exactly as the
- // provider asked it to. `0` still disables it outright.
+ // Keep the existing positive minimum; `0` still disables the watchdog.
process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "1000";
expect(streamIdleTimeoutMs()).toBe(STREAM_IDLE_TIMEOUT_FLOOR_MS);
expect(STREAM_IDLE_TIMEOUT_FLOOR_MS).toBeGreaterThan(1_000);
diff --git a/packages/agent-runtime/src/provider-retry.ts b/packages/agent-runtime/src/provider-retry.ts
index 90d78b0a8..bb13aa0b1 100644
--- a/packages/agent-runtime/src/provider-retry.ts
+++ b/packages/agent-runtime/src/provider-retry.ts
@@ -550,13 +550,10 @@ export function createProviderRetryStream(
export const STREAM_IDLE_TIMEOUT_DEFAULT_MS = 180_000;
/**
- * The smallest idle budget a positive override may set. The watchdog wraps the
- * whole retry adapter, so the backoff wait between two attempts is zero-event
- * time to it: a budget below the largest retry delay would end a turn that is
- * pacing exactly as the provider asked it to. `0` still disables the watchdog
- * outright — this floor only clamps a positive override.
+ * The smallest supported positive idle budget. `0` disables the watchdog;
+ * otherwise the existing 30-second minimum applies to each network attempt.
*/
-export const STREAM_IDLE_TIMEOUT_FLOOR_MS = PROVIDER_RATE_LIMIT_MAX_DELAY_MS;
+export const STREAM_IDLE_TIMEOUT_FLOOR_MS = 30_000;
/**
* `PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS` overrides the zero-event idle budget;
@@ -589,15 +586,9 @@ function streamIdleTimeoutMessage(timeoutMs: number): string {
* socket produces — so the existing transient retry budget picks it up instead
* of adding a second recovery path.
*
- * `onStall` is the caller's chance to *stop* what this watchdog abandons, and a
- * caller that can must pass it. The wrapper sits outside the retry adapter, so
- * `inner` is that adapter: draining it without aborting it lets it wake from a
- * backoff and open a second request for the same turn while the runtime is
- * already re-running the turn — two provider requests and two bills for one
- * answer. Aborting the request's own signal is what makes the adapter's next
- * attempt refuse to start and its backoff sleep reject. The abandoned stream is
- * drained either way, so its queued events are released rather than left to
- * pile up behind a consumer that has stopped reading.
+ * `onStall` stops the abandoned attempt before its caller can retry. Draining
+ * alone does not cancel network work. The abandoned iterator is drained to
+ * release late events, while the retry adapter owns any subsequent backoff.
*/
export function withStreamIdleTimeout(
inner: AssistantMessageEventStream,
@@ -623,9 +614,8 @@ export function withStreamIdleTimeout(
step = await Promise.race([iterator.next(), idle]);
} catch {
clearTimeout(timer);
- // Stop before draining: the abort is what keeps the adapter from
- // starting another request behind the retry the runtime is already
- // running (see the doc comment above).
+ // Stop the abandoned request before exposing the failure to its
+ // retry owner. Draining alone would leave network work running.
onStall?.();
drainAbandonedStream(iterator);
const message = setupErrorMessage(
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index b224f2b0f..2b6a4ea02 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -2301,14 +2301,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
m.api,
this.fastMode,
);
- // The watchdog must be able to *stop* what it abandons. It wraps the
- // retry adapter, so draining alone would let the adapter wake from its
- // backoff and open a second request for this turn while the runtime is
- // already re-running the turn — two provider requests and two bills for
- // one answer. So the stall trips a signal this request owns, combined
- // with pi's own run signal (Stop must keep working): the adapter refuses
- // to start an attempt on an aborted signal, and its backoff sleep rejects.
- const stallAbort = new AbortController();
// Both output clamps, ours and pi-ai's inside `streamSimple`, must see
// the instructions the adapter sends, not every superseded snapshot.
const requestContext = requestTranscript(m, context);
@@ -2320,24 +2312,33 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// `thinkingLevel: "omit"` would otherwise send it untouched, and
// both consume an estimate that under-counts CJK text (issue B).
maxTokens: clampOutputToContext(m, requestContext, hookedOptions.maxTokens),
- signal: AbortSignal.any([
- ...(hookedOptions.signal ? [hookedOptions.signal] : []),
- stallAbort.signal,
- ]),
};
const usageTurnId = this.turnId;
const retryStream = createProviderRetryStream(
m,
requestContext,
attemptOptions,
- (retryOptions) => accountModelStream(m, () =>
- this.thinkingLevel === "omit"
- ? this.models.stream(omitThinkingModel(m), requestContext, retryOptions)
- : this.models.streamSimple(m, requestContext, retryOptions), {
+ (retryOptions) => {
+ // Each network attempt owns its idle clock and abort signal.
+ // Deliberate backoff must not look like a stalled provider stream.
+ const stallAbort = new AbortController();
+ const timedOptions = {
+ ...retryOptions,
+ signal: AbortSignal.any([
+ ...(retryOptions.signal ? [retryOptions.signal] : []),
+ stallAbort.signal,
+ ]),
+ };
+ const stream = accountModelStream(m, () =>
+ this.thinkingLevel === "omit"
+ ? this.models.stream(omitThinkingModel(m), requestContext, timedOptions)
+ : this.models.streamSimple(m, requestContext, timedOptions), {
providerId: this.provider.id,
nativeCost: this.provider.modelConfig?.nativeCost,
onUsage: (usage) => this.emit({ type: "usage", usage }, usageTurnId),
- }),
+ });
+ return withStreamIdleTimeout(stream, m, streamIdleTimeoutMs(), () => stallAbort.abort());
+ },
{
claim: (error, phase) => this.claimProviderRetry(error, phase),
headers: () => this.providerRetryHeaders,
@@ -2355,14 +2356,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
},
},
);
- // Zero-event idle watchdog: a stream that emits nothing for the
- // configured budget ends as a STREAM_FAILED error and re-enters the
- // shared transient retry path instead of hanging the turn on a
- // connection the provider never closes.
- return this.uniqueToolCalls(
- withStreamIdleTimeout(retryStream, m, streamIdleTimeoutMs(), () => stallAbort.abort()),
- context.messages,
- );
+ return this.uniqueToolCalls(retryStream, context.messages);
},
// A vendor account has no long-lived key. Leaving it unset keeps pi-ai
// from overriding the auth the provider just resolved for this request.
diff --git a/scripts/e2e-provider-retry-idle.mjs b/scripts/e2e-provider-retry-idle.mjs
new file mode 100644
index 000000000..5e34b66cf
--- /dev/null
+++ b/scripts/e2e-provider-retry-idle.mjs
@@ -0,0 +1,97 @@
+/** Production sidecar + localhost HTTP: retry waits are not stalled requests. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { mkdir, mkdtemp, rm } 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, isolatedEnv } 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-retry-idle-"));
+const results = [];
+
+async function scenario(mode) {
+ const dir = join(temporary, mode);
+ await mkdir(dir, { recursive: true });
+ let requests = 0, stalledSocketClosed = false, overlapped = false;
+ const server = createServer(async (request, response) => {
+ for await (const _chunk of request) { /* Consume the fixture request body. */ }
+ requests++;
+ if (requests === 1 && mode === "stalled-request") {
+ response.on("close", () => { stalledSocketClosed = true; });
+ return;
+ }
+ if (requests === 1) {
+ response.writeHead(429, { "retry-after-ms": "30000" }).end("Rate limited");
+ return;
+ }
+ if (mode === "stalled-request" && !stalledSocketClosed) overlapped = true;
+ const chunk = (delta, finish) => `data: ${JSON.stringify({ id: "completion", object: "chat.completion.chunk",
+ created: 1, model: "fixture-model", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`;
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.end(chunk({ role: "assistant", content: "Recovered" }, null) + chunk({}, "stop") + "data: [DONE]\n\n");
+ });
+ await new Promise((done) => server.listen(0, "127.0.0.1", done));
+ const baseHost = fixtureHost();
+ const host = (method, params) => method === "plans.abort" ? { ok: true } : baseHost(method, params);
+ const env = await isolatedEnv(dir);
+ env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "30000";
+ const child = spawn(process.execPath, [bundle], { cwd: dir, env, stdio: ["pipe", "pipe", "pipe"] });
+ const sidecar = new OfflineSidecar(child, dir, host, 45_000);
+ sidecar.allowProviderRetries = true;
+ const sessionId = `retry-${mode}`;
+ const turnId = `${sessionId}-turn`;
+ const retries = () => sidecar.events.flatMap(({ event }) =>
+ event.type === "status" && event.status.activity?.phase === "retrying" ? [event.status.activity] : []);
+ try {
+ assert.equal((await sidecar.call("sidecar.health")).ok, true);
+ await sidecar.call("agent.prompt", {
+ sessionId, turnId, userMessageId: `${turnId}-user`, content: "Report when the provider becomes available.",
+ mode: "agent", thinkingLevel: "off", infiniteProviderRetry: false, scratchDir: dir,
+ pluginTools: [], pluginSkills: [], trustedExtensions: [],
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ provider: { id: "fixture", name: "Fixture", modelId: "fixture-model",
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, apiKey: "fixture-only", apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ });
+ if (mode === "abort-backoff") {
+ await sidecar.waitFor(() => retries().length > 0, "rate-limit backoff");
+ await sidecar.call("agent.abort", { sessionId, turnId });
+ }
+ await sidecar.waitFor(() => {
+ const attempts = retries().map((retry) => retry.attempt);
+ assert.ok(attempts.length <= 1 && attempts.every((attempt) => attempt === 1),
+ `idle watchdog charged another retry during backoff: ${JSON.stringify(attempts)}`);
+ return sidecar.events.some((event) => event.turnId === turnId && event.event.type === "agent_end");
+ }, "turn completion");
+ assert.deepEqual(retries().map((retry) => retry.attempt), [1]);
+ assert.equal((await sidecar.call("agent.getStatus", { sessionId })).status.isRunning, false);
+ assert.equal(requests, mode === "abort-backoff" ? 1 : 2);
+ if (mode !== "abort-backoff") {
+ assert.ok([...sidecar.messages.values()].some((message) => message.content === "Recovered"));
+ }
+ if (mode === "stalled-request") {
+ assert.equal(stalledSocketClosed, true, "timed-out attempt was not cancelled");
+ assert.equal(overlapped, false, "retry overlapped the abandoned request");
+ }
+ sidecar.check();
+ results.push({ mode, passed: true, requests });
+ console.log(JSON.stringify(results.at(-1)));
+ } finally {
+ await sidecar.stop();
+ server.closeAllConnections();
+ await new Promise((done) => server.close(done));
+ }
+}
+
+try {
+ for (const mode of ["abort-backoff", "retry-after", "stalled-request"]) await scenario(mode);
+ console.log(JSON.stringify({ passed: true, results }));
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/hosted-search-sidecar.mjs b/scripts/e2e/hosted-search-sidecar.mjs
index 943e1efb0..0ccf76c99 100644
--- a/scripts/e2e/hosted-search-sidecar.mjs
+++ b/scripts/e2e/hosted-search-sidecar.mjs
@@ -40,6 +40,7 @@ export class OfflineSidecar {
this.closed = false;
this.stopping = false;
this.expectContextValidationError = false;
+ this.allowProviderRetries = false;
child.on("error", (error) => this.fail(error));
this.exit = new Promise((resolve) => child.once("close", (code, signal) => {
this.closed = true;
@@ -123,7 +124,7 @@ export class OfflineSidecar {
if (message.error && !expectedError(message.error)) this.fail(new Error(`message error: ${JSON.stringify(message.error)}`));
}
if (event.type === "error" && !expectedError(event.error)) this.fail(new Error(`agent error: ${JSON.stringify(event.error)}`));
- if (event.type === "status" && event.status.activity?.phase === "retrying") {
+ if (!this.allowProviderRetries && event.type === "status" && event.status.activity?.phase === "retrying") {
this.fail(new Error(`unexpected retry: ${JSON.stringify(event.status.activity.error)}`));
}
}