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);