// @vitest-environment node import { describe, expect, it } from "vitest"; import { idleWatchdogFetch, PROVIDER_IDLE_TIMEOUT_MS } from "@/lib/ai/generate"; /** * The idle watchdog exists because a provider can answer 200, stream part of a * response, and then go quiet without finishing or closing. These tests drive * the wrapper with fake streams: a healthy body must pass through unchanged, a * silent one must fail fast instead of waiting for a total timeout. */ describe("provider idle watchdog", () => { it("is a full minute by default", () => { expect(PROVIDER_IDLE_TIMEOUT_MS).toBe(60_000); }); it("delivers a healthy stream byte for byte", async () => { const encoder = new TextEncoder(); const body = new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("data: one\n\n")); controller.enqueue(encoder.encode("data: two\n\n")); controller.close(); }, }); const originalFetch = globalThis.fetch; globalThis.fetch = async () => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }); try { const response = await idleWatchdogFetch(500)("https://example.test/chat/completions"); expect(response.status).toBe(200); expect(response.headers.get("content-type")).toBe("text/event-stream"); await expect(response.text()).resolves.toBe("data: one\n\ndata: two\n\n"); } finally { globalThis.fetch = originalFetch; } }); it("fails a stream that stops sending instead of hanging", async () => { const encoder = new TextEncoder(); const body = new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("data: partial\n\n")); // Never closes: this is the OpenRouter stall, in miniature. }, }); const originalFetch = globalThis.fetch; globalThis.fetch = async () => new Response(body, { status: 200 }); try { const response = await idleWatchdogFetch(60)("https://example.test/chat/completions"); const started = Date.now(); await expect(response.text()).rejects.toThrow(/stopped sending data/i); // Fast, not after a total timeout: the silence window, not the call budget. expect(Date.now() - started).toBeLessThan(2_000); } finally { globalThis.fetch = originalFetch; } }); it("leaves a body-less response alone", async () => { const originalFetch = globalThis.fetch; globalThis.fetch = async () => new Response(null, { status: 204 }); try { const response = await idleWatchdogFetch(50)("https://example.test/chat/completions"); expect(response.status).toBe(204); expect(response.body).toBeNull(); } finally { globalThis.fetch = originalFetch; } }); });