"use client"; import Tooltip from "@/shared/ui/Tooltip"; import { type KeyboardEvent, useCallback, useEffect, useId, useRef, useState } from "react"; import { Check, ChevronDown, Loader2, Pencil, PlugZap, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { apiFetch, apiUrl } from "@/lib/api"; import type { Discovery } from "@/lib/provider-registry"; import { useOutsideClick } from "@/hooks/use-outside-click"; import type { ProviderProbeInput } from "./ProviderModelDiscovery"; import { inputClass, subPanelClass } from "./shared"; // These buttons only ever had a hover fill, so pressing one produced no // response at all and the pages felt like inert blocks. Every variant now moves // on press and shows a real focus ring. Disabled buttons keep pointer events — // several of them explain why they are disabled through `title`. const registryButtonBase = "inline-flex min-h-10 items-center justify-center gap-2 rounded-lg border px-3 text-[13px] font-medium outline-none transition-[background-color,border-color,color,box-shadow,transform] duration-150 active:scale-[0.97] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--background)] disabled:opacity-40 disabled:active:scale-100"; export const registryButton = `${registryButtonBase} border-[var(--border)] hover:border-[color-mix(in_srgb,var(--foreground)_20%,var(--border))] hover:bg-[var(--accent)] disabled:hover:border-[var(--border)] disabled:hover:bg-transparent`; /** Destructive action: reads as neutral until you reach for it. */ export const registryDanger = `${registryButtonBase} border-[var(--border)] text-[var(--muted-foreground)] hover:border-red-300 hover:bg-red-50 hover:text-red-600 disabled:hover:border-[var(--border)] disabled:hover:bg-transparent disabled:hover:text-[var(--muted-foreground)] dark:hover:border-red-900 dark:hover:bg-red-950 dark:hover:text-red-400`; export const registryPrimary = "inline-flex min-h-10 items-center justify-center gap-2 rounded-lg bg-[var(--foreground)] px-4 text-[13px] font-medium text-[var(--background)] outline-none transition-[background-color,box-shadow,transform] duration-150 hover:bg-[color-mix(in_srgb,var(--foreground)_86%,var(--background))] active:scale-[0.97] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--background)] disabled:opacity-40 disabled:hover:bg-[var(--foreground)] disabled:active:scale-100"; export function EditableRegistryName({ name, onChange, label, }: { name: string; onChange: (value: string) => void; label: string; }) { const [editing, setEditing] = useState(false); if (editing) return ( onChange(e.target.value)} onBlur={() => setEditing(false)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === "Escape") setEditing(false); }} /> ); return (

{ setEditing(true); }} > {name}

); } const PROBE_MESSAGES: Record = { connected: "Provider connected", auth_error: "The provider rejected these credentials. Check the API key and its permissions.", unavailable: "This provider does not expose a model list. Its connection can be verified when you test a model or search configuration.", rate_limited: "The provider is rate limiting requests. Try again later.", timeout: "The connection timed out. Check the address and network, then try again.", unreachable: "Could not reach the provider. Check the address and network.", invalid_url: "Enter a valid HTTP or HTTPS provider address.", http_error: "The provider returned an error. Check the address or try again later.", json_forbidden: "SearXNG rejected the JSON search request. Enable json in search.formats in its settings.yml and check access rules.", invalid_response: "The search endpoint returned an invalid response. Check that the address serves the SearXNG JSON search API.", }; function usesLoopbackAddress(address: string): boolean { try { const host = new URL(address.includes("://") ? address : `http://${address}`).hostname; return host === "localhost" || host.startsWith("127.") || host === "[::1]"; } catch { return false; } } const CATEGORIES = [ "Language models", "Embedding models", "Search", "Voice", "Multimodal generation", ]; const CATEGORY_KEYS = ["llm", "embedding", "search", "voice", "generation"]; export function RegistryProbe({ input, discovery, onResult, listing = false, automatic = false, hints = [], showCapabilities = true, }: { input: ProviderProbeInput; discovery?: Discovery; onResult: (result: Discovery) => void; listing?: boolean; automatic?: boolean; hints?: string[]; showCapabilities?: boolean; }) { // Credentials are only an in-memory request signature, never rendered or persisted. return ( ); } function ProbeForm({ input, discovery, onResult, listing, automatic, hints, showCapabilities, }: { input: ProviderProbeInput; discovery?: Discovery; onResult: (result: Discovery) => void; listing: boolean; automatic: boolean; hints: string[]; showCapabilities: boolean; }) { const { t } = useTranslation(); const [result, setResult] = useState(discovery); const [pending, setPending] = useState(false); const controller = useRef(null); useEffect(() => () => { controller.current?.abort(); controller.current = null; }, []); const probe = useCallback(async () => { controller.current?.abort(); const request = new AbortController(); controller.current = request; setPending(true); const timeout = setTimeout(() => request.abort(), 35000); try { const response = await apiFetch(apiUrl("/api/settings/test-provider"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input), signal: request.signal, }); const payload = await response.json(); if (request.signal.aborted) return; const next: Discovery = response.ok ? { ...payload, checked_at: new Date().toISOString() } : { status: "http_error", models: [] }; setResult(next); onResult(next); } catch { if (controller.current === request) { const failed: Discovery = { status: request.signal.aborted ? "timeout" : "unreachable", models: [], checked_at: new Date().toISOString() }; setResult(failed); onResult(failed); } } finally { clearTimeout(timeout); if (controller.current === request) setPending(false); } }, [input, onResult]); useEffect(() => { // The keyed form resets on credential/URL/protocol changes. Wait for typing // to settle; cached results and failures keep manual retry under user control. if (!automatic || discovery) return; const timer = setTimeout(() => { void probe(); }, 1200); return () => clearTimeout(timer); }, [automatic, discovery, probe]); return (

{t(listing ? "Provider model list" : "Provider connection")}

{t( listing ? "Choose a listed model or enter any model ID below." : "Check access and discover the services this provider offers.", )}

{result && (
{t(result.status === "connected" && input.service !== "search" ? "settings.providerServices.catalogListed" : PROBE_MESSAGES[result.status] || PROBE_MESSAGES.http_error)} {result.warning === "partial_models" &&

{t("settings.providerServices.partial")}

} {result.http_status != null && ` · HTTP ${result.http_status}`} {result.warning === "empty_results" && (

{t("The search API is reachable but returned no results. Check the enabled engines and their network access.")}

)} {input.binding === "searxng" && result.status !== "connected" && usesLoopbackAddress(input.base_url) && (

{t("This test runs from the DeepTutor backend. In Docker, localhost points to the DeepTutor container. Use a shared-network service name and container port, or host.docker.internal and the published host port.")}

)} {result.status === "connected" && input.service !== "search" && ` · ${t("{{count}} models available", { count: result.models.length })}`}
)} {!listing && showCapabilities && ( <>
{CATEGORIES.map((label, i) => { const evidence = result?.capabilities?.find( (c) => c.category === CATEGORY_KEYS[i], ); const status = evidence?.evidence === "metadata" ? "Detected" : evidence || hints.includes(CATEGORY_KEYS[i]) ? "Provider supports" : "Unknown"; return (

{t(label)}

{t(status)}

); })}

{t( "Detected describes model modalities, not API compatibility. Provider support indicates an available integration; test a specific model to verify your account access.", )}

)}
); } export function RegistryField({ label, value, onChange, placeholder, type = "text", disabled = false, }: { label: string; value: string; onChange: (value: string) => void; placeholder?: string; type?: string; disabled?: boolean; }) { const id = useId(); return (
onChange(e.target.value)} placeholder={placeholder} className={inputClass} />
); } /** * The model ID, with the provider's listed models offered as suggestions. * * This was a native input with a datalist, which hands the popup to the * browser — and the browser draws every option at once. A provider that lists * thirty models covered the page from above its header to below its footer, in * the browser's styling rather than ours. A datalist popup takes no CSS at all, * so capping that height means owning the list. * * The field stays free text: a model the provider does not list is still a * model the user may have to type, so the suggestions narrow as they type and * simply stay shut when nothing matches — an unlisted ID is this field working, * not an error to report. */ export function RegistryModelIdField({ label, value, options, onChange, placeholder, disabled = false, required = false, invalid = false, }: { label: string; value: string; options: string[]; onChange: (value: string) => void; placeholder?: string; disabled?: boolean; required?: boolean; invalid?: boolean; }) { const { t } = useTranslation(); const id = useId(); const box = useRef(null); const listRef = useRef(null); const [open, setOpen] = useState(false); const [active, setActive] = useState(-1); useOutsideClick(box, open, () => setOpen(false)); // A value that *is* one of the options keeps the list whole: narrowing it to // the single option the field already holds would turn "show me the models" // into "show me the one I picked". const query = value.trim().toLowerCase(); const matches = !query || options.some((option) => option.toLowerCase() === query) ? options : options.filter((option) => option.toLowerCase().includes(query)); const visible = open && matches.length > 0; useEffect(() => { if (!visible) return; listRef.current ?.querySelector('[data-active="true"]') // Optional call, as elsewhere: a host without the method (jsdom) has // nothing to scroll, and keyboard navigation must not depend on it. ?.scrollIntoView?.({ block: "nearest" }); }, [visible, active]); const pick = (option: string) => { onChange(option); setActive(-1); setOpen(false); }; const onKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") { if (!open) return; // Contained on purpose: Escape in an open list means "close the list", // not "leave the editor" to whatever is listening further up. event.stopPropagation(); setOpen(false); return; } if (event.key === "ArrowDown" || event.key === "ArrowUp") { if (!matches.length) return; // Otherwise the caret jumps to either end of the ID being typed. event.preventDefault(); if (!visible) { setActive(event.key === "ArrowDown" ? 0 : matches.length - 1); setOpen(true); return; } const step = event.key === "ArrowDown" ? 1 : -1; setActive((current) => { const next = current + step; if (next < 0) return matches.length - 1; return next >= matches.length ? 0 : next; }); return; } if (event.key === "Enter" && visible && active >= 0) { event.preventDefault(); pick(matches[active]); } }; return (
= 0 ? `${id}-option-${active}` : undefined } aria-invalid={invalid || undefined} aria-describedby={invalid ? `${id}-error` : undefined} required={required} disabled={disabled} className={`${inputClass} pr-9 font-mono placeholder:font-sans`} value={value} placeholder={placeholder} onChange={(event) => { onChange(event.target.value); setActive(-1); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={onKeyDown} /> {options.length > 0 && !disabled && ( )} {visible && (
{matches.map((option, index) => ( ))}
)}
{invalid && ( )}
); }