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.
This commit is contained in:
parent
3896071632
commit
31e6cd6509
6 changed files with 185 additions and 28 deletions
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
84
src/components/admin/ai/ApiKeyField.tsx
Normal file
84
src/components/admin/ai/ApiKeyField.tsx
Normal file
|
|
@ -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<string>({ path: "apiKey" });
|
||||
const { value: saved } = useField<boolean>({ path: "hasApiKey" });
|
||||
const [reveal, setReveal] = useState(false);
|
||||
|
||||
const forged = typeof value === "string" ? value : "";
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "1.5rem" }}>
|
||||
<label
|
||||
htmlFor="ai-connection-api-key"
|
||||
style={{ display: "block", marginBottom: "0.5rem", fontSize: "0.85rem" }}
|
||||
>
|
||||
API Key
|
||||
</label>
|
||||
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
|
||||
<input
|
||||
id="ai-connection-api-key"
|
||||
type={reveal ? "text" : "password"}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={forged}
|
||||
placeholder={saved ? "A key is stored. Type a new one to replace it." : "No key stored."}
|
||||
onChange={(event) => 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",
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setReveal((current) => !current)}
|
||||
style={{
|
||||
padding: "0.5rem 0.75rem",
|
||||
border: "1px solid var(--theme-elevation-150)",
|
||||
borderRadius: "4px",
|
||||
background: "var(--theme-elevation-50)",
|
||||
color: "var(--theme-text)",
|
||||
fontSize: "0.75rem",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
{reveal ? "Hide" : "Show"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p
|
||||
style={{
|
||||
marginTop: "0.5rem",
|
||||
fontSize: "0.75rem",
|
||||
color: "var(--theme-elevation-500)",
|
||||
}}
|
||||
>
|
||||
{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.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<div className="mt-2 rounded-md border border-white/15 bg-zinc-900/60 p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div style={frame}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem", flexWrap: "wrap" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void run()}
|
||||
disabled={busy || !saved}
|
||||
className="rounded border border-fuchsia-500/40 bg-fuchsia-500/10 px-2.5 py-1 text-[11px] font-medium text-fuchsia-200 hover:bg-fuchsia-500/20 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
style={{ ...button, opacity: busy || !saved ? 0.5 : 1, cursor: busy || !saved ? "not-allowed" : "pointer" }}
|
||||
>
|
||||
{busy ? "Testing..." : "Test connection"}
|
||||
</button>
|
||||
<span className="text-[11px] text-white/40">
|
||||
<span style={{ fontSize: "0.75rem", color: "var(--theme-elevation-500)" }}>
|
||||
{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 ? (
|
||||
<p
|
||||
className={`mt-2 whitespace-pre-wrap text-[11px] ${
|
||||
result.ok ? "text-emerald-300" : "text-rose-300"
|
||||
}`}
|
||||
style={{
|
||||
marginTop: "0.5rem",
|
||||
marginBottom: 0,
|
||||
fontSize: "0.75rem",
|
||||
whiteSpace: "pre-wrap",
|
||||
color: result.ok ? "var(--theme-success-500)" : "var(--theme-error-500)",
|
||||
}}
|
||||
>
|
||||
{result.ok ? "Passed. " : "Failed. "}
|
||||
{result.message}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<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;
|
||||
|
|
|
|||
Loading…
Reference in a new issue