1
0
Fork 0
polaris-task-force/tests/int/ai-connections.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

213 lines
6.9 KiB
TypeScript

import type { Payload } from "payload";
import { beforeAll, describe, expect, it } from "vitest";
import { getTestPayload } from "../helpers/get-test-payload";
import { resolveConnection } from "@/lib/ai/connections";
/**
* The connection record is where a swapped provider can break silently, so the two
* things that must not drift are pinned here: the write-only key contract, and the
* resolution the AI calls actually perform.
*
* The key rules exist because the field's read access denies everyone, so the admin
* form can never show the stored value. That makes a blank submission ambiguous
* ("unchanged" or "delete?"), which is why blank means unchanged and `clearApiKey`
* is the only delete.
*/
let payload: Payload;
beforeAll(async () => {
payload = await getTestPayload();
});
const createConnection = (overrides: Record<string, unknown> = {}) =>
payload.create({
collection: "ai-connections",
data: {
label: "Unit box",
baseUrl: "http://192.168.1.7:8888/v1",
modelId: "unsloth/Ornith-1.0-9B-GGUF",
structuredMode: "json_schema",
sendReasoningOff: true,
...overrides,
},
overrideAccess: true,
});
describe("ai-connections key handling", () => {
it("denies the key field to every reader that does not bypass access", async () => {
const created = await createConnection({ apiKey: "sk-test-secret" });
expect(created.hasApiKey).toBe(true);
// The local API defaults to overrideAccess: true, so a plain findByID proves
// nothing about the gate. Assert the field's own access rule instead: this is
// what strips the value from REST, GraphQL and the admin form.
const collection = payload.config.collections.find((c) => c.slug === "ai-connections");
const field = collection?.fields.find(
(candidate) => "name" in candidate && candidate.name === "apiKey",
) as { access?: { read?: (args: unknown) => unknown } } | undefined;
expect(typeof field?.access?.read).toBe("function");
expect(await field?.access?.read?.({ req: {} })).toBe(false);
});
it("hides the collection from a caller without the superuser tier", async () => {
await createConnection({ apiKey: "sk-test-secret" });
await expect(
payload.find({ collection: "ai-connections", overrideAccess: false, depth: 0 }),
).rejects.toThrow(/not allowed/i);
});
it("keeps the stored key when the form submits it blank", async () => {
const created = await createConnection({ apiKey: "sk-first" });
const updated = await payload.update({
collection: "ai-connections",
id: created.id,
data: { label: "Renamed", apiKey: "" },
overrideAccess: true,
});
expect(updated.hasApiKey).toBe(true);
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-first");
});
it("replaces the key when a new value is submitted", async () => {
const created = await createConnection({ apiKey: "sk-first" });
await payload.update({
collection: "ai-connections",
id: created.id,
data: { apiKey: "sk-second" },
overrideAccess: true,
});
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-second");
});
it("clears the key only when clearApiKey is set, and resets the flag", async () => {
const created = await createConnection({ apiKey: "sk-first" });
const cleared = await payload.update({
collection: "ai-connections",
id: created.id,
data: { clearApiKey: true },
overrideAccess: true,
});
expect(cleared.hasApiKey).toBe(false);
// The checkbox is an action: leaving it ticked would clear a key set later.
expect(cleared.clearApiKey).toBe(false);
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey ?? null).toBeNull();
});
});
describe("resolveConnection", () => {
it("returns null when a surface has no connection selected", async () => {
await payload.updateGlobal({
slug: "ai-settings",
data: { composeConnection: null, dialogueDraftConnection: null, dialogueLineConnection: null },
overrideAccess: true,
});
expect(await resolveConnection(payload, "compose")).toBeNull();
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
expect(await resolveConnection(payload, "dialogue-line")).toBeNull();
});
it("resolves the connection selected for that surface only", async () => {
const draft = await createConnection({
label: "Draft box",
modelId: "draft-model",
apiKey: "sk-draft",
structuredMode: "json_object",
});
const line = await createConnection({
label: "Line box",
modelId: "line-model",
sendReasoningOff: false,
});
await payload.updateGlobal({
slug: "ai-settings",
data: {
composeConnection: null,
dialogueDraftConnection: draft.id,
dialogueLineConnection: line.id,
},
overrideAccess: true,
});
const draftResolved = await resolveConnection(payload, "dialogue-draft");
expect(draftResolved).toMatchObject({
label: "Draft box",
modelId: "draft-model",
apiKey: "sk-draft",
structuredMode: "json_object",
});
const lineResolved = await resolveConnection(payload, "dialogue-line");
expect(lineResolved).toMatchObject({
label: "Line box",
modelId: "line-model",
sendReasoningOff: false,
structuredMode: "json_schema",
});
// Compose was left blank, so it must keep using the env defaults.
expect(await resolveConnection(payload, "compose")).toBeNull();
});
it("falls back to the env defaults for a half-filled connection", async () => {
const connection = await createConnection({ modelId: " " });
await payload.updateGlobal({
slug: "ai-settings",
data: { dialogueDraftConnection: connection.id },
overrideAccess: true,
});
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
});
it("resets a passing test result when the configuration changes", async () => {
const connection = await createConnection();
await payload.update({
collection: "ai-connections",
id: connection.id,
data: { lastTestOk: true, lastTestMessage: "passed" },
overrideAccess: true,
});
const changed = await payload.update({
collection: "ai-connections",
id: connection.id,
data: { modelId: "some-other-model" },
overrideAccess: true,
});
expect(changed.lastTestOk).toBe(false);
expect(changed.lastTestMessage).toContain("run the test again");
});
});