"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import Link from "next/link"; import { ArrowUpRight, CheckCircle2, ChevronDown, Eye, EyeOff, Info, Loader2, Plus, RefreshCw, Terminal, Trash2, X, } from "lucide-react"; import { useTranslation } from "react-i18next"; import Modal from "@/components/common/Modal"; import ProviderIcon from "@/components/common/ProviderIcon"; import { ConfirmDialog } from "@/components/ui/ConfirmDialog"; import { apiFetch, apiUrl } from "@/lib/api"; import { reasoningEffortOptions, reasoningEffortOptionsFromSupportedLevels, } from "@/lib/reasoning-effort"; import { CodexOAuthCard } from "./CodexOAuthCard"; import { CodeBuddyAuthCard } from "./CodeBuddyAuthCard"; import { isBoundManagedCodexProfile, isCodexOAuthProfile, isManagedCodexProfile, } from "./codex-profile"; import { type CatalogModel, type CatalogProfile, type LlmContextWindowDetection, type ModelCapabilityKey, type ProviderOption, type ServiceName, getActiveModel, getActiveProfile, useSettings, } from "@/features/settings/store/SettingsStore"; import { DimensionField } from "./DimensionField"; import { ModelCapabilityFields } from "./ModelCapabilityFields"; import { ModelListPicker } from "./ModelListPicker"; import { AddCard, CardAction, CardGrid, ModelCard, ProfileCard, SectionHead, UseRow, } from "./ModelCards"; import { nextProfileName } from "./profile-naming"; import { searchProviderFields } from "./search-providers"; import { activeProfileDetail, formatContextWindowSource, inputClass, selectClass, selectOptionClass, stringifyExtraHeaders, } from "./shared"; // The protocol an endpoint speaks. Labels and hints are keyed by the backend // value so the select never invents a format the registry does not know. const API_FORMAT_LABELS: Record = { auto: "Auto (recommended)", openai_chat: "OpenAI Chat Completions", openai_responses: "OpenAI Responses", anthropic: "Anthropic Messages", }; const API_FORMAT_HINTS: Record = { auto: "Chat Completions for most endpoints; Responses for OpenAI reasoning models, with fallback.", openai_chat: "Send every request to /v1/chat/completions.", openai_responses: "Send every request to /v1/responses. Endpoint errors are returned without falling back.", anthropic: "Send every request as Anthropic Messages (/v1/messages).", }; const LLM_SHAPED = new Set(["llm", "task"]); const SERVICE_LABEL: Record = { llm: "LLM", task: "Task model", embedding: "Embedding", search: "Search", tts: "Text-to-Speech", stt: "Speech-to-Text", imagegen: "Image Generation", videogen: "Video Generation", }; export function ServiceConfigEditor({ service }: { service: ServiceName }) { const { t } = useTranslation(); const { catalog, draft, catalogEditable, settingsError, providers, language, embeddingCapabilities, embeddingDefaultDim, logs, testRunning, applying, mutateCatalog, addProfile, removeActiveProfile, addModel, removeActiveModel, updateProfileField: setProfileField, updateModelField: setModelField, updateModelBoolField: setModelBoolField, updateContextWindowField: setContextWindowField, updateReasoningEffort: setReasoningEffort, updateModelCapability: setModelCapability, llmContextDetection, applyDetectedContextWindow, runDetailedTest, applyService, setToast, } = useSettings(); const profiles = draft.services[service].profiles; const inUseProfileId = draft.services[service].active_profile_id; const inUseModelId = draft.services[service].active_model_id; // ── Browsing vs using ─────────────────────────────────────────────────── // // The page always shows its providers. Opening one pops a dialog with its // connection fields and its models; nothing in that dialog adopts it — "in // use" is a separate, deliberate act, which is what lets you look at a // provider you are not currently running on without switching to it. const [openProfileId, setOpenProfileId] = useState(null); const [expandedModelId, setExpandedModelId] = useState(null); const openedProfile = profiles.find((item) => item.id === openProfileId) ?? null; // Whatever the field editors below are pointed at. Falling back to the // profile in use keeps every reference working before anything is opened. const activeProfile = openedProfile ?? getActiveProfile(draft, service); const activeModel = openedProfile ? ((expandedModelId ? openedProfile.models.find((item) => item.id === expandedModelId) : null) ?? null) : getActiveModel(draft, service); // The context's mutators write to whatever is in use unless told otherwise. // Binding them to what is on screen here means the ~300 lines of field // editors below need no knowledge of any of this. const updateProfileField = useCallback( (svc: ServiceName, field: keyof CatalogProfile, value: string) => setProfileField(svc, field, value, activeProfile?.id), [setProfileField, activeProfile?.id], ); const updateModelField = useCallback( (svc: ServiceName, field: keyof CatalogModel, value: string) => setModelField(svc, field, value, activeProfile?.id, activeModel?.id), [setModelField, activeProfile?.id, activeModel?.id], ); const updateModelBoolField = useCallback( (svc: ServiceName, field: keyof CatalogModel, value: boolean) => setModelBoolField(svc, field, value, activeProfile?.id, activeModel?.id), [setModelBoolField, activeProfile?.id, activeModel?.id], ); const updateContextWindowField = useCallback( (value: string) => setContextWindowField(value, activeProfile?.id, activeModel?.id), [setContextWindowField, activeProfile?.id, activeModel?.id], ); const updateReasoningEffort = useCallback( (value: string) => setReasoningEffort(value, activeProfile?.id, activeModel?.id), [setReasoningEffort, activeProfile?.id, activeModel?.id], ); const updateModelCapability = useCallback( (key: ModelCapabilityKey, value: boolean | null) => setModelCapability( service, key, value, activeProfile?.id, activeModel?.id, ), [setModelCapability, service, activeProfile?.id, activeModel?.id], ); const activeProviderValue = service === "search" ? activeProfile?.provider || "" : activeProfile?.binding || ""; const activeProviderOption = (providers[service] || []).find( (option) => option.value === activeProviderValue, ); const isManagedCodex = isManagedCodexProfile(activeProfile); const isBoundManagedCodex = isBoundManagedCodexProfile(activeProfile); const isCodexOAuth = isCodexOAuthProfile( service, activeProviderValue, activeProviderOption, activeProfile, ); // Arriving from Settings > Connections with ?profile=: open that // provider's dialog directly. It used to have to *adopt* the profile to // show it, because selecting and using were the same act — with the two // separated, following the link costs nothing and needs no warning. // // The query is read from `window.location` rather than `useSearchParams()` // so no settings page needs a Suspense boundary for something that only // exists after hydration. const deepLinkHandled = useRef(false); useEffect(() => { if (deepLinkHandled.current) return; const requested = new URLSearchParams(window.location.search).get( "profile", ); if (!requested) { deepLinkHandled.current = true; return; } // The catalog may still be loading; leave the flag down and retry. if (!profiles.some((item) => item.id === requested)) return; deepLinkHandled.current = true; // Drop the query so a refresh does not re-open something already closed. window.history.replaceState(null, "", window.location.pathname); setOpenProfileId(requested); }, [profiles]); const [showApiKey, setShowApiKey] = useState(false); const [deletingProfile, setDeletingProfile] = useState( null, ); const [diagnosticsOpen, setDiagnosticsOpen] = useState(false); const [editingModelId, setEditingModelId] = useState(null); const [editingModelName, setEditingModelName] = useState(""); const [editingProfileId, setEditingProfileId] = useState(null); const [editingProfileName, setEditingProfileName] = useState(""); const [modelsSyncing, setModelsSyncing] = useState(false); const [pickerOpen, setPickerOpen] = useState(false); const closeProviderEditor = useCallback(() => { setOpenProfileId(null); setExpandedModelId(null); }, []); const finishProviderEditing = useCallback(async () => { const serviceChanged = JSON.stringify(catalog.services[service]) !== JSON.stringify(draft.services[service]); if (serviceChanged && !(await applyService(service))) return; closeProviderEditor(); }, [ applyService, catalog.services, closeProviderEditor, draft.services, service, ]); // Reset API-key visibility whenever we land on a different profile or // switch services — same effect the old code had, but using React's // documented "store previous prop in state" pattern so it happens during // render rather than in a useEffect (which the linter forbids). const profileKey = `${service}:${activeProfile?.id ?? "none"}`; const [lastProfileKey, setLastProfileKey] = useState(profileKey); if (lastProfileKey !== profileKey) { setLastProfileKey(profileKey); if (showApiKey) setShowApiKey(false); } const searchProviderRaw = service === "search" ? (activeProfile?.provider || "").trim().toLowerCase() : ""; const showSearchProviderWarning = service === "search" && Boolean(searchProviderRaw); // Every judgement below reads the backend's own provider list, so the web app // never keeps a second (and drifting) copy of what is supported. const searchProviderOption = (providers.search || []).find( (option) => option.value === searchProviderRaw, ); const isDeprecatedSearchProvider = searchProviderOption?.status === "deprecated"; const isSupportedSearchProvider = Boolean(searchProviderOption) && !isDeprecatedSearchProvider; const supportedSearchProviderNames = (providers.search || []) .filter( (option) => option.status !== "deprecated" && option.value !== "none", ) .map((option) => option.value) .join("/"); // Providers that fail hard rather than falling back need their key before the // first query — say so while the user is still on this screen. const searchProviderMissingKey = service === "search" && isSupportedSearchProvider && searchProviderOption?.requires_api_key === true && searchProviderOption?.soft_fallback === false && !String(activeProfile?.api_key || "").trim(); const activeLlmDetection = service === "llm" && llmContextDetection?.profileId === draft.services.llm.active_profile_id && llmContextDetection?.modelId === draft.services.llm.active_model_id ? llmContextDetection : null; const reasoningOptions = service === "llm" && activeModel ? isManagedCodex ? isBoundManagedCodex ? reasoningEffortOptionsFromSupportedLevels( activeModel.codex_supported_reasoning_levels ?? [], ) : [] : reasoningEffortOptions( activeProfile?.binding, activeModel.model, activeModel.reasoning_effort, activeModel.capabilities?.reasoning, ) : []; const syncProviderModels = async ( connection?: Pick, ) => { if (!LLM_SHAPED.has(service) || !activeProfile || modelsSyncing) return; const binding = connection?.binding ?? activeProfile.binding ?? ""; const baseUrl = connection?.base_url ?? activeProfile.base_url ?? ""; const apiKey = connection?.api_key ?? activeProfile.api_key ?? ""; if (!binding || (binding !== "codebuddy" && !baseUrl.trim())) return; const profileId = activeProfile.id; setModelsSyncing(true); try { const response = await apiFetch(apiUrl("/api/settings/fetch-models"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ binding, base_url: baseUrl, api_key: apiKey || null, profile_id: profileId, service, api_format: activeProfile.api_format ?? "auto", }), }); if (!response.ok) { const payload = (await response.json().catch(() => ({}))) as { detail?: string; }; throw new Error(payload.detail || `HTTP ${response.status}`); } const payload = (await response.json()) as { models?: Array<{ id: string; name?: string }>; }; const fetched = payload.models || []; if (fetched.length === 0) throw new Error(t("No models returned")); mutateCatalog((next) => { const target = next.services[service]; const profile = target.profiles.find((item) => item.id === profileId); if (!profile || profile.binding !== binding) return; const existing = new Map( profile.models.map((model) => [model.model, model]), ); profile.models = fetched.map((item, index) => { const previous = existing.get(item.id); return previous ? { ...previous, name: item.name || previous.name, model: item.id } : { id: `${service}-model-${Date.now()}-${index}`, name: item.name || item.id, model: item.id, }; }); if ( !profile.models.some((model) => model.id === target.active_model_id) ) { target.active_model_id = profile.models[0]?.id ?? null; } }); setToast(t("Synced {{count}} models", { count: fetched.length })); } catch (error) { setToast(error instanceof Error ? error.message : String(error)); } finally { setModelsSyncing(false); } }; const startModelRename = (model: CatalogModel) => { setEditingModelId(model.id); setEditingModelName(model.name || model.model || ""); }; const commitModelRename = (modelId: string) => { const fallbackIndex = activeProfile?.models.findIndex((model) => model.id === modelId) ?? -1; const fallbackName = defaultModelLabel(language, fallbackIndex + 1); const nextName = editingModelName.trim() || fallbackName; mutateCatalog((next) => { const profile = getActiveProfile(next, service); const model = profile?.models.find((item) => item.id === modelId); if (model) model.name = nextName; }); setEditingModelId(null); setEditingModelName(""); }; const cancelModelRename = () => { setEditingModelId(null); setEditingModelName(""); }; const startProfileRename = (profile: CatalogProfile) => { setEditingProfileId(profile.id); setEditingProfileName(profile.name || ""); }; const commitProfileRename = (profileId: string) => { const nextName = editingProfileName.trim(); if (nextName) { mutateCatalog((next) => { const profile = next.services[service].profiles.find( (item) => item.id === profileId, ); if (profile) profile.name = nextName; }); } setEditingProfileId(null); setEditingProfileName(""); }; const cancelProfileRename = () => { setEditingProfileId(null); setEditingProfileName(""); }; if (!catalogEditable) { // catalogEditable=false covers two unrelated cases: settings fetch failed, // or multi-user grant denied. Split them so a Docker user without the // 8001 port mapped does not see an "assigned by administrator" hint. if (settingsError) { return (
{t( "Backend unreachable — model endpoints will appear once the connection is restored. See the banner above for details.", )}
); } return (
{t( "Model endpoints are assigned by your administrator. You can still personalize theme and language here.", )}
{/* One thing an ordinary user CAN configure for themselves: an owner-bound Codex login. It authenticates their own ChatGPT plan, so it is never something an administrator can grant them — the account has to sign in for itself (#781). The card talks only to the per-user OAuth endpoints and exposes no catalog. */} {service === "llm" && }
); } return (
{activeProfile ? (
{/* ── The providers configured for this service ────────────────── A card is a place, not a switch: opening one pops a dialog with its connection fields and its models, and nothing in there changes which provider the app is running on. That is what "In use" is for. */} addProfile(service)}> {t("Add provider")} } /> {profiles.map((profile) => ( commitProfileRename(profile.id)} onRenameCancel={cancelProfileRename} onRenameStart={() => startProfileRename(profile)} onOpen={() => { setOpenProfileId(profile.id); setExpandedModelId( profile.id === inUseProfileId ? (inUseModelId ?? null) : (profile.models[0]?.id ?? null), ); }} onUse={() => mutateCatalog((next) => { next.services[service].active_profile_id = profile.id; if (service !== "search") { next.services[service].active_model_id = profile.models[0]?.id ?? null; } }) } /> ))} addProfile(service)} /> {/* ── One provider, in a dialog: its connection, then its models ── */} {openedProfile && ( } width="lg" footer={
} >
mutateCatalog((next) => { next.services[service].active_profile_id = openedProfile.id; if (service !== "search") { next.services[service].active_model_id = openedProfile.models[0]?.id ?? null; } }) } /> { if (service !== "llm" || !activeProfile) return; const crossesCodeBuddyBoundary = provider.value === "codebuddy" || previousProvider === "codebuddy"; if (crossesCodeBuddyBoundary) { const profileId = activeProfile.id; mutateCatalog((next) => { const target = next.services.llm; const profile = target.profiles.find( (item) => item.id === profileId, ); if (!profile || profile.binding !== provider.value) return; if (provider.value === "codebuddy") { profile.models = []; target.active_model_id = null; return; } const modelId = `llm-model-${Date.now()}`; profile.models = [ { id: modelId, name: defaultModelLabel(language, 1), model: "", }, ]; target.active_model_id = modelId; }); } if (provider.value === "codebuddy") { void syncProviderModels({ binding: provider.value, base_url: provider.base_url || "", api_key: "", }); } }} /> {service !== "search" && (
{service === "llm" && openedProfile.binding === "codebuddy" && ( void syncProviderModels()} disabled={modelsSyncing} > {t("Sync models")} )} {LLM_SHAPED.has(service) && !isCodexOAuth && openedProfile.binding !== "codebuddy" && Boolean( String(openedProfile.base_url || "").trim(), ) && ( setPickerOpen(true)}> {t("List models")} )} addModel(service, openedProfile.id)} > {t("Add model")} } /> {/* Capped at 2 columns rather than the page grid's `xl:grid-cols-3` — that breakpoint reads the browser viewport, not this dialog's fixed width, and would force 3 columns into a 600px box on a large screen. */}
{openedProfile.models.map((model, index) => ( commitModelRename(model.id)} onRenameCancel={cancelModelRename} onRenameStart={() => startModelRename(model)} onToggleExpand={() => setExpandedModelId( model.id === expandedModelId ? null : model.id, ) } onUse={() => mutateCatalog((next) => { next.services[service].active_profile_id = openedProfile.id; next.services[service].active_model_id = model.id; }) } onDelete={() => removeActiveModel( service, openedProfile.id, model.id, ) } /> ))} addModel(service, openedProfile.id)} />
)} {service !== "search" && (
{activeModel && (!isCodexOAuth || isBoundManagedCodex) && (
{(activeModel.name || "").trim() || t("Model")}
)} {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (
{!isCodexOAuth && (
{t("Model ID")}
updateModelField( service, "model", e.target.value, ) } placeholder="gpt-4o" />
)} {service === "llm" && ( <> {!isCodexOAuth && ( <>
{t("Context Window")}
updateContextWindowField(e.target.value) } placeholder="65536" />
)} {reasoningOptions.length > 0 && (
{t("Reasoning effort")}

{t( "Sets this model's default reasoning depth. Auto leaves the choice to the provider.", )}

)} )} {LLM_SHAPED.has(service) && !isCodexOAuth && ( 0} onChange={updateModelCapability} /> )} {service === "embedding" && (
{t("Dimension")}
updateModelField(service, "dimension", value) } />
)} {service === "tts" && ( <>
{t("Voice")}
updateModelField( service, "voice", e.target.value, ) } placeholder="alloy" />

{t( "Provider-specific voice name, e.g. alloy (OpenAI) or model:voice (SiliconFlow).", )}

{t("Output format")}
)} {service === "imagegen" && ( <>
{t("Image size")}
updateModelField( service, "size", e.target.value, ) } placeholder="1024x1024" />

{t( "Default pixel size sent with each request. Leave empty for the provider default.", )}

{t("Quality / Style")}
updateModelField( service, "quality", e.target.value, ) } placeholder={t("quality (e.g. hd)")} /> updateModelField( service, "style", e.target.value, ) } placeholder={t("style (e.g. vivid)")} />
)} {service === "videogen" && ( <>
{t("Aspect ratio")}
updateModelField( service, "aspect_ratio", e.target.value, ) } placeholder="16:9" />

{t( "Defaults sent with each request. Leave empty for the provider default.", )}

{t("Duration / Resolution")}
updateModelField( service, "duration", e.target.value, ) } placeholder={t("seconds")} /> updateModelField( service, "resolution", e.target.value, ) } placeholder="720p" />
)}
)}
)}
)} {pickerOpen && openedProfile && (service === "llm" || service === "task") && ( model.model)} onClose={() => setPickerOpen(false)} onAdd={(ids) => { const profileId = openedProfile.id; mutateCatalog((next) => { const target = next.services[service]; const profile = target.profiles.find( (item) => item.id === profileId, ); if (!profile) return; const present = new Set( profile.models.map((model) => model.model), ); ids .filter((id) => !present.has(id)) .forEach((id, index) => { profile.models.push({ id: `${service}-model-${Date.now()}-${index}`, name: id, model: id, }); }); if ( profile.id === target.active_profile_id && !profile.models.some( (model) => model.id === target.active_model_id, ) ) { target.active_model_id = profile.models[0]?.id ?? null; } }); setPickerOpen(false); setToast(t("Added {{count}} models.", { count: ids.length })); }} /> )}
{/* ── Diagnostics — per-service, inline ── */}
{diagnosticsOpen && (

{t( "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.", { service: t(SERVICE_LABEL[service]) }, )}

                    {testRunning === service || logs
                      ? logs
                      : t("Waiting for test run...")}
                  
)}
) : ( // Zero state in the same language as the populated one: the grid with // only its add card in it, so starting out looks like what comes next.
addProfile(service)} />
)} {deletingProfile && ( { removeActiveProfile(service, deletingProfile.id); setDeletingProfile(null); setOpenProfileId(null); setExpandedModelId(null); }} onCancel={() => setDeletingProfile(null)} > {deletingProfile.id === inUseProfileId ? t( "This is your active {{service}} provider — deleting it switches to {{next}}.", { service: t(SERVICE_LABEL[service]), next: profiles.find((item) => item.id !== deletingProfile.id) ?.name ?? t("nothing configured"), }, ) : t( "This removes {{count}} model(s) and its saved credentials. This can't be undone.", { count: deletingProfile.models.length }, )} )}
); } function defaultModelLabel(language: "en" | "zh", index: number): string { const safeIndex = index > 0 ? index : 1; return language === "zh" ? `模型${safeIndex}` : `Model ${safeIndex}`; } function formatCompactTokens(value: string | number | undefined): string { if (value === undefined || value === "") return ""; const parsed = typeof value === "number" ? value : Number.parseInt(String(value).replace(/[^\d]/g, ""), 10); if (!Number.isFinite(parsed) || parsed <= 0) return ""; if (parsed >= 1_000_000) { const m = parsed / 1_000_000; return `${m >= 10 ? m.toFixed(0) : m.toFixed(1).replace(/\.0$/, "")}M`; } if (parsed >= 1_000) { const k = parsed / 1_000; return `${k >= 10 ? k.toFixed(0) : k.toFixed(1).replace(/\.0$/, "")}K`; } return String(parsed); } function formatVoiceBadge(value: string | undefined): string { const voice = (value || "").trim(); if (!voice) return ""; // "model:voice" → show just the voice segment to keep the chip compact. const tail = voice.includes(":") ? voice.slice(voice.lastIndexOf(":") + 1) : voice; return tail.length > 14 ? `${tail.slice(0, 13)}…` : tail; } function formatDimensionBadge(value: string | number | undefined): string { if (value === undefined || value === "") return ""; const parsed = typeof value === "number" ? value : Number.parseInt(String(value).replace(/[^\d]/g, ""), 10); if (!Number.isFinite(parsed) || parsed <= 0) return ""; return `${parsed}d`; } function formatIsoLocal(value: string | undefined): string { if (!value) return ""; const parsed = new Date(value); if (Number.isNaN(parsed.getTime())) return value; const pad = (n: number) => String(n).padStart(2, "0"); return ( `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ` + `${pad(parsed.getHours())}:${pad(parsed.getMinutes())}` ); } function ContextWindowMeta({ model }: { model: CatalogModel }) { const { t } = useTranslation(); if (!model.context_window) return null; const source = formatContextWindowSource(model.context_window_source, t); const updatedAt = formatIsoLocal(model.context_window_detected_at); return (
{t("Source")}: {source} {updatedAt && ( <> · {updatedAt} )}
); } function ContextWindowDetectionBanner({ model, detection, onApply, }: { model: CatalogModel; detection: LlmContextWindowDetection | null; onApply: () => void; }) { const { t } = useTranslation(); if (!detection) return null; const currentRaw = Number.parseInt( String(model.context_window || "").replace(/[^\d]/g, ""), 10, ); const matches = Number.isFinite(currentRaw) && currentRaw === detection.contextWindow; const detectedFormatted = detection.contextWindow.toLocaleString("en-US"); const detectedAt = formatIsoLocal(detection.detectedAt); const source = formatContextWindowSource(detection.source, t); if (matches) { return (
{t("Detected value matches your current setting")} ({detectedFormatted} · {source})
); } return (
{t("Detected")}: {detectedFormatted} · {source} {detectedAt && ( · {detectedAt} )}
); } function ProfileFields({ service, profile, showApiKey, setShowApiKey, showSearchProviderWarning, isSupportedSearchProvider, isDeprecatedSearchProvider, searchProviderMissingKey, supportedSearchProviderNames, onProviderChanged, }: { service: ServiceName; profile: CatalogProfile; showApiKey: boolean; setShowApiKey: (next: boolean | ((prev: boolean) => boolean)) => void; showSearchProviderWarning: boolean; isSupportedSearchProvider: boolean; isDeprecatedSearchProvider: boolean; searchProviderMissingKey: boolean; supportedSearchProviderNames: string; onProviderChanged: ( provider: ProviderOption, previousProvider: string, ) => void; }) { const { t } = useTranslation(); const { draft, providers, updateProfileField: setProfileField, updateModelField: setModelField, unlinkProfile, } = useSettings(); // Bound to the profile on screen. The context mutators fall back to whatever // is *in use* when no id is given, so editing an opened-but-inactive // provider here used to rewrite the active one's fields instead. const updateProfileField = useCallback( (svc: ServiceName, field: keyof CatalogProfile, value: string) => setProfileField(svc, field, value, profile.id), [setProfileField, profile.id], ); const updateModelField = useCallback( (svc: ServiceName, field: keyof CatalogModel, value: string) => setModelField(svc, field, value, profile.id), [setModelField, profile.id], ); const [extraOpen, setExtraOpen] = useState(false); // A profile fed by a connection shows its credentials but does not let them // be edited here: the next save would mirror the connection's values back // over anything typed, and a field that silently reverts is worse than one // that says where it comes from. const linkedConnection = (draft.connections ?? []).find( (item) => item.id === profile.connection_id, ) ?? null; const providerValue = service === "search" ? profile.provider || "" : profile.binding || ""; const providerOption = (providers[service] || []).find( (option) => option.value === providerValue, ); const isManagedCodex = isManagedCodexProfile(profile); const isCodexOAuth = isCodexOAuthProfile( service, providerValue, providerOption, profile, ); const isCodeBuddyAuth = service === "llm" && providerValue === "codebuddy"; const apiFormats = LLM_SHAPED.has(service) ? (providerOption?.api_formats ?? []) : []; const supportsApiFormatSelection = apiFormats.length > 1; const apiFormat = profile.api_format || providerOption?.default_api_format || "auto"; const changeApiFormat = (next: string) => { updateProfileField(service, "api_format", next); // A vendor may serve the new format at a different endpoint (MiniMax: // /v1 vs /anthropic). Follow it only while the field still holds the old // format's default — a hand-typed URL is the user's and stays. const baseUrls = providerOption?.base_urls ?? {}; const previousDefault = baseUrls[apiFormat] ?? providerOption?.base_url ?? ""; const nextDefault = baseUrls[next] ?? providerOption?.base_url ?? ""; const current = String(profile.base_url || "").trim(); if ( !linkedConnection && nextDefault && nextDefault !== current && (!current || current === previousDefault) ) { updateProfileField(service, "base_url", nextDefault); } }; const fields = isCodexOAuth || isCodeBuddyAuth ? { apiKey: false, baseUrl: false, baseUrlRequired: false } : service === "search" ? searchProviderFields(profile.provider, providerOption) : { apiKey: true, baseUrl: true, baseUrlRequired: false }; const missingRequiredBaseUrl = fields.baseUrlRequired && !String(profile.base_url || "").trim(); return (
{t("Provider")}
{providerValue && ( )}
{showSearchProviderWarning && (

{isSupportedSearchProvider ? searchProviderMissingKey ? t( "{{provider}} requires an API key. It will fail hard without credentials.", { provider: providerOption?.label ?? providerValue }, ) : t("Supported provider.") : isDeprecatedSearchProvider ? t("Deprecated provider. Switch to one of: {{providers}}.", { providers: supportedSearchProviderNames, }) : t("Unsupported provider. Use one of: {{providers}}.", { providers: supportedSearchProviderNames, })}

)}
{isCodexOAuth && (
)} {isCodeBuddyAuth && (
)} {linkedConnection && (
{t("Credentials come from the {{name}} connection.", { name: linkedConnection.name, })} {t("Edit connection")}
)} {fields.baseUrl && (
{service === "embedding" ? t("Endpoint URL") : t("Base URL")}
updateProfileField(service, "base_url", e.target.value) } placeholder={ service === "embedding" ? "https://api.openai.com/v1/embeddings" : service === "search" ? "http://localhost:8888" : "https://api.openai.com/v1" } /> {service === "embedding" && (

{t( "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.", )}

)} {missingRequiredBaseUrl && (

{t("Required — without it, search falls back to DuckDuckGo.")}

)}
)} {fields.apiKey && (
{t("API Key")}
updateProfileField(service, "api_key", e.target.value) } placeholder="sk-..." />
)} {supportsApiFormatSelection && (
{t("API format")}
{API_FORMAT_HINTS[apiFormat] && (

{t(API_FORMAT_HINTS[apiFormat])}

)}
)} {!isCodexOAuth && !isCodeBuddyAuth && (
{extraOpen && (
{t("API Version")}
updateProfileField(service, "api_version", e.target.value) } placeholder={t("Optional")} />
{service === "search" ? (
{t("Proxy")}
updateProfileField(service, "proxy", e.target.value) } placeholder={t("http://127.0.0.1:7890 (optional)")} />
) : (
{t("Extra Headers (JSON)")}