From 802e2391a8e050366dfce9d58b838ac8a2dad9b3 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 1 Dec 2026 13:00:56 -0500 Subject: [PATCH] test(ai): reach the lazy stream through a seam instead of mocking the module The lazy-stream guard passed alone and timed out in a full run: the test worker shares one module registry between files, so when another spec had already loaded `ai`, `vi.mock` was ignored and `generateStructured` bound the real `streamObject`. generateStructured takes an optional stream factory now, and the test supplies a stub whose object is released by the first pull of its text stream. Same proof (the drain is what makes the object resolve), no timers, no module mocking, no dependence on file order. --- src/lib/ai/generate.ts | 25 ++++++++++- tests/int/ai-structured-stream.int.spec.ts | 48 ++++++++++------------ 2 files changed, 45 insertions(+), 28 deletions(-) diff --git a/src/lib/ai/generate.ts b/src/lib/ai/generate.ts index bb69774f..d216f7d5 100644 --- a/src/lib/ai/generate.ts +++ b/src/lib/ai/generate.ts @@ -316,6 +316,19 @@ export async function generatePlainText( }; } +/** + * The shape `generateStructured` needs from a structured stream. Narrow on + * purpose: it lets a test supply a lazy stream without mocking the whole `ai` + * module, and it keeps the production call readable. + */ +export interface StructuredStreamFactory { + (options: Record): { + textStream: AsyncIterable; + object: Promise; + finishReason: Promise; + }; +} + export interface StructuredGenerationOptions { /** The user-turn instruction. */ prompt: string; @@ -336,6 +349,13 @@ export interface StructuredGenerationOptions { * callers pass something smaller. */ timeoutMs?: number; + /** + * Seam for tests. Production always uses the SDK's `streamObject`; a test that + * needs to model a lazy provider stream supplies its own here, because + * mocking the `ai` module is unreliable when the test worker shares a module + * registry between files. + */ + streamFactory?: StructuredStreamFactory; } export interface StructuredResult { @@ -410,7 +430,8 @@ export async function generateStructured( const reasoning = connection ? connection.sendReasoningOff !== false : true; - const result = streamObject({ + const factory = options.streamFactory ?? (streamObject as unknown as StructuredStreamFactory); + const result = factory({ maxOutputTokens: options.maxTokens ?? 5000, // No transport retries. The SDK's default (two) turns one stalled stream into // three sequential waits, which is how a 60s idle abort became a multi-minute @@ -422,7 +443,7 @@ export async function generateStructured( // modal waits on `result.object` for as long as the stream dribbles. abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS), model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()), - onError: (error) => { + onError: (error: unknown) => { console.error("AI generateStructured: ", error); }, prompt: options.prompt, diff --git a/tests/int/ai-structured-stream.int.spec.ts b/tests/int/ai-structured-stream.int.spec.ts index 3f57d9d4..cced7d14 100644 --- a/tests/int/ai-structured-stream.int.spec.ts +++ b/tests/int/ai-structured-stream.int.spec.ts @@ -1,5 +1,8 @@ // @vitest-environment node -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; + +import type { StructuredStreamFactory } from "@/lib/ai/generate"; +import { generateStructured } from "@/lib/ai/generate"; /** * Regression: `streamObject`'s stream is lazy, so `result.object` never resolves @@ -7,34 +10,26 @@ import { describe, expect, it, vi } from "vitest"; * what made every NPC draft hang on "Drafting..." against OpenRouter, with the * provider having delivered a complete answer. * - * The stub below models that laziness: `object` resolves only after the text - * stream has been read. + * The stub models that laziness: `object` is released by the first pull of the + * text stream, with no timers. Reaching the object means the drain ran. It is + * injected through the factory seam rather than by mocking `ai`, because a test + * worker shares one module registry across files and a mock registered here is + * ignored when another spec has already loaded the real module. */ -vi.mock("ai", async (importOriginal) => { - const actual = await importOriginal(); +const lazyStream: StructuredStreamFactory = () => { + const holder: { release?: (value: unknown) => void } = {}; + const object = new Promise((resolve) => { + holder.release = resolve; + }); return { - ...actual, - streamObject: () => { - let drained = false; - return { - textStream: (async function* () { - drained = true; - yield '{"nodes":[{"id":"n1"}]}'; - })(), - object: new Promise((resolve) => { - const timer = setInterval(() => { - if (!drained) return; - clearInterval(timer); - resolve({ nodes: [{ id: "n1" }] }); - }, 5); - }), - finishReason: Promise.resolve("stop"), - }; - }, + textStream: (async function* () { + holder.release?.({ nodes: [{ id: "n1" }] }); + yield '{"nodes":[{"id":"n1"}]}'; + })(), + object, + finishReason: Promise.resolve("stop"), }; -}); - -const { generateStructured } = await import("@/lib/ai/generate"); +}; describe("structured generation drives the stream", () => { it("resolves the object instead of waiting on a lazy stream", async () => { @@ -50,6 +45,7 @@ describe("structured generation drives the stream", () => { structuredMode: "json_schema", sendReasoningOff: false, }, + streamFactory: lazyStream, }); expect(result.object.nodes).toHaveLength(1);