"use client"; import { scrollToSettingsElement } from "@/features/settings/navigation/settings-scroll"; import Tooltip from "@/shared/ui/Tooltip"; import { stageRegistryAction, type RegistryEdit } from "@/lib/provider-registry"; import { useEffect, useRef, useState } from "react"; import Link from "next/link"; import { ArrowRight, Cable, Plus, Trash2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import { formatConfiguredProviderName, formatProviderLabel } from "@/lib/provider-branding"; import ProviderIcon from "@/components/common/ProviderIcon"; import { randomUuid } from "@/lib/random-uuid"; import { useSettings, type CatalogConnection, type ServiceName, } from "@/features/settings/store/SettingsStore"; import { providerRegistry, providerUsage, providerProbeInput, updateProvider, REGISTRY_SERVICES, SERVICE_TITLES, PROVIDER_SERVICES, providerServiceSupport, } from "@/lib/provider-registry"; import { EditableRegistryName, RegistryField, RegistryProbe, registryButton, registryDanger, registryPrimary, } from "./RegistryControls"; import { ProviderServices } from "./ProviderServices"; import { AddProviderPanel, ProviderProtocol, type CustomProviderInput } from "./AddProviderPanel"; import { CodexOAuthCard } from "./CodexOAuthCard"; import { CodeBuddyAuthCard } from "./CodeBuddyAuthCard"; import { stringifyExtraHeaders, subPanelClass } from "./shared"; import { WorkspaceDetailEmpty, WorkspaceRail, WorkspaceSplit, workspaceCardClass, } from "./WorkspaceShell"; export function ProvidersWorkspace() { const { t, i18n } = useTranslation(); const uiLanguage = i18n?.resolvedLanguage ?? i18n?.language ?? "en"; const { catalog, draft, providers, connectionTargets, catalogEditable, mutateCatalog, applying, } = useSettings(); const stageRegistry = async (edit: RegistryEdit) => { mutateCatalog((next) => stageRegistryAction(next, edit)); return true; }; const sources = providerRegistry(draft); const editorRef = useRef(null); const [selected, setSelected] = useState(null); // Below xl the detail pane sits under the rail, so anything that changes what // it shows has to bring it into view. const revealDetail = () => { if (window.matchMedia("(max-width: 1279px)").matches) requestAnimationFrame(() => scrollToSettingsElement(editorRef.current), ); }; const [adding, setAdding] = useState(false); useEffect(() => { if (adding) requestAnimationFrame(() => scrollToSettingsElement(editorRef.current)); else if (selected) revealDetail(); }, [adding, selected]); const [vendor, setVendor] = useState(""); const [query, setQuery] = useState(""); const [auth, setAuth] = useState(""); useEffect(() => { const id = new URLSearchParams(window.location.search).get("provider"); if (id && sources.some((p) => p.id === id)) setSelected((current) => current || id); // eslint-disable-next-line react-hooks/exhaustive-deps }, [sources.length]); const options = [ ...new Map( REGISTRY_SERVICES.flatMap((service) => (providers[service] ?? []) .filter(p => p.value !== "none" && p.status !== "deprecated") .map(option => [option.value, { ...option, service }] as const)).reverse(), ).values(), ].map(option => ({ ...option, services: PROVIDER_SERVICES.filter(service => providers[service]?.some(p => p.value === option.value && p.status !== "deprecated") || Boolean(connectionTargets.find(target => target.provider === option.value)?.services[service])) })).sort((a, b) => a.label.localeCompare(b.label)); // Protocol-specific aliases still resolve saved accounts, but new accounts // use the vendor once and select their protocol in the connection editor. const addableOptions = options.filter((p) => p.status !== "legacy"); const optionLabel = (provider: string) => formatProviderLabel(provider, options.find(p => p.value === provider)?.label ?? provider, uiLanguage); const source = sources.find((p) => p.id === selected); const option = options.find((p) => p.value === source?.provider); const managed = source?.provider === "openai_codex"; const connection = source?.source; const apiFormat = connection?.api_format || (option?.default_api_format as CatalogConnection["api_format"]) || "auto"; const defaultBaseUrl = option?.base_urls?.[apiFormat] || option?.base_url || ""; const change = (field: string, value: unknown) => { if (source) mutateCatalog((next) => { updateProvider(next, source.ref, field, value); if (field === "name" && managed) updateProvider(next, source.ref, "user_name", value); }); }; const create = (custom?: CustomProviderInput) => { const option = addableOptions.find((o) => o.value === vendor); if (!option) return; if (option.value === "openai_codex") { setAuth("openai_codex"); setAdding(false); return; } const id = `conn-${randomUuid()}`; const entry: CatalogConnection = { id, name: custom?.name || option.label, provider: option.value, source_service: option.service, api_key: "", base_url: custom?.base_url || "", api_version: "", ...(custom ? { service_overrides: { llm: { enabled: true, binding: "custom" } } } : {}), api_format: custom?.api_format || (option.default_api_format as CatalogConnection["api_format"]) || "auto", }; mutateCatalog((next) => { (next.connections ??= []).push(entry); }); setSelected(`connection:${id}`); setAdding(false); setAuth(""); }; if (!catalogEditable) return (

{t("Only administrators can manage providers.")}

); const savedIds = new Set(providerRegistry(catalog).map((p) => p.id)); const saved = Boolean(source && savedIds.has(source.id)); const filtered = sources.filter((p) => `${formatConfiguredProviderName(p.provider, p.name, uiLanguage)} ${optionLabel(p.provider)} ${p.provider}`.toLowerCase().includes(query.toLowerCase()), ); const hints = source ? PROVIDER_SERVICES.filter(service => providerServiceSupport(source, service, connectionTargets, providers).enabled) .map(service => ["tts", "stt"].includes(service) ? "voice" : ["imagegen", "videogen"].includes(service) ? "generation" : service) : []; if (adding) return (
setAdding(false)} />
); return (
{ setAdding(true); }} className={`${registryButton} w-full py-2`} > {t("Add provider")} } search={{ label: t("Find provider"), value: query, onChange: setQuery, placeholder: t("Search by name"), }} empty={ filtered.length ? undefined : sources.length ? t("No providers match your search.") : t("Add your first provider to start configuring models.") } > {filtered.map((p) => { const editing = !adding && !auth && p.id === selected; return ( ); })} } detail={
{auth === "openai_codex" ? ( ) : source && connection ? (

{t("Configuring provider")}

change("name", name)} />

{optionLabel(source.provider)} {!saved && ` · ${t("Not saved")}`}

{managed ? ( ) : ( <> {source.provider === "codebuddy" && } {/* Address and credential belong on one line: they are the two halves of one connection, and stacking them full width was most of what made this pane feel cramped. */}
change("base_url", v)} placeholder={ defaultBaseUrl || "https://api.example.com/v1" } />

{t( "Leave blank to use the provider default. Enter a custom URL for a gateway or private deployment.", )}

{option?.requires_api_key !== false && (
{Array.isArray(connection.api_key) ? ( connection.api_key.map( (key: string, index: number) => ( { const keys = [...connection.api_key]; keys[index] = value; change("api_key", keys); }} /> ), ) ) : ( change("api_key", value)} /> )}
)}
{source.provider === "volcengine_speech" && (
change("app_id", v)} />

{t("Use the Speech console API key. For the legacy console, enter App ID and put the access token in the key field. Ark keys are separate.")}

)} {providerServiceSupport(source, "llm", connectionTargets, providers).enabled && option?.api_formats?.length !== 0 && ( change("api_format", value)} /> )} change("service_overrides", value)} />
{t("Advanced connection settings")}
{source.provider !== "volcengine_speech" && <> change("api_version", v)} /> }
change("extra_headers", v)} />
{source.service === "search" && ( change("proxy", v)} /> )}
change("discovery", result)} /> )}
{source && (
{[ ["llm", "Language models"], ["embedding", "Embedding models"], ["search", "Search"], ["voice", "Voice"], ["multimodal", "Multimodal generation"], ].filter(([path]) => PROVIDER_SERVICES.some(service => (path === "voice" ? service === "tts" || service === "stt" : path === "multimodal" ? service === "imagegen" || service === "videogen" : service === path) && providerServiceSupport(source, service, connectionTargets, providers).enabled )).map(([path, label]) => ( {t(label)} ))}
)}
) : ( } title={t("Nothing selected")} hint={t( "Select a provider to edit its connection. Models are managed on their own pages.", )} /> )}
} />
); }