1
0
Fork 0
polaris-task-force/tests/int/ai-generate-modes.int.spec.ts
Z8MB1E 7abca7185c feat(ai): add admin-configurable model connections
Every AI surface talked to the Unsloth box through env vars, so swapping
provider or model meant editing .env and restarting. A connection is now
a stored record: base URL, model id, key, structured-output mode, and a
reasoning toggle.

Three surfaces with their own selector (Compose, dialogue draft, line
rewrite), because they want different things from a model: a draft needs
strict schema adherence while a line rewrite only needs prose. Blank
means the env defaults, so an empty global behaves exactly as before.

The API key is write-only: field read access denies everyone, so it never
reaches the admin form, REST, GraphQL, or a populated relationship. Blank
submission means "unchanged" and `clearApiKey` is the only delete, which
avoids the masked-field-round-trips-empty bug. Backups still contain it;
a blank connection key falls back to UNSLOTH_API_KEY for that reason.

Structured output is no longer assumed to be json_schema. Some
OpenAI-compatible providers reject it, so a connection selects
json_schema, json_object or prompt, and the weaker modes serialise the
schema into the prompt and parse the reply. The Test button runs a plain
probe and a structured probe, because a provider that refuses json_schema
passes the first and fails every draft.

Compose keeps a single fixed dropdown entry: plugin config is built at
boot and cannot list database rows, so the handler resolves the selected
connection per request instead.

Draft provenance records the connection label, so a stored conversation
still names the provider that produced it.
2026-11-24 13:04:39 -05:00

157 lines
5.1 KiB
TypeScript

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<string, unknown> };
let captured: Captured[] = [];
let reply = "";
let status = 200;
let server: ReturnType<typeof createServer>;
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<string, unknown>,
});
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<void>((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<void>((resolve) => server.close(() => resolve()));
});
const connection = (overrides: Partial<AiConnection> = {}): 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();
});
});