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 = {}) => 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, }); await payload.update({ collection: "ai-connections", id: connection.id, data: { modelId: "some-other-model" }, overrideAccess: true, }); // Read back from the database: an afterChange return value is only ever the // response of the operation, so asserting the update's own result would pass // while the stored row kept saying "passed". const stored = await payload.findByID({ collection: "ai-connections", id: connection.id, overrideAccess: true, }); expect(stored.lastTestOk).toBe(false); expect(stored.lastTestMessage).toContain("run the test again"); }); it("keeps a fresh test result when only the result is written", async () => { const connection = await createConnection(); // The Test button patches the result fields alone. If an absent field counted // as "changed", that write would immediately invalidate itself. await payload.update({ collection: "ai-connections", id: connection.id, data: { lastTestOk: true, lastTestMessage: "passed" }, overrideAccess: true, }); const stored = await payload.findByID({ collection: "ai-connections", id: connection.id, overrideAccess: true, }); expect(stored.lastTestOk).toBe(true); expect(stored.lastTestMessage).toBe("passed"); }); });