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.
54 lines
2 KiB
TypeScript
54 lines
2 KiB
TypeScript
// @vitest-environment node
|
|
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
|
|
* unless something drains the stream first. Awaiting only the object promise is
|
|
* what made every NPC draft hang on "Drafting..." against OpenRouter, with the
|
|
* provider having delivered a complete answer.
|
|
*
|
|
* 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.
|
|
*/
|
|
const lazyStream: StructuredStreamFactory = () => {
|
|
const holder: { release?: (value: unknown) => void } = {};
|
|
const object = new Promise((resolve) => {
|
|
holder.release = resolve;
|
|
});
|
|
return {
|
|
textStream: (async function* () {
|
|
holder.release?.({ nodes: [{ id: "n1" }] });
|
|
yield '{"nodes":[{"id":"n1"}]}';
|
|
})(),
|
|
object,
|
|
finishReason: Promise.resolve("stop"),
|
|
};
|
|
};
|
|
|
|
describe("structured generation drives the stream", () => {
|
|
it("resolves the object instead of waiting on a lazy stream", async () => {
|
|
const result = await generateStructured<{ nodes: { id: string }[] }>({
|
|
prompt: "Draft something.",
|
|
system: "Stub.",
|
|
schema: { type: "object", properties: {}, additionalProperties: false },
|
|
connection: {
|
|
label: "stub",
|
|
baseUrl: "https://example.test/v1",
|
|
modelId: "stub-model",
|
|
apiKey: "unused",
|
|
structuredMode: "json_schema",
|
|
sendReasoningOff: false,
|
|
},
|
|
streamFactory: lazyStream,
|
|
});
|
|
|
|
expect(result.object.nodes).toHaveLength(1);
|
|
expect(result.truncated).toBe(false);
|
|
});
|
|
});
|