import { useEffect, useMemo, useRef, useState } from "react"; import { SettingsAction, SettingsCard, SettingsInput, SettingsSection, SettingsSelect, } from "@getpaseo/plugin/client/ui"; import { isApiProtocolId, protocolNeedsAccountId, type ApiEndpoint, type ApiProtocolId } from "../../../shared/api-protocol.js"; import type { ApiTestOutput } from "../../../shared/rpc.js"; import type { PromptKitSettings } from "../../../shared/settings.js"; import { ENDPOINT_PRESETS, KEY_SOURCE_OPTIONS, MODEL_PLACEHOLDER, PROTOCOL_OPTIONS, endpointFromPreset, isUsableSecretsDir, validateEndpoint, } from "../api-endpoints.js"; import type { SettingsPatch } from "../draft.js"; import { MODEL_FILTER_THRESHOLD, describeFilter, filterModels } from "../model-filter.js"; import { StoredKeyRows, type StoredKeyRowsProps } from "./stored-key-rows.js"; export interface ApiEndpointSectionProps { values: PromptKitSettings; disabled: boolean; /** Bumps when the draft is discarded or saved, so text fields re-read their value. */ epoch: number; patch(update: SettingsPatch): void; /** Runs the real key lookup and model list against one endpoint. */ test(endpoint: ApiEndpoint, secretsDir: string | null): Promise; keyStatus: StoredKeyRowsProps["status"]; writeKey: StoredKeyRowsProps["write"]; } type TestState = | { kind: "idle" } | { kind: "running" } | { kind: "ok"; models: number } | { kind: "error"; message: string }; const NONE = ""; /** The value of the "add an endpoint that is not a preset" option. */ const CUSTOM = "__custom__"; const PRESET_IDS: ReadonlySet = new Set(ENDPOINT_PRESETS.map((preset) => preset.id)); /** A free id for a custom endpoint, so two of them cannot collide. */ function nextCustomId(endpoints: readonly ApiEndpoint[]): string { for (let n = 1; ; n += 1) { const id = `custom-${n}`; if (!endpoints.some((endpoint) => endpoint.id === id)) return id; } } function withEndpoint( endpoints: readonly ApiEndpoint[], id: string, changes: Partial, ): ApiEndpoint[] { return endpoints.map((endpoint) => (endpoint.id === id ? { ...endpoint, ...changes } : endpoint)); } /** Pick endpoint → fill details → Test → pick model. One picker for presets and custom entries. */ export function ApiEndpointSection({ values, disabled, epoch, patch, test, keyStatus, writeKey }: ApiEndpointSectionProps) { const [tests, setTests] = useState>>({}); const [modelQuery, setModelQuery] = useState(""); const live = useRef({ values, active: true }); live.current.values = values; useEffect(() => { live.current.active = true; return () => { live.current.active = false; }; }, []); const selected = values.apiEndpoints.find((endpoint) => endpoint.id === values.apiEndpointId) ?? null; const selectedIsPreset = selected !== null && PRESET_IDS.has(selected.id); const testState: TestState = selected === null ? { kind: "idle" } : (tests[selected.id] ?? { kind: "idle" }); const problem = selected === null ? null : validateEndpoint(selected, values.apiEndpoints, selected.id); // Presets and saved custom endpoints together, A–Z; "Custom endpoint…" always last. const endpointOptions = useMemo(() => { const protocolLabel = (id: ApiProtocolId) => PROTOCOL_OPTIONS.find((option) => option.value === id)?.label ?? id; const entries = [ ...ENDPOINT_PRESETS.map((preset) => ({ label: `${preset.label} — ${preset.note}`, value: preset.id })), ...values.apiEndpoints .filter((endpoint) => !PRESET_IDS.has(endpoint.id)) .map((endpoint) => ({ label: `${endpoint.label} — ${protocolLabel(endpoint.protocol)}`, value: endpoint.id })), ].sort((left, right) => left.label.localeCompare(right.label, undefined, { sensitivity: "base" })); return [{ label: "Choose an endpoint…", value: NONE }, ...entries, { label: "Custom endpoint…", value: CUSTOM }]; }, [values.apiEndpoints]); const modelOptions = useMemo(() => { const declared = (selected?.models ?? []).map((model) => ({ label: model, value: model })); // Keep the saved model selectable even if the endpoint no longer lists it. if (values.apiModel !== null && !declared.some((option) => option.value === values.apiModel)) { return [{ label: values.apiModel, value: values.apiModel }, ...declared]; } return declared; }, [selected, values.apiModel]); /** Choosing an endpoint selects one that exists or adds it from its preset. */ const choose = (choice: string) => { setModelQuery(""); patch((current) => { if (choice === NONE) return { apiEndpointId: null, apiModel: null }; if (current.apiEndpoints.some((endpoint) => endpoint.id === choice)) { return { apiEndpointId: choice, // The model belongs to one endpoint, so switching endpoint drops it. apiModel: choice === current.apiEndpointId ? current.apiModel : null, }; } if (choice === CUSTOM) { const id = nextCustomId(current.apiEndpoints); return { apiEndpoints: [ ...current.apiEndpoints, { id, label: "Custom endpoint", protocol: "openai" as ApiProtocolId, baseUrl: "https://", keySource: "env" as const, apiKeyEnv: "", accountIdVar: "", models: [], }, ], apiEndpointId: id, apiModel: null, }; } const preset = ENDPOINT_PRESETS.find((candidate) => candidate.id === choice); if (preset === undefined) return {}; return { apiEndpoints: [...current.apiEndpoints, endpointFromPreset(preset)], apiEndpointId: preset.id, apiModel: null, }; }); }; const edit = (changes: Partial) => { if (selected === null) return; const id = selected.id; setTests((previous) => ({ ...previous, [id]: { kind: "idle" } })); patch((current) => ({ apiEndpoints: withEndpoint(current.apiEndpoints, id, changes) })); }; const remove = () => { if (selected === null) return; const id = selected.id; patch((current) => ({ apiEndpoints: current.apiEndpoints.filter((endpoint) => endpoint.id !== id), apiEndpointId: null, apiModel: null, apiEndpointByProvider: Object.fromEntries( Object.entries(current.apiEndpointByProvider).filter(([, target]) => target !== id), ), })); }; const runTest = async (endpoint: ApiEndpoint) => { const fingerprint = JSON.stringify([endpoint, values.secretsDir]); const current = () => live.current.active && JSON.stringify([live.current.values.apiEndpoints.find((entry) => entry.id === endpoint.id), live.current.values.secretsDir]) === fingerprint; setTests((previous) => ({ ...previous, [endpoint.id]: { kind: "running" } })); try { const output = await test(endpoint, values.secretsDir); if (!current()) return; if (output.status === "ok") { setTests((previous) => ({ ...previous, [endpoint.id]: { kind: "ok", models: output.models.length } })); // Test fills the model list; an empty answer leaves it alone. if (output.models.length > 0) { const models = [...output.models]; patch((current) => ({ apiEndpoints: withEndpoint(current.apiEndpoints, endpoint.id, { models }) })); } } else { setTests((previous) => ({ ...previous, [endpoint.id]: { kind: "error", message: output.error.message }, })); } } catch (thrown) { if (!current()) return; setTests((previous) => ({ ...previous, [endpoint.id]: { kind: "error", message: thrown instanceof Error ? thrown.message : String(thrown) }, })); } }; const testHint = testState.kind === "ok" ? testState.models === 0 ? "Model-list request succeeded with an empty list. Generation has not been tested." : `Model list received: ${testState.models}. Generation has not been tested.` : "Asks the endpoint which models it offers, with the same key lookup a rewrite uses."; const keyFound = selected === null || testState.kind !== "ok" ? "" : selected.keySource === "none" ? " No key was sent." : selected.keySource === "env" ? ` Key read from the environment variable ${selected.apiKeyEnv.trim()}.` : ` Key read from secrets.json (${selected.apiKeyEnv.trim()}).`; const secretsDirError = values.secretsDir !== null && !isUsableSecretsDir(values.secretsDir) ? "Must be an absolute path or start with ~/." : null; return ( {selected === null ? null : ( <> {selectedIsPreset ? null : ( <> edit({ label })} /> edit({ protocol: isApiProtocolId(protocol) ? protocol : "openai" }) } /> )} edit({ baseUrl })} /> edit({ keySource: keySource === "secrets_file" || keySource === "none" ? keySource : "env" }) } /> {protocolNeedsAccountId(selected.protocol) ? ( edit({ accountIdVar })} /> ) : null} {selected.keySource === "none" ? null : ( edit({ apiKeyEnv })} /> )} {selected.keySource === "secrets_file" ? ( patch({ secretsDir: text.trim() === "" ? null : text.trim() })} /> ) : null} {selected.keySource === "secrets_file" && secretsDirError === null ? ( <> {protocolNeedsAccountId(selected.protocol) ? ( ) : null} ) : null} void runTest(selected)} /> {modelOptions.length > MODEL_FILTER_THRESHOLD ? ( ) : null} {selected.models.length > 0 ? ( patch({ apiModel: apiModel === NONE ? null : apiModel })} /> ) : ( patch({ apiModel: model.trim() === "" ? null : model.trim() })} /> )} )} ); }