Three defects found by driving the real admin panel, none of which a
typecheck or a unit test would have caught:
- The API key could not be entered at all. Field-level read access denies
the value, and Payload does not render a field you cannot read, so the
input was absent while the collection said it existed. The input is now
a `ui` component that writes the hidden value through useField, which
keeps the key server-only and gives it a working control.
- The probe panel and key input used frontend/ zinc styling, which reads
as an accidental dark block on the admin panel's light theme. They now
use the admin bundle's own --theme-elevation variables.
- An unreachable host reported "fetch failed" with no cause. Node hides
the connect error inside `cause`, and that string ("connect
ECONNREFUSED 10.0.0.5:8888") is the only part an admin can act on, so
it is now included.
Also labels the acronym fields ("Base URL", "Model ID", "Has API key")
and covers the unreachable-host path in the generate-modes spec.
173 lines
5.9 KiB
TypeScript
173 lines
5.9 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("names the connection and the underlying cause when the host is unreachable", async () => {
|
|
// A closed port is the realistic mistake (a typo in the base URL). Node hides
|
|
// the connect error inside `cause`, which is the only actionable part. Bind a
|
|
// port and release it so the port is free without guessing a number.
|
|
const probe = createServer();
|
|
await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
|
|
const freePort = (probe.address() as AddressInfo).port;
|
|
await new Promise<void>((resolve) => probe.close(() => resolve()));
|
|
|
|
await expect(
|
|
generatePlainText("ping", "probe", "env-model", {
|
|
connection: connection({ baseUrl: `http://127.0.0.1:${freePort}/v1` }),
|
|
}),
|
|
).rejects.toThrow(/Probe box request failed[\s\S]*(ECONNREFUSED|fetch failed)/);
|
|
});
|
|
|
|
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();
|
|
});
|
|
});
|