import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { generatePlainText, generateStructured } from "@/lib/ai/generate"; import type { AiConnection } from "@/lib/ai/generate"; /** * The provider-aware paths are the ones a connection change can break, and they are * pure HTTP: a local server stands in for the model so the request body and the * reply parsing are checked without a GPU, a key, or the real model host. * * What is pinned here: the connection's URL and model win, the key travels in the * header, the reasoning toggle is honoured (a strict provider rejects unknown * fields), the non-strict structured modes actually degrade, and a provider error * surfaces its body instead of a bare status. */ type Captured = { url: string; auth: string | undefined; body: Record }; let captured: Captured[] = []; let reply = ""; let status = 200; let server: ReturnType; let baseUrl = ""; beforeAll(async () => { server = createServer((req, res) => { const chunks: Buffer[] = []; req.on("data", (chunk: Buffer) => chunks.push(chunk)); req.on("end", () => { captured.push({ url: req.url ?? "", auth: req.headers.authorization, body: JSON.parse(Buffer.concat(chunks).toString() || "{}") as Record, }); res.writeHead(status, { "Content-Type": "application/json" }); res.end( status === 200 ? JSON.stringify({ choices: [{ message: { content: reply }, finish_reason: "stop" }] }) : JSON.stringify({ error: { message: reply } }), ); }); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const address = server.address() as AddressInfo; baseUrl = `http://127.0.0.1:${address.port}/v1`; }); afterAll(async () => { await new Promise((resolve) => server.close(() => resolve())); }); const connection = (overrides: Partial = {}): AiConnection => ({ label: "Probe box", baseUrl, modelId: "probe-model", apiKey: "sk-probe", structuredMode: "json_schema", sendReasoningOff: true, ...overrides, }); const last = () => captured[captured.length - 1]; describe("generatePlainText with a connection", () => { it("posts to the connection's endpoint with its model and key", async () => { captured = []; reply = "ready"; const result = await generatePlainText("ping", "probe", "env-model", { connection: connection(), }); expect(result.text).toBe("ready"); expect(last().url).toBe("/v1/chat/completions"); expect(last().auth).toBe("Bearer sk-probe"); expect(last().body.model).toBe("probe-model"); }); it("sends reasoning off when the connection allows it, and omits it otherwise", async () => { captured = []; reply = "ok"; await generatePlainText("ping", "probe", "env-model", { connection: connection() }); expect(last().body.reasoning_effort).toBe("none"); await generatePlainText("ping", "probe", "env-model", { connection: connection({ sendReasoningOff: false }), }); expect(last().body).not.toHaveProperty("reasoning_effort"); }); it("reports a provider error with its status and body", async () => { captured = []; status = 401; reply = "Invalid API key"; await expect( generatePlainText("ping", "probe", "env-model", { connection: connection() }), ).rejects.toThrow(/Probe box API error: 401[\s\S]*Invalid API key/); status = 200; }); }); describe("generateStructured modes", () => { const schema = { type: "object", properties: { status: { type: "string" } }, required: ["status"], additionalProperties: false, }; it("parses a fenced reply in prompt mode and describes the schema", async () => { captured = []; reply = '```json\n{"status":"ready"}\n```'; const result = await generateStructured<{ status: string }>({ prompt: "probe", schema, connection: connection({ structuredMode: "prompt" }), }); expect(result.object.status).toBe("ready"); // No provider-side JSON mode is claimed, so none is requested. expect(last().body).not.toHaveProperty("response_format"); const messages = last().body.messages as { role: string; content: string }[]; expect(messages[0].content).toContain("additionalProperties"); }); it("asks for json_object mode when the connection says so", async () => { captured = []; reply = '{"status":"ready"}'; const result = await generateStructured<{ status: string }>({ prompt: "probe", schema, connection: connection({ structuredMode: "json_object" }), }); expect(result.object.status).toBe("ready"); expect(last().body.response_format).toEqual({ type: "json_object" }); }); it("surfaces unparsable output as an error, so the caller's retry can act on it", async () => { captured = []; reply = "I am not JSON at all."; await expect( generateStructured({ prompt: "probe", schema, connection: connection({ structuredMode: "prompt" }), }), ).rejects.toThrow(); }); });