1
0
Fork 0

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.
This commit is contained in:
Jason Fraley 2026-12-01 13:00:56 -05:00
parent 1db89addf5
commit 802e2391a8
2 changed files with 45 additions and 28 deletions

View file

@ -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<string, unknown>): {
textStream: AsyncIterable<string>;
object: Promise<unknown>;
finishReason: Promise<string>;
};
}
export interface StructuredGenerationOptions { export interface StructuredGenerationOptions {
/** The user-turn instruction. */ /** The user-turn instruction. */
prompt: string; prompt: string;
@ -336,6 +349,13 @@ export interface StructuredGenerationOptions {
* callers pass something smaller. * callers pass something smaller.
*/ */
timeoutMs?: number; 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<T> { export interface StructuredResult<T> {
@ -410,7 +430,8 @@ export async function generateStructured<T>(
const reasoning = connection ? connection.sendReasoningOff !== false : true; 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, maxOutputTokens: options.maxTokens ?? 5000,
// No transport retries. The SDK's default (two) turns one stalled stream into // 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 // three sequential waits, which is how a 60s idle abort became a multi-minute
@ -422,7 +443,7 @@ export async function generateStructured<T>(
// modal waits on `result.object` for as long as the stream dribbles. // modal waits on `result.object` for as long as the stream dribbles.
abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS), abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS),
model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()), model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()),
onError: (error) => { onError: (error: unknown) => {
console.error("AI generateStructured: ", error); console.error("AI generateStructured: ", error);
}, },
prompt: options.prompt, prompt: options.prompt,

View file

@ -1,5 +1,8 @@
// @vitest-environment node // @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 * 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 * what made every NPC draft hang on "Drafting..." against OpenRouter, with the
* provider having delivered a complete answer. * provider having delivered a complete answer.
* *
* The stub below models that laziness: `object` resolves only after the text * The stub models that laziness: `object` is released by the first pull of the
* stream has been read. * 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 lazyStream: StructuredStreamFactory = () => {
const actual = await importOriginal<typeof import("ai")>(); const holder: { release?: (value: unknown) => void } = {};
const object = new Promise((resolve) => {
holder.release = resolve;
});
return { return {
...actual, textStream: (async function* () {
streamObject: () => { holder.release?.({ nodes: [{ id: "n1" }] });
let drained = false; yield '{"nodes":[{"id":"n1"}]}';
return { })(),
textStream: (async function* () { object,
drained = true; finishReason: Promise.resolve("stop"),
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"),
};
},
}; };
}); };
const { generateStructured } = await import("@/lib/ai/generate");
describe("structured generation drives the stream", () => { describe("structured generation drives the stream", () => {
it("resolves the object instead of waiting on a lazy stream", async () => { 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", structuredMode: "json_schema",
sendReasoningOff: false, sendReasoningOff: false,
}, },
streamFactory: lazyStream,
}); });
expect(result.object.nodes).toHaveLength(1); expect(result.object.nodes).toHaveLength(1);