Skip to content

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

fix(agent-runtime): fail a stream that stops emitting events (#672)

zhangqingkun976ef3b282a2353
diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.ts
index a01e8d13f..29ce8bc72 100644
--- a/packages/agent-runtime/src/provider-retry.test.ts
+++ b/packages/agent-runtime/src/provider-retry.test.ts
@@ -15,8 +15,12 @@ import {
PROVIDER_TRANSIENT_MAX_RETRIES,
providerRateLimitDelayMs,
providerSetupRetryDelayMs,
+ STREAM_IDLE_TIMEOUT_DEFAULT_MS,
+ STREAM_IDLE_TIMEOUT_FLOOR_MS,
+ streamIdleTimeoutMs,
stripOutputLimitFields,
withoutDerivedOutputLimit,
+ withStreamIdleTimeout,
} from "./provider-retry.js";
import { activeNodeTransportRoute } from "./node-proxy.js";
import { describeProviderFetchFailure } from "./provider-transport-recovery.js";
@@ -821,3 +825,172 @@ describe("opaque bad-request repair", () => {
expect(typeof repaired.onPayload).toBe("function");
});
});
+
+describe("stream idle watchdog", () => {
+ it("reads the idle budget from the environment with a safe default", () => {
+ const previous = process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
+ try {
+ delete process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
+ expect(streamIdleTimeoutMs()).toBe(STREAM_IDLE_TIMEOUT_DEFAULT_MS);
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "45000";
+ expect(streamIdleTimeoutMs()).toBe(45_000);
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "0";
+ expect(streamIdleTimeoutMs()).toBe(0);
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "not-a-number";
+ expect(streamIdleTimeoutMs()).toBe(STREAM_IDLE_TIMEOUT_DEFAULT_MS);
+ } finally {
+ if (previous === undefined) {
+ delete process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
+ } else {
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = previous;
+ }
+ }
+ });
+
+ it("clamps a positive override up to the retry backoff floor", () => {
+ 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.
+ 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);
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = "0";
+ expect(streamIdleTimeoutMs()).toBe(0);
+ } finally {
+ if (previous === undefined) {
+ delete process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
+ } else {
+ process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS = previous;
+ }
+ }
+ });
+
+ it("passes the stream through unchanged when the watchdog is disabled", () => {
+ const stream = createAssistantMessageEventStream();
+ expect(withStreamIdleTimeout(stream, model, 0)).toBe(stream);
+ });
+
+ it("forwards a productive stream unchanged", async () => {
+ const wrapped = withStreamIdleTimeout(successfulStream(), model, 1_000);
+ const events: string[] = [];
+ for await (const event of wrapped) events.push(event.type);
+ expect(events).toEqual(["start", "done"]);
+ expect(await wrapped.result()).toMatchObject({
+ stopReason: "stop",
+ errorMessage: undefined,
+ });
+ });
+
+ it("ends a silent stream as a retriable stream failure", async () => {
+ vi.useFakeTimers();
+ try {
+ const stalled = createAssistantMessageEventStream();
+ stalled.push({ type: "start", partial: assistantMessage() });
+ const wrapped = withStreamIdleTimeout(stalled, model, 1_000);
+
+ const events: string[] = [];
+ const collected = (async () => {
+ for await (const event of wrapped) events.push(event.type);
+ })();
+ await vi.advanceTimersByTimeAsync(600);
+ expect(events).toEqual(["start"]);
+ await vi.advanceTimersByTimeAsync(400);
+ await collected;
+
+ expect(events).toEqual(["start", "error"]);
+ const result = await wrapped.result();
+ expect(result.stopReason).toBe("error");
+ expect(result.errorMessage).toContain("stream stalled");
+ // The timeout must merge into the existing transient retry path: the
+ // classified code is retriable and claims the shared budget.
+ const classified = classifyProviderError(result.errorMessage);
+ expect(classified).toMatchObject({
+ code: "STREAM_FAILED",
+ retriable: true,
+ });
+ expect(isTransientProviderRetryCode(classified.code)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("resets the idle timer on every event", async () => {
+ vi.useFakeTimers();
+ try {
+ const slow = createAssistantMessageEventStream();
+ slow.push({ type: "start", partial: assistantMessage() });
+ const wrapped = withStreamIdleTimeout(slow, model, 1_000);
+
+ const events: string[] = [];
+ const collected = (async () => {
+ for await (const event of wrapped) events.push(event.type);
+ })();
+ // An event at t=800 re-arms the watchdog; without the reset the stream
+ // would already have failed at t=1000.
+ await vi.advanceTimersByTimeAsync(800);
+ slow.push({ type: "text_start", contentIndex: 0, partial: assistantMessage() });
+ await vi.advanceTimersByTimeAsync(800);
+ expect(events).toEqual(["start", "text_start"]);
+ await vi.advanceTimersByTimeAsync(400);
+ await collected;
+ expect(events).toEqual(["start", "text_start", "error"]);
+ expect((await wrapped.result()).errorMessage).toContain("stream stalled");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops the retry adapter it abandons instead of letting it issue a second request", async () => {
+ vi.useFakeTimers();
+ try {
+ const controller = new AbortController();
+ let attempts = 0;
+ const adapter = createProviderRetryStream(
+ model,
+ context,
+ { signal: controller.signal } as any,
+ () => {
+ attempts += 1;
+ return failedStream({
+ errorMessage:
+ 'OpenAI API error (502): {"type":"api_error","message":"Upstream API request failed."}',
+ });
+ },
+ {
+ claim: (error) =>
+ isTransientProviderRetryCode(error.code) ? 1 : undefined,
+ headers: () => undefined,
+ status: () => 502,
+ },
+ );
+ // 500 ms: inside the adapter's first 1 s backoff, which is zero-event time
+ // to this wrapper. The real `sleep` is used on purpose — it is the thing
+ // the abort has to reject.
+ const wrapped = withStreamIdleTimeout(adapter, model, 500, () =>
+ controller.abort(),
+ );
+
+ const events: string[] = [];
+ const collected = (async () => {
+ for await (const event of wrapped) events.push(event.type);
+ })();
+ // The first attempt fails retriably and the adapter starts backing off.
+ // That wait is zero-event time to the watchdog, which fires inside it and
+ // aborts the request: the backoff rejects instead of resolving, so the
+ // adapter never opens the second request the runtime's own retry is
+ // already covering.
+ await vi.advanceTimersByTimeAsync(120_000);
+ await collected;
+
+ expect(controller.signal.aborted).toBe(true);
+ expect(events).toEqual(["error"]);
+ expect(attempts).toBe(1);
+ await vi.advanceTimersByTimeAsync(600_000);
+ expect(attempts).toBe(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/agent-runtime/src/provider-retry.ts b/packages/agent-runtime/src/provider-retry.ts
index ac816ac2b..f29b8075d 100644
--- a/packages/agent-runtime/src/provider-retry.ts
+++ b/packages/agent-runtime/src/provider-retry.ts
@@ -2,6 +2,7 @@ import {
createAssistantMessageEventStream,
type Api,
type AssistantMessage,
+ type AssistantMessageEvent,
type AssistantMessageEventStream,
type Context,
type FetchFunction,
@@ -533,3 +534,136 @@ export function createProviderRetryStream(
return outer;
}
+
+/**
+ * Default zero-event idle budget for a provider stream: a stream that emits
+ * nothing for this long is ended as a retriable stream failure so the shared
+ * transient retry path re-runs the request instead of leaving the turn hung on
+ * a connection the provider never closes.
+ */
+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.
+ */
+export const STREAM_IDLE_TIMEOUT_FLOOR_MS = PROVIDER_RATE_LIMIT_MAX_DELAY_MS;
+
+/**
+ * `PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS` overrides the zero-event idle budget;
+ * `0` disables the watchdog, and any other override is clamped up to
+ * `STREAM_IDLE_TIMEOUT_FLOOR_MS` (see above). A value that is not a number, or
+ * is negative, keeps the default.
+ */
+export function streamIdleTimeoutMs(): number {
+ const raw = process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
+ if (raw === undefined || raw.trim() === "") {
+ return STREAM_IDLE_TIMEOUT_DEFAULT_MS;
+ }
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value < 0) {
+ return STREAM_IDLE_TIMEOUT_DEFAULT_MS;
+ }
+ if (value === 0) return 0;
+ return Math.max(STREAM_IDLE_TIMEOUT_FLOOR_MS, Math.floor(value));
+}
+
+function streamIdleTimeoutMessage(timeoutMs: number): string {
+ return `stream stalled: no provider events for ${timeoutMs}ms`;
+}
+
+/**
+ * Zero-event idle watchdog around a provider stream. Every event resets the
+ * timer and total stream duration is never limited, so a long but productive
+ * stream is forwarded unchanged. A stream that stays silent for `timeoutMs` is
+ * ended as a `STREAM_FAILED`-classified error result — the same shape a dropped
+ * 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.
+ */
+export function withStreamIdleTimeout(
+ inner: AssistantMessageEventStream,
+ model: Model<Api>,
+ timeoutMs: number,
+ onStall?: () => void,
+): AssistantMessageEventStream {
+ if (timeoutMs <= 0) return inner;
+ const outer = createAssistantMessageEventStream();
+
+ void (async () => {
+ const iterator = inner[Symbol.asyncIterator]();
+ for (;;) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const idle = new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(streamIdleTimeoutMessage(timeoutMs))),
+ timeoutMs,
+ );
+ });
+ let step: IteratorResult<AssistantMessageEvent>;
+ try {
+ 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).
+ onStall?.();
+ drainAbandonedStream(iterator);
+ const message = setupErrorMessage(
+ model,
+ new Error(streamIdleTimeoutMessage(timeoutMs)),
+ false,
+ );
+ outer.push({ type: "error", reason: "error", error: message });
+ outer.end(message);
+ return;
+ }
+ clearTimeout(timer);
+ if (step.done) {
+ outer.end(await inner.result());
+ return;
+ }
+ outer.push(step.value);
+ if (step.value.type === "done" || step.value.type === "error") {
+ return;
+ }
+ }
+ })().catch((error) => {
+ // The driver only rejects on a programming error; surface it the way the
+ // retry adapter does so a consumer never waits on a dead wrapper.
+ const message = setupErrorMessage(model, error, false);
+ outer.push({ type: "error", reason: "error", error: message });
+ outer.end(message);
+ });
+
+ return outer;
+}
+
+/** Keep consuming an abandoned stream so its queued events are released. */
+function drainAbandonedStream(
+ iterator: AsyncIterator<AssistantMessageEvent>,
+): void {
+ void (async () => {
+ try {
+ for (;;) {
+ const step = await iterator.next();
+ if (step.done) return;
+ }
+ } catch {
+ // The stalled stream's own late failures are not ours to surface.
+ }
+ })();
+}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 572831bf8..94804ad78 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -198,6 +198,8 @@ import {
isTransientProviderRetryCode,
providerRateLimitDelayMs,
providerSetupRetryDelayMs,
+ streamIdleTimeoutMs,
+ withStreamIdleTimeout,
} from "./provider-retry.js";
import { rebuildNodeNetworkTransport } from "./node-proxy.js";
@@ -1833,10 +1835,25 @@ Delegation rules:
),
);
const hookedOptions = this.withExtensionProviderHooks(requestOptions, m);
- return createProviderRetryStream(
+ // 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();
+ const attemptOptions: SimpleStreamOptions = {
+ ...hookedOptions,
+ signal: AbortSignal.any([
+ ...(hookedOptions.signal ? [hookedOptions.signal] : []),
+ stallAbort.signal,
+ ]),
+ };
+ const retryStream = createProviderRetryStream(
m,
context,
- hookedOptions,
+ attemptOptions,
(retryOptions) =>
this.thinkingLevel === "omit"
? this.models.stream(omitThinkingModel(m), context, retryOptions)
@@ -1857,6 +1874,13 @@ Delegation rules:
},
},
);
+ // 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 withStreamIdleTimeout(retryStream, m, streamIdleTimeoutMs(), () =>
+ stallAbort.abort(),
+ );
},
// 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.