From 31e6cd6509edaedbfe2bd3889d1f4ee444b6fb96 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 13:28:58 -0500 Subject: [PATCH] fix(ai): make the connection key enterable and the probe legible 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. --- src/app/(payload)/admin/importMap.js | 6 +- src/collections/server/AiConnections.ts | 18 +++- src/components/admin/ai/ApiKeyField.tsx | 84 +++++++++++++++++++ .../admin/ai/TestConnectionButton.tsx | 46 +++++++--- src/lib/ai/generate.ts | 43 ++++++---- tests/int/ai-generate-modes.int.spec.ts | 16 ++++ 6 files changed, 185 insertions(+), 28 deletions(-) create mode 100644 src/components/admin/ai/ApiKeyField.tsx diff --git a/src/app/(payload)/admin/importMap.js b/src/app/(payload)/admin/importMap.js index 19327ef7..550ef056 100644 --- a/src/app/(payload)/admin/importMap.js +++ b/src/app/(payload)/admin/importMap.js @@ -39,7 +39,8 @@ import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/component import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker' import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField' import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor' -import { default as default_b6b06afff77de9004b742c9e09ce66ea } from '@/components/admin/ai/TestConnectionButton' +import { ApiKeyField as ApiKeyField_572d447267c045e561786734c8c444d0 } from '@/components/admin/ai/ApiKeyField' +import { TestConnectionButton as TestConnectionButton_b6b06afff77de9004b742c9e09ce66ea } from '@/components/admin/ai/TestConnectionButton' import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl' import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client' import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client' @@ -100,7 +101,8 @@ export const importMap = { "@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b, "@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2, "@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759, - "@/components/admin/ai/TestConnectionButton#default": default_b6b06afff77de9004b742c9e09ce66ea, + "@/components/admin/ai/ApiKeyField#ApiKeyField": ApiKeyField_572d447267c045e561786734c8c444d0, + "@/components/admin/ai/TestConnectionButton#TestConnectionButton": TestConnectionButton_b6b06afff77de9004b742c9e09ce66ea, "@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380, "@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73, "@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73, diff --git a/src/collections/server/AiConnections.ts b/src/collections/server/AiConnections.ts index d27ea4d2..076ee13b 100644 --- a/src/collections/server/AiConnections.ts +++ b/src/collections/server/AiConnections.ts @@ -114,6 +114,7 @@ export const AiConnections: CollectionConfig = { { name: "baseUrl", type: "text", + label: "Base URL", required: true, admin: { description: @@ -123,6 +124,7 @@ export const AiConnections: CollectionConfig = { { name: "modelId", type: "text", + label: "Model ID", required: true, admin: { description: @@ -132,6 +134,7 @@ export const AiConnections: CollectionConfig = { { name: "apiKey", type: "text", + label: "API Key", access: { // Never leaves the server. The resolver reads it with overrideAccess. read: () => false, @@ -141,9 +144,21 @@ export const AiConnections: CollectionConfig = { "Stored encrypted at rest by the database, server-only. Leave blank to keep the current key.", }, }, + { + // Payload does not render a field you cannot read, so the input is a `ui` + // component that writes the hidden `apiKey` value through useField. + name: "apiKeyInput", + type: "ui", + admin: { + components: { + Field: "@/components/admin/ai/ApiKeyField#ApiKeyField", + }, + }, + }, { name: "hasApiKey", type: "checkbox", + label: "Has API key", admin: { readOnly: true, description: "Whether a key is stored. The key itself is never shown.", @@ -152,6 +167,7 @@ export const AiConnections: CollectionConfig = { { name: "clearApiKey", type: "checkbox", + label: "Clear API key", admin: { description: "Tick and save to delete the stored key. Cannot be undone.", }, @@ -198,7 +214,7 @@ export const AiConnections: CollectionConfig = { type: "ui", admin: { components: { - Field: "@/components/admin/ai/TestConnectionButton", + Field: "@/components/admin/ai/TestConnectionButton#TestConnectionButton", }, }, }, diff --git a/src/components/admin/ai/ApiKeyField.tsx b/src/components/admin/ai/ApiKeyField.tsx new file mode 100644 index 00000000..ed9846e2 --- /dev/null +++ b/src/components/admin/ai/ApiKeyField.tsx @@ -0,0 +1,84 @@ +"use client"; + +import { useState } from "react"; +import { useField } from "@payloadcms/ui"; + +/** + * Write-only API key input. + * + * The `apiKey` field itself has read access denied, which is what keeps the secret + * out of the admin form value, REST, GraphQL and populated relationships. The side + * effect is that Payload does not render a field you cannot read, so the input lives + * here as a `ui` field and writes the hidden value through `useField`. + * + * Only a *new* value is ever typed: the stored key is never shown, so the field + * starts empty on every load and an empty submission leaves the stored key alone + * (enforced by the collection's beforeChange). + */ +export function ApiKeyField() { + const { value, setValue } = useField({ path: "apiKey" }); + const { value: saved } = useField({ path: "hasApiKey" }); + const [reveal, setReveal] = useState(false); + + const forged = typeof value === "string" ? value : ""; + + return ( +
+ + +
+ setValue(event.target.value)} + style={{ + flex: 1, + padding: "0.5rem 0.75rem", + border: "1px solid var(--theme-elevation-150)", + borderRadius: "4px", + background: "var(--theme-input-bg)", + color: "var(--theme-text)", + fontFamily: "monospace", + }} + /> + +
+ +

+ {saved + ? "A key is stored and never displayed. Type a new value to replace it." + : "Leave blank to use the UNSLOTH_API_KEY environment variable."}{" "} + Blank means unchanged; use Clear API key to delete it. +

+
+ ); +} diff --git a/src/components/admin/ai/TestConnectionButton.tsx b/src/components/admin/ai/TestConnectionButton.tsx index 82d6c135..3fd56bc0 100644 --- a/src/components/admin/ai/TestConnectionButton.tsx +++ b/src/components/admin/ai/TestConnectionButton.tsx @@ -13,9 +13,30 @@ import { useDocumentInfo } from "@payloadcms/ui"; * edit has to be saved first; that is called out rather than silently probing the * old values. * - * Styled in zinc because the admin bundle does not load the frontend theme's CSS - * variables (see the root AGENTS.md note on custom admin field components). + * Styled with the admin panel's own elevation variables so it reads correctly in + * both the light and dark admin themes. The frontend theme's CSS variables do not + * exist in this bundle. */ +const frame: React.CSSProperties = { + marginTop: "0.5rem", + marginBottom: "1.5rem", + padding: "0.75rem", + border: "1px solid var(--theme-elevation-150)", + borderRadius: "4px", + background: "var(--theme-elevation-50)", +}; + +const button: React.CSSProperties = { + padding: "0.4rem 0.75rem", + border: "1px solid var(--theme-elevation-200)", + borderRadius: "4px", + background: "var(--theme-elevation-100)", + color: "var(--theme-text)", + fontSize: "0.8rem", + fontWeight: 500, + cursor: "pointer", +}; + export function TestConnectionButton() { const { id } = useDocumentInfo(); const [busy, setBusy] = useState(false); @@ -34,7 +55,8 @@ export function TestConnectionButton() { const data = (await response.json()) as { ok?: boolean; message?: string }; setResult({ ok: Boolean(data.ok), - message: data.message ?? (response.ok ? "Test finished." : `Test failed (${response.status}).`), + message: + data.message ?? (response.ok ? "Test finished." : `Test failed (${response.status}).`), }); } catch (error) { setResult({ @@ -49,17 +71,17 @@ export function TestConnectionButton() { const saved = typeof id === "number" || typeof id === "string"; return ( -
-
+
+
- + {saved ? "Sends one plain prompt and one structured prompt. Save first; the test uses the stored values." : "Save this connection before testing it."} @@ -68,9 +90,13 @@ export function TestConnectionButton() { {result ? (

{result.ok ? "Passed. " : "Failed. "} {result.message} diff --git a/src/lib/ai/generate.ts b/src/lib/ai/generate.ts index 4dd2ede8..111f25e2 100644 --- a/src/lib/ai/generate.ts +++ b/src/lib/ai/generate.ts @@ -173,25 +173,38 @@ export async function generatePlainText( const connection = options.connection ?? null; const reasoning = connection ? connection.sendReasoningOff !== false : true; - const response = await fetch(completionsUrl(connection), { - method: "POST", + let response: Response; + try { + response = await fetch(completionsUrl(connection), { + method: "POST", headers: { Authorization: "Bearer " + (connection?.apiKey || process.env.UNSLOTH_API_KEY), "Content-Type": "application/json", }, - body: JSON.stringify({ - model: connection?.modelId || model, - messages: [ - { role: "system", content: system || "You are a helpful assistant." }, - { role: "user", content: prompt }, - ], - stream: false, - max_tokens: options.maxTokens ?? 5000, - temperature: options.temperature ?? 0.7, - ...(reasoning ? REASONING_DISABLED : {}), - ...(options.responseFormat ? { response_format: { type: options.responseFormat } } : {}), - }), - }); + body: JSON.stringify({ + model: connection?.modelId || model, + messages: [ + { role: "system", content: system || "You are a helpful assistant." }, + { role: "user", content: prompt }, + ], + stream: false, + max_tokens: options.maxTokens ?? 5000, + temperature: options.temperature ?? 0.7, + ...(reasoning ? REASONING_DISABLED : {}), + ...(options.responseFormat ? { response_format: { type: options.responseFormat } } : {}), + }), + }); + } catch (error) { + // A dead host or a mistyped URL fails here, before any status exists. The + // underlying cause ("connect ECONNREFUSED 10.0.0.5:8888") is the only part an + // admin can act on, and Node hides it inside `cause`. + const cause = (error as { cause?: unknown }).cause; + throw new Error( + `${connection?.label ?? "Unsloth"} request failed: ${ + cause ? String(cause) : error instanceof Error ? error.message : String(error) + }`, + ); + } if (!response.ok) { // The body carries the reason a provider rejected a request (bad key, unknown diff --git a/tests/int/ai-generate-modes.int.spec.ts b/tests/int/ai-generate-modes.int.spec.ts index a75c356e..3a98c078 100644 --- a/tests/int/ai-generate-modes.int.spec.ts +++ b/tests/int/ai-generate-modes.int.spec.ts @@ -90,6 +90,22 @@ describe("generatePlainText with a connection", () => { 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((resolve) => probe.listen(0, "127.0.0.1", resolve)); + const freePort = (probe.address() as AddressInfo).port; + await new Promise((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;