Skip to content

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

55.2 KB
Raw Blame
import { describe, expect, it, vi } from "vitest";
import {
  createAssistantMessageEventStream,
  type AssistantMessage,
} from "@earendil-works/pi-ai";
import {
  captureProviderResponse,
  carriesRetryDelayHeaders,
  classifyProviderError,
  createProviderRetryStream,
  delayWithAbort,
  isOpaqueBadRequest,
  isTransientProviderRetryCode,
  PROVIDER_RATE_LIMIT_MAX_RETRIES,
  PROVIDER_TRANSIENT_MAX_RETRIES,
  providerRateLimitDelayMs,
  providerSetupRetryDelayMs,
  STREAM_IDLE_TIMEOUT_DEFAULT_MS,
  STREAM_IDLE_TIMEOUT_FLOOR_MS,
  streamIdleTimeoutMs,
  isOutputLimitRejection,
  outputTokenCeiling,
  stripOutputLimitFields,
  withoutDerivedOutputLimit,
  withStreamIdleTimeout,
} from "./provider-retry.js";
import { activeNodeTransportRoute } from "./node-proxy.js";
import { describeProviderFetchFailure } from "./provider-transport-recovery.js";
import { classifyAgentError, type ClassifiedAgentError } from "./agent-errors.js";

const model = {
  id: "model",
  api: "openai-completions",
  provider: "provider",
  reasoning: false,
  input: ["text"],
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  contextWindow: 32_000,
  maxTokens: 4_000,
  baseUrl: "https://provider.invalid/v1",
} as any;

const context = { messages: [], tools: [] };

function assistantMessage(overrides: Partial<AssistantMessage> = {}): AssistantMessage {
  return {
    role: "assistant",
    content: [],
    api: "openai-completions",
    provider: "provider",
    model: "model",
    usage: {
      input: 0,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      totalTokens: 0,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
    },
    stopReason: "error",
    errorMessage: "429: too many requests",
    timestamp: Date.now(),
    ...overrides,
  };
}

function failedStream(
  overrides: Partial<AssistantMessage> = {},
): ReturnType<typeof createAssistantMessageEventStream> {
  const stream = createAssistantMessageEventStream();
  const error = assistantMessage(overrides);
  queueMicrotask(() => {
    stream.push({ type: "error", reason: "error", error });
    stream.end(error);
  });
  return stream;
}

function successfulStream(): ReturnType<typeof createAssistantMessageEventStream> {
  const stream = createAssistantMessageEventStream();
  const message = assistantMessage({
    content: [{ type: "text", text: "recovered" }],
    stopReason: "stop",
    errorMessage: undefined,
  });
  queueMicrotask(() => {
    stream.push({ type: "start", partial: message });
    stream.push({ type: "done", reason: "stop", message });
    stream.end(message);
  });
  return stream;
}

describe("local request failures", () => {
  const errorDetails = {
    code: "LOCAL_REQUEST_ERROR" as const,
    phase: "context-validation" as const,
    message: "Local request validation failed.",
    causeName: "TypeError",
  };

  it.each([false, true])("never claims, retries or fetches a local event (started=%s)", async (started) => {
    const failure = Object.assign(assistantMessage({ errorMessage: "fetch failed" }), { errorDetails });
    const fetch = vi.fn();
    const createStream = vi.fn(() => {
      const inner = createAssistantMessageEventStream();
      queueMicrotask(() => {
        if (started) inner.push({ type: "start", partial: failure });
        inner.push({ type: "error", reason: "error", error: failure });
        inner.end(failure);
      });
      return inner;
    });
    // Even a permissive controller must not get to claim a local failure.
    const claim = vi.fn(() => undefined as number | undefined).mockReturnValueOnce(1);
    const sleep = vi.fn(async () => undefined);
    const onRetry = vi.fn();
    const stream = createProviderRetryStream(model, context, { fetch }, createStream, {
      claim, sleep, onRetry, headers: () => undefined, status: () => 429,
      failure: () => describeProviderFetchFailure(new TypeError("fetch failed")),
    });
    const events = [];
    for await (const event of stream) events.push(event);
    const result = await stream.result();
    expect(createStream).toHaveBeenCalledTimes(1);
    expect(fetch).not.toHaveBeenCalled();
    expect(claim).not.toHaveBeenCalled();
    expect(sleep).not.toHaveBeenCalled();
    expect(onRetry).not.toHaveBeenCalled();
    expect(result).toBe(failure);
    expect(events.at(-1)).toMatchObject({ type: "error", error: { errorDetails } });
    expect(classifyProviderError(result, 429)).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "context-validation", causeName: "TypeError" },
    });
  });

  it("retains setup error metadata and its original cause without serializing private data", async () => {
    const cause = new TypeError("private prompt api_key=test-secret");
    const error = Object.assign(new Error("private payload", { cause }), {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
    });
    const claim = vi.fn();
    const fetch = vi.fn();
    const createStream = vi.fn(() => { throw error; });
    const stream = createProviderRetryStream(model, context, { fetch }, createStream, {
      claim, headers: () => undefined,
    });
    const result = await stream.result();
    expect(result).toHaveProperty("errorDetails", {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
      message: expect.any(String), causeName: "TypeError",
    });
    expect(result).toHaveProperty("cause", error);
    expect(error.cause).toBe(cause);
    expect(JSON.stringify(result)).not.toMatch(/private|test-secret|stack/);
    expect(classifyProviderError(result)).toMatchObject({ code: "INTERNAL", retriable: false });
    expect(createStream).toHaveBeenCalledTimes(1);
    expect(claim).not.toHaveBeenCalled();
    expect(fetch).not.toHaveBeenCalled();
  });

  it("still retries an ordinary TypeError fetch rejection with no local metadata", async () => {
    const fetch = vi.fn().mockRejectedValueOnce(new TypeError("fetch failed"))
      .mockResolvedValueOnce(new Response("ok"));
    const claim = vi.fn((error: ClassifiedAgentError) => error.retriable ? 1 : undefined);
    const sleep = vi.fn(async () => undefined);
    const stream = createProviderRetryStream(model, context, { fetch }, (options) => {
      const inner = createAssistantMessageEventStream();
      void options.fetch!("https://provider.invalid", {}).then(() => {
        const message = assistantMessage({ stopReason: "stop", errorMessage: undefined });
        inner.push({ type: "done", reason: "stop", message });
        inner.end(message);
      }, (error) => {
        const message = assistantMessage({ errorMessage: error.message });
        inner.push({ type: "error", reason: "error", error: message });
        inner.end(message);
      });
      return inner;
    }, { claim, sleep, headers: () => undefined });
    expect((await stream.result()).stopReason).toBe("stop");
    expect(fetch).toHaveBeenCalledTimes(2);
    expect(claim).toHaveBeenCalledWith(expect.objectContaining({ code: "NETWORK_ERROR", retriable: true }), "request");
    expect(sleep).toHaveBeenCalledTimes(1);
  });

  it("keeps an already cancelled request from starting or claiming a retry", async () => {
    const controller = new AbortController();
    controller.abort();
    const createStream = vi.fn(() => failedStream());
    const claim = vi.fn();
    const stream = createProviderRetryStream(model, context, { signal: controller.signal }, createStream, {
      claim, headers: () => undefined,
    });
    const result = await stream.result();
    expect(result.stopReason).toBe("aborted");
    expect(classifyProviderError(result)).toMatchObject({ code: "TURN_ABORTED", retriable: false });
    expect(createStream).not.toHaveBeenCalled();
    expect(claim).not.toHaveBeenCalled();
  });

  it("keeps a phase-only local marker terminal under a stale 429", async () => {
    // The captured status belongs to an earlier response. The later failure is
    // explicit local provenance, so it must not be relabelled as a rate limit and
    // must not claim the retry the stale status alone would allow.
    const failure = Object.assign(assistantMessage({ errorMessage: "fetch failed" }), {
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR", phase: "context-estimation", causeName: "TypeError",
      },
    });
    const claim = vi.fn(() => undefined as number | undefined).mockReturnValueOnce(1);
    const sleep = vi.fn(async () => undefined);
    const createStream = vi.fn(() => {
      const inner = createAssistantMessageEventStream();
      queueMicrotask(() => {
        inner.push({ type: "error", reason: "error", error: failure });
        inner.end(failure);
      });
      return inner;
    });
    const stream = createProviderRetryStream(model, context, {}, createStream, {
      claim, sleep, headers: () => undefined, status: () => 429,
    });
    const events = [];
    for await (const event of stream) events.push(event);
    const result = await stream.result();

    expect(createStream).toHaveBeenCalledTimes(1);
    expect(claim).not.toHaveBeenCalled();
    expect(sleep).not.toHaveBeenCalled();
    expect(result).toBe(failure);
    expect(result.errorMessage).toBe("fetch failed");
    expect(events.at(-1)).toMatchObject({
      type: "error",
      error: { errorMessage: "fetch failed" },
    });
    expect(classifyProviderError(result, 429)).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
    });
  });

  it("neither retries nor relabels a synchronous local throw under a stale 429", async () => {
    const error = Object.assign(new Error("Local request preparation failed."), {
      name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
      phase: "request-preparation", cause: new TypeError("private prompt"),
    });
    const claim = vi.fn(() => 1 as number | undefined);
    const sleep = vi.fn(async () => undefined);
    const createStream = vi.fn(() => { throw error; });
    const stream = createProviderRetryStream(model, context, {}, createStream, {
      claim, sleep, headers: () => ({ "retry-after": "1" }), status: () => 429,
    });
    const events: string[] = [];
    for await (const event of stream) events.push(event.type);
    const result = await stream.result();

    expect(events).toEqual(["error"]);
    expect(createStream).toHaveBeenCalledTimes(1);
    expect(claim).not.toHaveBeenCalled();
    expect(sleep).not.toHaveBeenCalled();
    expect(result).toHaveProperty("errorDetails", {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
      message: expect.any(String), causeName: "TypeError",
    });
    expect(JSON.stringify(result)).not.toMatch(/private/);
    expect(classifyProviderError(result, 429)).toMatchObject({
      code: "INTERNAL", retriable: false,
    });
  });

  it("keeps a locally wrapped Stop as cancellation, not as a local failure", async () => {
    // pi-ai records the wrapped AbortError only in the marker's cause, and this
    // path has no aborted signal to read, so the cause name is all there is.
    const thrown = Object.assign(new Error("Local request preparation failed."), {
      name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
      phase: "request-preparation",
      cause: Object.assign(new Error("The operation was aborted"), { name: "AbortError" }),
    });
    const claim = vi.fn(() => 1 as number | undefined);
    const sleep = vi.fn(async () => undefined);
    const createStream = vi.fn(() => { throw thrown; });
    const stream = createProviderRetryStream(model, context, {}, createStream, {
      claim, sleep, headers: () => undefined,
    });
    const result = await stream.result();

    expect(createStream).toHaveBeenCalledTimes(1);
    expect(claim).not.toHaveBeenCalled();
    expect(sleep).not.toHaveBeenCalled();
    expect(result).toHaveProperty("errorDetails", {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
      message: expect.any(String), causeName: "AbortError",
    });
    expect(classifyProviderError(result)).toMatchObject({
      code: "TURN_ABORTED", retriable: false,
    });
  });
});

describe("provider rate-limit retry", () => {
  it("uses a captured 429 status when the provider body is generic", () => {
    expect(classifyProviderError("upstream unavailable", 429)).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
      details: { providerStatus: 429 },
    });
    expect(classifyProviderError("authentication failed", 429)).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
  });

  it.each([
    '429: {"error":{"message":"You exceeded your current quota, please check your plan and billing details.","type":"insufficient_quota","code":"insufficient_quota"}}',
    '429: {"type":"FreeUsageLimitError","message":"Free usage limit reached."}',
  ])("does not retry explicit quota exhaustion on HTTP 429: %s", async (errorMessage) => {
    let attempts = 0;
    let retryableClaims = 0;
    const claim = vi.fn((error: ClassifiedAgentError) => {
      if (!error.retriable) return undefined;
      retryableClaims += 1;
      return retryableClaims === 1 ? 1 : undefined;
    });
    const sleep = vi.fn(async () => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({ errorMessage });
      },
      { claim, headers: () => undefined, status: () => 429, sleep },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(1);
    expect(claim).toHaveBeenCalledWith(
      expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false, message: errorMessage }),
      "request",
    );
    expect(sleep).not.toHaveBeenCalled();
    expect(events).toEqual(["error"]);
  });

  it("prefers retry headers and bounds exponential fallback", () => {
    expect(providerRateLimitDelayMs(1, { "retry-after-ms": "1250" }, 0, 0)).toBe(1250);
    expect(providerRateLimitDelayMs(1, { "retry-after": "2" }, 0, 0)).toBe(2000);
    expect(
      providerRateLimitDelayMs(
        1,
        { "retry-after": new Date(5_000).toUTCString() },
        0,
        0,
      ),
    ).toBe(5000);
    expect(
      providerRateLimitDelayMs(
        1,
        { "retry-after": new Date(-5_000).toUTCString() },
        0,
        0,
      ),
    ).toBe(0);
    expect(providerRateLimitDelayMs(1, undefined, 0, 0)).toBe(2000);
    expect(providerRateLimitDelayMs(1, undefined, 0, 1)).toBe(2500);
    expect(providerRateLimitDelayMs(20, { "retry-after": "120" }, 0, 0)).toBe(30_000);
  });

  it("silently retries pre-stream 429s and forwards only the successful stream", async () => {
    let attempts = 0;
    const claims: Array<{ phase: string; attempt: number }> = [];
    const sleep = vi.fn(async () => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return attempts < 3 ? failedStream() : successfulStream();
      },
      {
        claim: (_error, phase) => {
          const attempt = attempts;
          claims.push({ phase, attempt });
          return attempt <= 2 ? attempt : undefined;
        },
        headers: () => ({ "retry-after-ms": "1" }),
        sleep,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(3);
    expect(claims).toEqual([
      { phase: "request", attempt: 1 },
      { phase: "request", attempt: 2 },
    ]);
    expect(sleep).toHaveBeenCalledTimes(2);
    expect(sleep).toHaveBeenNthCalledWith(1, 1, undefined);
    expect(sleep).toHaveBeenNthCalledWith(2, 1, undefined);
    expect(events).toEqual(["start", "done"]);
  });

  it("uses the captured HTTP status when the error body omits rate-limit text", async () => {
    let attempts = 0;
    const claimedCodes: string[] = [];
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        if (attempts === 1) {
          const result = createAssistantMessageEventStream();
          const error = assistantMessage({ errorMessage: "upstream unavailable" });
          queueMicrotask(() => {
            result.push({ type: "error", reason: "error", error });
            result.end(error);
          });
          return result;
        }
        return successfulStream();
      },
      {
        claim: (error) => {
          claimedCodes.push(error.code);
          return 1;
        },
        headers: () => undefined,
        status: () => 429,
        sleep: vi.fn(async () => undefined),
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(2);
    expect(claimedCodes).toEqual(["PROVIDER_RATE_LIMITED"]);
    expect(events).toEqual(["start", "done"]);
  });

  it("does not replay a DashScope parameter rejection delivered over HTTP 200", async () => {
    let retryClaims = 0;
    const claim = vi.fn((error: ClassifiedAgentError) =>
      error.retriable && retryClaims++ === 0 ? 1 : undefined);
    const sleep = vi.fn(async () => undefined);
    const createStream = vi.fn(() => failedStream({
      errorMessage: "InvalidParameter: <400> InternalError.Algo.InvalidParameter: Repetitive tool calls detected in the conversation history.",
    }));
    const stream = createProviderRetryStream(model, context, {}, createStream, {
      claim, sleep, headers: () => undefined, status: () => 200,
    });

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(createStream).toHaveBeenCalledTimes(1);
    expect(sleep).not.toHaveBeenCalled();
    expect(claim).toHaveBeenCalledWith(expect.objectContaining({
      code: "PROVIDER_ERROR", retriable: false, details: { providerStatus: 400 },
    }), "request");
    expect(events).toEqual(["error"]);
  });

  it("does not promote known non-retryable errors just because status is 429", async () => {
    const claim = vi.fn(() => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        const result = createAssistantMessageEventStream();
        const error = assistantMessage({ errorMessage: "authentication failed" });
        queueMicrotask(() => {
          result.push({ type: "error", reason: "error", error });
          result.end(error);
        });
        return result;
      },
      {
        claim,
        headers: () => undefined,
        status: () => 429,
        sleep: vi.fn(async () => undefined),
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(claim).toHaveBeenCalledWith(
      expect.objectContaining({ code: "PROVIDER_UNAUTHORIZED", retriable: false }),
      "request",
    );
    expect(events).toEqual(["error"]);
  });

  it("does not replay a Zhipu 1308 usage-limit 429 through the rate-limit budget", async () => {
    const claim = vi.fn(() => undefined);
    const sleep = vi.fn(async () => undefined);
    const createStream = vi.fn(() => failedStream({
      errorMessage: '429 {"error":{"code":"1308","message":"Usage limit reached for 5 hour."}}',
    }));
    const stream = createProviderRetryStream(model, context, {}, createStream, {
      claim, sleep, headers: () => undefined, status: () => 429,
    });

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(createStream).toHaveBeenCalledTimes(1);
    expect(sleep).not.toHaveBeenCalled();
    expect(claim).toHaveBeenCalledWith(
      expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false }),
      "request",
    );
    expect(events).toEqual(["error"]);
  });

  it("clears a captured 429 before a fetch fails without a response", async () => {
    let calls = 0;
    let snapshot: { status: number; headers: Record<string, string> } | undefined;
    const wrapped = captureProviderResponse(
      async () => {
        calls += 1;
        if (calls === 1) {
          return new Response("rate limited", { status: 429 });
        }
        throw new Error("fetch failed");
      },
      (response) => {
        snapshot = response;
      },
    );

    await wrapped("https://provider.invalid", {});
    expect(snapshot?.status).toBe(429);
    await expect(wrapped("https://provider.invalid", {})).rejects.toThrow("fetch failed");
    expect(snapshot).toBeUndefined();
  });

  it("describes the transport cause of a rejected fetch and keeps the error", async () => {
    const failures: Array<ReturnType<typeof describeProviderFetchFailure>> = [];
    const original = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("read ECONNRESET"), {
        code: "ECONNRESET",
        syscall: "read",
      }),
    });
    const wrapped = captureProviderResponse(
      async () => {
        throw original;
      },
      (_response, _requestBytes, failure) => {
        failures.push(failure);
      },
    );

    await expect(
      wrapped("https://chatgpt.com/backend-api/codex/responses", {}),
    ).rejects.toBe(original);
    // The first entry is the clear before the attempt, the last is the cause.
    expect(failures).toEqual([
      undefined,
      {
        origin: "https://chatgpt.com",
        category: "reset",
        fields: {
          networkCategory: "reset",
          networkCode: "ECONNRESET",
          networkSyscall: "read",
          networkRoute: activeNodeTransportRoute(),
        },
      },
    ]);
  });
  it("names the failing layer on the retried error, not just fetch failed", async () => {
    let attempts = 0;
    const retried: ClassifiedAgentError[] = [];
    const failure = describeProviderFetchFailure(
      Object.assign(new TypeError("fetch failed"), {
        cause: Object.assign(new Error("read ECONNRESET"), {
          code: "ECONNRESET",
        }),
      }),
      "https://chatgpt.com/backend-api/codex/responses",
    );
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({ errorMessage: "fetch failed" });
      },
      {
        claim: () => (attempts <= 1 ? attempts : undefined),
        headers: () => undefined,
        status: () => undefined,
        failure: () => failure,
        onRetry: ({ error }) => {
          retried.push(error);
        },
      },
    );

    const final = await stream.result();

    // The retry indicator renders this object, so the errno has to be on it;
    // the provider message itself stays untouched.
    expect(retried).toHaveLength(1);
    expect(retried[0]).toMatchObject({
      code: "NETWORK_ERROR",
      message: "fetch failed",
      details: { networkCategory: "reset", networkCode: "ECONNRESET" },
    });
    expect(final.errorMessage).toBe("fetch failed");
  });

  it("reports the request body size even when the request dies first", async () => {
    const seen: Array<[number | undefined, number | undefined]> = [];
    const body = JSON.stringify({ model: "gpt-5.6-sol", input: "hello" });
    const wrapped = captureProviderResponse(
      async () => {
        throw new Error("fetch failed");
      },
      (response, requestBytes) => {
        seen.push([response?.status, requestBytes]);
      },
    );

    await expect(
      wrapped("https://provider.invalid", { method: "POST", body }),
    ).rejects.toThrow("fetch failed");

    // The clearing call, then the failure: only the size survives, never the
    // body content, and a request that never got headers still reports it.
    expect(seen).toEqual([
      [undefined, undefined],
      [undefined, Buffer.byteLength(body, "utf8")],
    ]);
  });

  it("reports no request size when the body cannot be measured unread", async () => {
    const sizes: Array<number | undefined> = [];
    const wrapped = captureProviderResponse(
      async () => new Response("ok", { status: 200 }),
      (_response, requestBytes) => {
        sizes.push(requestBytes);
      },
    );

    // A body the transport does not expose as a string/buffer/blob reports no
    // size instead of throwing or being read.
    await wrapped("https://provider.invalid", {
      method: "POST",
      body: new FormData(),
    });
    expect(sizes.at(-1)).toBeUndefined();

    await wrapped("https://provider.invalid", {
      method: "POST",
      body: new Uint8Array([1, 2, 3, 4]),
    });
    expect(sizes.at(-1)).toBe(4);
  });

  it("rejects an abortable retry delay without waiting for the timer", async () => {
    vi.useFakeTimers();
    const controller = new AbortController();
    try {
      const pending = delayWithAbort(30_000, controller.signal);
      controller.abort();
      await expect(pending).rejects.toMatchObject({ name: "AbortError" });
      expect(vi.getTimerCount()).toBe(0);
    } finally {
      vi.useRealTimers();
    }
  });

  it("keeps an exhausted setup 429 classified when its body omits status text", async () => {
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        const result = createAssistantMessageEventStream();
        const error = assistantMessage({ errorMessage: "upstream unavailable" });
        queueMicrotask(() => {
          result.push({ type: "error", reason: "error", error });
          result.end(error);
        });
        return result;
      },
      {
        claim: vi.fn(() => undefined),
        headers: () => undefined,
        status: () => 429,
        sleep: vi.fn(async () => undefined),
      },
    );

    const events: Array<{ type: string; error?: AssistantMessage }> = [];
    for await (const event of stream) events.push(event as typeof events[number]);

    expect(events).toHaveLength(1);
    expect(events[0]).toMatchObject({
      type: "error",
      error: { errorMessage: "429: upstream unavailable" },
    });
  });

  it("does not hide a 429 after a stream has started", async () => {
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        const result = createAssistantMessageEventStream();
        const partial = assistantMessage({ stopReason: "pending" });
        const error = assistantMessage();
        queueMicrotask(() => {
          result.push({ type: "start", partial });
          result.push({ type: "error", reason: "error", error });
          result.end(error);
        });
        return result;
      },
      {
        claim: vi.fn(() => 1),
        headers: () => undefined,
        sleep: vi.fn(async () => undefined),
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(events).toEqual(["start", "error"]);
  });
});

describe("bounded transient provider retry", () => {
  it("admits only the transport/gateway codes into the shared budget", () => {
    for (const code of [
      "NETWORK_ERROR",
      "TIMEOUT",
      "STREAM_FAILED",
      "PROVIDER_ERROR",
    ]) {
      expect(isTransientProviderRetryCode(code)).toBe(true);
    }
    for (const code of [
      "PROVIDER_RATE_LIMITED",
      "PROVIDER_UNAUTHORIZED",
      "CONTEXT_TOO_LARGE",
      "MODEL_NOT_CONFIGURED",
      "EMPTY_MODEL_RESPONSE",
      "TURN_ABORTED",
    ]) {
      expect(isTransientProviderRetryCode(code)).toBe(false);
    }
  });

  it("classifies an upstream gateway 502 as a retryable provider error", () => {
    const classified = classifyProviderError(
      'OpenAI API error (502): {"type":"api_error","message":"Upstream API request failed."}',
    );
    expect(classified).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
      details: { providerStatus: 502 },
    });
    expect(isTransientProviderRetryCode(classified.code)).toBe(true);
  });

  it("keeps retry headers for every status that can state a delay", () => {
    expect(carriesRetryDelayHeaders(429)).toBe(true);
    expect(carriesRetryDelayHeaders(408)).toBe(true);
    expect(carriesRetryDelayHeaders(409)).toBe(true);
    expect(carriesRetryDelayHeaders(502)).toBe(true);
    expect(carriesRetryDelayHeaders(503)).toBe(true);
    expect(carriesRetryDelayHeaders(400)).toBe(false);
    expect(carriesRetryDelayHeaders(401)).toBe(false);
    expect(carriesRetryDelayHeaders(undefined)).toBe(false);
  });

  it("allows ten transient retries and caps the later waits at 8s", () => {
    expect(PROVIDER_RATE_LIMIT_MAX_RETRIES).toBe(10);
    expect(PROVIDER_TRANSIENT_MAX_RETRIES).toBe(10);
    expect(providerSetupRetryDelayMs(1)).toBe(1_000);
    expect(providerSetupRetryDelayMs(2)).toBe(2_000);
    expect(providerSetupRetryDelayMs(3)).toBe(4_000);
    expect(providerSetupRetryDelayMs(4)).toBe(8_000);
    // The schedule is deterministic: the unused random argument cannot shift it.
    expect(providerSetupRetryDelayMs(2, 0)).toBe(2_000);
    expect(providerSetupRetryDelayMs(2, 1)).toBe(2_000);
    // Beyond the budget the cap holds.
    expect(providerSetupRetryDelayMs(20)).toBe(8_000);
  });

  it("prefers a gateway Retry-After over the fixed backoff schedule", () => {
    expect(providerSetupRetryDelayMs(1, 0, { "retry-after-ms": "1250" })).toBe(1250);
    expect(providerSetupRetryDelayMs(1, 0, { "retry-after": "2" })).toBe(2_000);
    expect(
      providerSetupRetryDelayMs(1, 0, { "retry-after": new Date(5_000).toUTCString() }, 0),
    ).toBe(5_000);
    // A hostile or stale header cannot hold the turn past the non-429 cap.
    expect(providerSetupRetryDelayMs(1, 0, { "retry-after": "600" })).toBe(8_000);
  });

  it("lets a server ask for a shorter wait than the schedule", () => {
    // A gateway that says it is ready sooner is believed, and a stale or
    // hostile value still cannot exceed the cap.
    expect(providerSetupRetryDelayMs(1, 0, { "retry-after-ms": "100" })).toBe(100);
    expect(providerSetupRetryDelayMs(4, 0, { "retry-after-ms": "250" })).toBe(250);
    expect(providerSetupRetryDelayMs(1, 0, { "retry-after": "600" })).toBe(8_000);
  });

  it("retries repeated pre-stream 502s until the shared budget is spent", async () => {
    let attempts = 0;
    const claims: Array<{ code: string; attempt: number }> = [];
    const delays: number[] = [];
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return attempts <= PROVIDER_TRANSIENT_MAX_RETRIES
          ? failedStream({
              errorMessage:
                'OpenAI API error (502): {"type":"api_error","message":"Upstream API request failed."}',
            })
          : successfulStream();
      },
      {
        claim: (error) => {
          if (!isTransientProviderRetryCode(error.code)) return undefined;
          if (claims.length >= PROVIDER_TRANSIENT_MAX_RETRIES) return undefined;
          const attempt = claims.length + 1;
          claims.push({ code: error.code, attempt });
          return attempt;
        },
        headers: () => undefined,
        status: () => 502,
        sleep: async (ms) => {
          delays.push(ms);
        },
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    // Ten retries after the initial attempt, so eleven provider attempts.
    expect(attempts).toBe(PROVIDER_TRANSIENT_MAX_RETRIES + 1);
    expect(claims.map((claim) => claim.attempt)).toEqual(
      Array.from({ length: PROVIDER_TRANSIENT_MAX_RETRIES }, (_, index) => index + 1),
    );
    expect(claims.every((claim) => claim.code === "PROVIDER_ERROR")).toBe(true);
    expect(delays).toEqual([
      1_000,
      2_000,
      4_000,
      ...Array.from({ length: PROVIDER_TRANSIENT_MAX_RETRIES - 3 }, () => 8_000),
    ]);
    // No intermediate error event reaches the consumer.
    expect(events).toEqual(["start", "done"]);
    expect((await stream.result()).stopReason).toBe("stop");
  });

  it("surfaces the 502 once the budget refuses a further attempt", async () => {
    let attempts = 0;
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({
          errorMessage:
            'OpenAI API error (502): {"type":"api_error","message":"Upstream API request failed."}',
        });
      },
      {
        claim: () =>
          attempts <= PROVIDER_TRANSIENT_MAX_RETRIES ? attempts : undefined,
        headers: () => undefined,
        status: () => 502,
        sleep: async () => undefined,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(PROVIDER_TRANSIENT_MAX_RETRIES + 1);
    expect(events).toEqual(["error"]);
    const result = await stream.result();
    expect(result.stopReason).toBe("error");
    expect(result.errorMessage).toContain("502");
  });
});

describe("opaque bad-request repair", () => {
  it("detects terminal 400/422s whose body was empty", () => {
    expect(
      isOpaqueBadRequest(classifyProviderError("400 status code (no body)", 400)),
    ).toBe(true);
    expect(
      isOpaqueBadRequest(classifyProviderError("422 status code (no body)", 422)),
    ).toBe(true);
    // Message-derived status still applies when the capture missed the response.
    expect(isOpaqueBadRequest(classifyProviderError("400 status code (no body)"))).toBe(
      true,
    );
    // Descriptive bodies and other statuses stay untouched.
    expect(
      isOpaqueBadRequest(
        classifyProviderError('400: {"error":{"message":"nope"}}', 400),
      ),
    ).toBe(false);
    expect(
      isOpaqueBadRequest(classifyProviderError("403 status code (no body)", 403)),
    ).toBe(false);
    expect(
      isOpaqueBadRequest(classifyProviderError("upstream unavailable", 429)),
    ).toBe(false);
  });

  it("repairs a pre-stream 400 with no body by dropping the derived output limit", async () => {
    let attempts = 0;
    let repairOptions: { onPayload?: (payload: unknown) => Promise<unknown> } | undefined;
    const claim = vi.fn(() => undefined);
    const sleep = vi.fn(async () => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {
        onPayload: async (payload: unknown) => ({
          ...(payload as Record<string, unknown>),
          marked: true,
        }),
      } as any,
      (options) => {
        attempts += 1;
        if (attempts === 1) {
          return failedStream({ errorMessage: "400 status code (no body)" });
        }
        repairOptions = options as typeof repairOptions;
        return successfulStream();
      },
      {
        claim,
        headers: () => undefined,
        status: () => 400,
        sleep,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(2);
    expect(events).toEqual(["start", "done"]);
    expect((await stream.result()).stopReason).toBe("stop");
    // The repair is neither a budget retry nor a paced one.
    expect(claim).not.toHaveBeenCalled();
    expect(sleep).not.toHaveBeenCalled();
    // The repair wraps the caller hook: its rewrite survives, the limit does not.
    const repaired = await repairOptions?.onPayload?.({
      model: "glm-5.3-flash",
      max_tokens: 4096,
      max_completion_tokens: 1_044_472,
      max_output_tokens: 1_044_472,
      messages: [{ role: "user", content: "hi" }],
    });
    expect(repaired).toEqual({
      marked: true,
      model: "glm-5.3-flash",
      messages: [{ role: "user", content: "hi" }],
    });
  });

  it("does not start the repair after the request is aborted", async () => {
    const abortController = new AbortController();
    let attempts = 0;
    const stream = createProviderRetryStream(
      model,
      context,
      { signal: abortController.signal },
      () => {
        attempts += 1;
        const result = createAssistantMessageEventStream();
        const error = assistantMessage({ errorMessage: "400 status code (no body)" });
        queueMicrotask(() => {
          result.push({ type: "error", reason: "error", error });
          abortController.abort();
          result.end(error);
        });
        return result;
      },
      {
        claim: vi.fn(() => undefined),
        headers: () => undefined,
        status: () => 400,
        sleep: async () => undefined,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(1);
    expect(events).toEqual(["error"]);
    expect((await stream.result()).stopReason).toBe("aborted");
  });

  it("surfaces the original error when the repaired attempt fails the same way", async () => {
    let attempts = 0;
    const claim = vi.fn(() => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({ errorMessage: "400 status code (no body)" });
      },
      {
        claim,
        headers: () => undefined,
        status: () => 400,
        sleep: async () => undefined,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(2);
    expect(events).toEqual(["error"]);
    const result = await stream.result();
    expect(result.stopReason).toBe("error");
    expect(result.errorMessage).toBe("400 status code (no body)");
    // Only the failed repair reaches the budget; the opaque first failure never did.
    expect(claim).toHaveBeenCalledTimes(1);
    expect(claim).toHaveBeenCalledWith(
      expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false }),
      "request",
    );
  });

  it("surfaces descriptive 400 bodies without attempting a repair", async () => {
    let attempts = 0;
    const claim = vi.fn(() => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({
          errorMessage: '400: {"error":{"message":"Model does not exist."}}',
        });
      },
      {
        claim,
        headers: () => undefined,
        status: () => 400,
        sleep: async () => undefined,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(1);
    expect(events).toEqual(["error"]);
    // A descriptive body is terminal, and the budget is consulted and refuses it.
    expect(claim).toHaveBeenCalledTimes(1);
    expect(claim).toHaveBeenCalledWith(
      expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false }),
      "request",
    );
  });

  it("strips only the output-limit fields", () => {
    expect(
      stripOutputLimitFields({
        model: "m",
        max_tokens: 1,
        max_completion_tokens: 2,
        max_output_tokens: 3,
        stream: true,
      }),
    ).toEqual({ model: "m", stream: true });
    expect(stripOutputLimitFields("raw")).toBe("raw");
  });

  it("keeps the repair options otherwise unchanged", () => {
    const options = { maxRetries: 0, fetch: globalThis.fetch } as any;
    const repaired = withoutDerivedOutputLimit(options);
    expect(repaired.maxRetries).toBe(0);
    expect(repaired.fetch).toBe(options.fetch);
    expect(typeof repaired.onPayload).toBe("function");
  });
});

const OPENAI_OUTPUT_CEILING =
  "OpenAI API error (400): max_tokens is too large: 16384. This model supports at most 4096 completion tokens, whereas you provided 16384.";
const ANTHROPIC_OUTPUT_CEILING =
  'API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 65537 > 64000, which is the maximum allowed number of output tokens for claude-opus-4-5-20251101"}}';
const DEEPSEEK_OUTPUT_CEILING =
  "400 Invalid max_tokens value, the valid range of max_tokens is [1, 8192]";
const GROQ_OUTPUT_CEILING =
  "`max_tokens` must be less than or equal to `16384`, the maximum value for `max_tokens` is less than the `context_window` for this model";
const PERPLEXITY_OUTPUT_CEILING =
  '400: {"error":{"message":"max_tokens must be at most 128000","type":"invalid_request","code":400,"param":"max_tokens"}}';
const MINIMAX_OUTPUT_CEILING =
  "400: invalid params, model[MiniMax-M2] does not support max tokens > 196608 (2013)";

describe("outputTokenCeiling", () => {
  it("reads the upper bound of a DeepSeek max_tokens range", () => {
    expect(outputTokenCeiling(DEEPSEEK_OUTPUT_CEILING)).toBe(8192);
  });

  it("reads DashScope ranges, including the native error prefix", () => {
    expect(outputTokenCeiling("Range of max_tokens should be [1, 8192]")).toBe(8192);
    expect(
      outputTokenCeiling(
        "<400> InternalError.Algo.InvalidParameter: Range of max_tokens should be [1, 65536]",
      ),
    ).toBe(65536);
  });

  it("reads a max_completion_tokens range the same way", () => {
    expect(
      outputTokenCeiling("valid range of max_completion_tokens is [1, 8192]"),
    ).toBe(8192);
    expect(
      outputTokenCeiling("valid range of `max_completion_tokens` is [`1`, `8192`]"),
    ).toBe(8192);
  });

  it("reads a Groq ceiling with or without backticks", () => {
    expect(outputTokenCeiling(GROQ_OUTPUT_CEILING)).toBe(16384);
    expect(
      outputTokenCeiling(
        "max_tokens must be less than or equal to 16384, the maximum value for max_tokens is less than the context_window for this model",
      ),
    ).toBe(16384);
  });

  it("keeps comma-grouped bounds", () => {
    expect(
      outputTokenCeiling("Range of max_tokens should be [1, 65,536]"),
    ).toBe(65536);
    expect(
      outputTokenCeiling("max_completion_tokens must be less than or equal to 16,384"),
    ).toBe(16384);
  });

  it("reads a Perplexity at-most ceiling with or without backticks", () => {
    expect(outputTokenCeiling("max_tokens must be at most 128000")).toBe(128000);
    expect(outputTokenCeiling("`max_tokens` must be at most 128000")).toBe(128000);
    expect(outputTokenCeiling(PERPLEXITY_OUTPUT_CEILING)).toBe(128000);
    expect(
      outputTokenCeiling("InvalidRequestError: max_tokens must be at most 4096"),
    ).toBe(4096);
    expect(
      outputTokenCeiling("max_completion_tokens must be at most 8,192"),
    ).toBe(8192);
    expect(
      outputTokenCeiling("`max_output_tokens` must be at most `4096`"),
    ).toBe(4096);
  });

  it("reads a MiniMax max tokens ceiling and ignores the business code", () => {
    expect(
      outputTokenCeiling(
        "invalid params, model[MiniMax-M2] does not support max tokens > 196608 (2013)",
      ),
    ).toBe(196608);
    expect(outputTokenCeiling(MINIMAX_OUTPUT_CEILING)).toBe(196608);
  });

  it("treats those 400s as output-limit rejections", () => {
    expect(
      isOutputLimitRejection(
        classifyAgentError("400: max_tokens must be at most 128000"),
      ),
    ).toBe(true);
    expect(
      isOutputLimitRejection(classifyAgentError(MINIMAX_OUTPUT_CEILING)),
    ).toBe(true);
    expect(
      isOutputLimitRejection(
        classifyAgentError(
          "400: Prompt tokens plus max_tokens must be at most 131,072",
        ),
      ),
    ).toBe(false);
  });

  it("does not treat a context-length message as an output ceiling", () => {
    expect(outputTokenCeiling("maximum context length is 131072 tokens")).toBeUndefined();
    expect(outputTokenCeiling("Range of input length should be [1, 30720]")).toBeUndefined();
    expect(
      outputTokenCeiling("Prompt tokens plus max_tokens must be at most 131,072"),
    ).toBeUndefined();
    expect(
      outputTokenCeiling("Prompt tokens plus `max_tokens` must be at most 131,072"),
    ).toBeUndefined();
  });
});

describe("explicit output-limit repair", () => {
  async function repairPayload(
    errorMessage: string,
    payload: Record<string, unknown>,
  ): Promise<{ attempts: number; repaired: unknown; claim: ReturnType<typeof vi.fn>; sleep: ReturnType<typeof vi.fn> }> {
    let attempts = 0;
    let repairOptions: { onPayload?: (payload: unknown) => Promise<unknown> } | undefined;
    const claim = vi.fn(() => undefined);
    const sleep = vi.fn(async () => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {
        onPayload: async (body: unknown) => ({
          ...(body as Record<string, unknown>),
          marked: true,
        }),
      } as any,
      (options) => {
        attempts += 1;
        if (attempts === 1) return failedStream({ errorMessage });
        repairOptions = options as typeof repairOptions;
        return successfulStream();
      },
      {
        claim,
        headers: () => undefined,
        status: () => undefined,
        sleep,
      },
    );
    for await (const _event of stream) {
      // Drain so the repair hook is installed before we inspect it.
    }
    return {
      attempts,
      repaired: await repairOptions?.onPayload?.(payload),
      claim,
      sleep,
    };
  }

  it("clamps an OpenAI completion ceiling instead of failing the turn", async () => {
    const result = await repairPayload(OPENAI_OUTPUT_CEILING, {
      model: "ft:gpt-4o",
      max_tokens: 16384,
      max_completion_tokens: 16384,
      temperature: 0,
    });

    expect(result.attempts).toBe(2);
    expect(result.claim).not.toHaveBeenCalled();
    expect(result.sleep).not.toHaveBeenCalled();
    expect(result.repaired).toEqual({
      marked: true,
      model: "ft:gpt-4o",
      max_tokens: 4096,
      max_completion_tokens: 4096,
      temperature: 0,
    });
  });

  it("clamps an Anthropic output ceiling without dropping max_tokens", async () => {
    const result = await repairPayload(ANTHROPIC_OUTPUT_CEILING, {
      model: "claude-opus-4-5-20251101",
      max_tokens: 65537,
      messages: [{ role: "user", content: "hi" }],
    });

    expect(result.attempts).toBe(2);
    expect(result.claim).not.toHaveBeenCalled();
    expect(result.sleep).not.toHaveBeenCalled();
    expect(result.repaired).toEqual({
      marked: true,
      model: "claude-opus-4-5-20251101",
      max_tokens: 64000,
      messages: [{ role: "user", content: "hi" }],
    });
  });

  it("leaves credit and context-overflow 400s terminal", async () => {
    const credit = await repairPayload(
      "400 This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 1000.",
      { max_tokens: 65536 },
    );
    const overflow = await repairPayload(
      "400 prompt is too long: 213462 tokens > 200000 maximum",
      { max_tokens: 64000 },
    );

    expect(credit.attempts).toBe(1);
    expect(overflow.attempts).toBe(1);
    expect(credit.claim).toHaveBeenCalledTimes(1);
    expect(overflow.claim).toHaveBeenCalledTimes(1);
  });

  it("clamps a DeepSeek max_tokens range instead of failing the turn", async () => {
    const result = await repairPayload(DEEPSEEK_OUTPUT_CEILING, {
      max_tokens: 32000,
    });

    expect(result.attempts).toBe(2);
    expect(result.claim).not.toHaveBeenCalled();
    expect(result.sleep).not.toHaveBeenCalled();
    expect(result.repaired).toEqual({
      marked: true,
      max_tokens: 8192,
    });
  });

  it("clamps a Perplexity at-most ceiling instead of failing the turn", async () => {
    const result = await repairPayload(PERPLEXITY_OUTPUT_CEILING, {
      max_tokens: 200000,
      stream: true,
    });

    expect(result.attempts).toBe(2);
    expect(result.claim).not.toHaveBeenCalled();
    expect(result.sleep).not.toHaveBeenCalled();
    expect(result.repaired).toEqual({
      marked: true,
      max_tokens: 128000,
      stream: true,
    });
  });

  it("clamps a MiniMax max tokens ceiling and ignores the business code", async () => {
    const result = await repairPayload(MINIMAX_OUTPUT_CEILING, {
      max_tokens: 200000,
    });

    expect(result.attempts).toBe(2);
    expect(result.claim).not.toHaveBeenCalled();
    expect(result.sleep).not.toHaveBeenCalled();
    expect(result.repaired).toEqual({
      marked: true,
      max_tokens: 196608,
    });
  });

  it("leaves a prompt-plus-max_tokens context sum terminal", async () => {
    const result = await repairPayload(
      "400: Prompt tokens plus max_tokens must be at most 131,072",
      { max_tokens: 65536 },
    );

    expect(result.attempts).toBe(1);
    expect(result.claim).toHaveBeenCalledTimes(1);
  });

  it("clamps a proxy expected-value ceiling without adding a missing field", async () => {
    const result = await repairPayload(
      '400 {"error":{"code":"InvalidParameter","message":"The parameter max_tokens specified in the request is not valid: integer above maximum value, expected a value <= 32768, but got 64000 instead."}}',
      { max_tokens: 64000, stream: true },
    );

    expect(result.attempts).toBe(2);
    expect(result.repaired).toEqual({
      marked: true,
      max_tokens: 32768,
      stream: true,
    });
  });

  it("surfaces the original ceiling error when the clamped attempt fails the same way", async () => {
    let attempts = 0;
    const claim = vi.fn(() => undefined);
    const stream = createProviderRetryStream(
      model,
      context,
      {},
      () => {
        attempts += 1;
        return failedStream({ errorMessage: OPENAI_OUTPUT_CEILING });
      },
      {
        claim,
        headers: () => undefined,
        status: () => undefined,
        sleep: async () => undefined,
      },
    );

    const events: string[] = [];
    for await (const event of stream) events.push(event.type);

    expect(attempts).toBe(2);
    expect(events).toEqual(["error"]);
    expect((await stream.result()).errorMessage).toBe(OPENAI_OUTPUT_CEILING);
    expect(claim).toHaveBeenCalledTimes(1);
  });
});

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 supported idle minimum", () => {
    const previous = process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
    try {
      // 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);
      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();
    }
  });
});