"use client"; import { stageRegistryAction, type RegistryEdit } from "@/lib/provider-registry"; import { useEffect, useId, useRef, useState } from "react"; import Link from "next/link"; import { Check, Plus, SlidersHorizontal, Trash2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import ProviderIcon from "@/components/common/ProviderIcon"; import { useSettings, type CatalogModel, type CatalogProfile, type ServiceName, } from "@/features/settings/store/SettingsStore"; import { flattenModels, modelProvider, providerAdapter, providerIdentity, providerProbeInput, providerRegistry, SERVICE_TITLES, type ProviderSource, } from "@/lib/provider-registry"; import { voiceModelOptions } from "@/lib/voice-settings"; import { VoiceModelFields } from "./VoiceModelFields"; import { VoicePreviewPanel } from "./VoicePreviewPanel"; import { ModelTestPanel } from "./ModelTestPanel"; import EmbeddingModelUsage from "./EmbeddingModelUsage"; import { EditableRegistryName, RegistryField, RegistryModelIdField, RegistryProbe, registryButton, registryDanger, registryPrimary, } from "./RegistryControls"; import { inputClass, selectClass, subPanelClass } from "./shared"; import { WorkspaceDetailEmpty, WorkspaceRail, WorkspaceSplit, workspaceCardClass, } from "./WorkspaceShell"; import { randomUuid } from "@/lib/random-uuid"; type ModelPage = "llm" | "embedding" | "search" | "voice" | "multimodal"; const PAGE_SERVICES: Record = { llm: ["llm", "task"], embedding: ["embedding"], search: ["search"], voice: ["tts", "stt"], multimodal: ["imagegen", "videogen"], }; export function ModelsWorkspace({ page, initialService, }: { page: ModelPage; initialService?: ServiceName; }) { const { t } = useTranslation(); const { draft, providers, connectionTargets, catalogEditable, mutateCatalog, } = useSettings(); const services = PAGE_SERVICES[page]; const rows = flattenModels(draft, services); const editorRef = useRef(null); const [selected, setSelected] = useState(null); const [adding, setAdding] = useState(false); const [newService, setNewService] = useState( initialService && services.includes(initialService) ? initialService : services[0], ); const [newProvider, setNewProvider] = useState(""); const [query, setQuery] = useState(""); const [filter, setFilter] = useState("all"); useEffect(() => { const params = new URLSearchParams(window.location.search); const profileId = params.get("profile"); if (profileId) setSelected( (current) => current || rows.find((r) => r.profile.id === profileId)?.key || null, ); // Resolve old profile links after the settings payload arrives. // eslint-disable-next-line react-hooks/exhaustive-deps }, [rows.length]); // 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(() => editorRef.current?.scrollIntoView({ behavior: "smooth", block: "start", }), ); }; const selectModel = (key: string) => { setSelected(key); setAdding(false); revealDetail(); }; const selectedRow = rows.find((r) => r.key === selected); // Providers and models can be created together in the same draft. const sources = providerRegistry(draft); /** Whether a built-in adapter is on record for this vendor and service. */ const declared = (source: ProviderSource, service: ServiceName) => { const adapterService = service === "task" ? "llm" : service; const exact = providers[adapterService]?.some( (option) => option.value === source.provider && option.value !== "none" && option.status !== "deprecated", ); const mapped = connectionTargets.find( (target) => target.provider === source.provider, )?.services[adapterService]; return Boolean( exact || mapped || (service !== "search" && source.service === service) || (service === "task" && source.service === "llm") || (service !== "search" && source.provider === "custom"), ); }; // Not being on record is not a veto for any service. Whether a vendor serves // a given model type is not knowable from its registry entry — plenty of // OpenAI-compatible endpoints serve embeddings or speech without appearing in // that service's table — so every provider is selectable, the ones with no // adapter on record are only grouped apart, and a wrong pick is reported by // the model test rather than pre-empted here. Managed credentials stay out: // that is not a capability judgement, their models arrive with them. const selectable = sources.filter( (source) => !("managed_by" in source.source && source.source.managed_by), ); const start = () => { setAdding(true); revealDetail(); const preferred = new URLSearchParams(window.location.search).get( "provider", ); if (preferred && selectable.some((p) => p.id === preferred)) setNewProvider(preferred); }; const create = () => { const source = selectable.find((p) => p.id === newProvider); if (!source) return; const profileId = `${newService}-profile-${randomUuid()}`; const modelId = `${newService}-model-${randomUuid()}`; const ref = providerAdapter( source, newService, connectionTargets, providers, ); const target = providers[newService]?.find((p) => p.value === ref.binding); const model = target?.default_model || ""; mutateCatalog((next) => { const profile: CatalogProfile = { id: profileId, name: source.name, binding: ref.binding, provider: newService === "search" ? ref.binding : undefined, provider_ref: ref, api_key: "", base_url: "", api_version: "", models: newService === "search" ? [] : [ { id: modelId, model, name: model, provider_ref: ref, ...(newService === "tts" ? { voice: target?.default_voice || "", response_format: voiceModelOptions(target?.voice_options, target?.default_model || "")?.formats[0] || "mp3", } : {}), }, ], }; if (newService === "search") profile.display_name = source.name; next.services[newService].profiles.push(profile); }); setSelected( newService === "search" ? `${newService}:${profileId}` : `${newService}:${profileId}:${modelId}`, ); setAdding(false); setQuery(""); setFilter("all"); }; if (!catalogEditable) return (

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

); const filtered = rows.filter( (row) => (filter === "all" || row.service === filter) && `${row.model?.name || row.profile.display_name || row.profile.name} ${row.model?.model || ""} ${modelProvider(draft, row.service, row.profile, row.model)?.name || ""}` .toLowerCase() .includes(query.toLowerCase()), ); const addLabel = t( page === "search" ? "Add search configuration" : "Add model", ); return (
{!sources.length && (

{t("Add a provider before adding models.")}

{t("Go to providers")}
)} {addLabel} } search={{ label: t("Find model"), value: query, onChange: setQuery, placeholder: t("Search by model or provider"), }} filter={ page === "voice" || page === "multimodal" ? ( ) : undefined } empty={ filtered.length ? undefined : rows.length ? t("No models match your search.") : t("No models configured yet.") } > {filtered.map((row) => { const provider = modelProvider( draft, row.service, row.profile, row.model, ); const bucket = draft.services[row.service]; const isDefault = bucket.active_profile_id === row.profile.id && (!row.model || bucket.active_model_id === row.model.id) && (row.service !== "task" || (bucket.mode !== "inherit" && bucket.mode !== "reference")); const label = row.model?.name || row.model?.model || row.profile.display_name || (row.model ? t("New model") : row.profile.name); const providerName = provider?.name || t("Provider unavailable"); const editing = !adding && row.key === selected; return ( ); })} } detail={
{/* One configuring surface at a time. The add form used to open as a band above the split while an existing model's editor kept rendering below it, so two things claimed to be "currently configuring". Cancel returns to whatever was open before. */} {adding ? ( { setNewService(value); setNewProvider(""); }} provider={newProvider} onProvider={setNewProvider} sources={selectable} declared={(source) => declared(source, newService)} onCreate={create} onCancel={() => setAdding(false)} /> ) : selectedRow ? ( declared(source, selectedRow.service)} onRemoved={() => setSelected(null)} /> ) : ( } title={t("Nothing selected")} hint={t( "Select a model to view its settings and connection test.", )} /> )}
} />
); } /** * Provider options for one service. Vendors with no adapter on record are * offered rather than hidden — they are only separated out, so the list still * says which ones are a known quantity without deciding for you. */ function ProviderOptions({ sources, declared, }: { sources: ProviderSource[]; declared: (source: ProviderSource) => boolean; }) { const { t } = useTranslation(); const option = (p: ProviderSource) => ( ); const unverified = sources.filter((source) => !declared(source)); if (!unverified.length) return <>{sources.map(option)}; const known = sources.filter(declared); return ( <> {known.length > 0 && ( {known.map(option)} )} {unverified.map(option)} ); } /** * The add flow. It lives in the detail pane, opposite the list, because that is * the one place on the page that means "what you are configuring right now" — * and only one thing can be there at a time. */ function AddModelPanel({ page, service, onService, provider, onProvider, sources, declared, onCreate, onCancel, }: { page: ModelPage; service: ServiceName; onService: (value: ServiceName) => void; provider: string; onProvider: (value: string) => void; sources: ProviderSource[]; declared: (source: ProviderSource) => boolean; onCreate: () => void; onCancel: () => void; }) { const { t } = useTranslation(); const title = t( page === "search" ? "Add search configuration" : "Add model", ); return (

{title}

{t("Manage providers")}
{(page === "voice" || page === "multimodal") && ( )}

{t( service === "search" ? "Every provider is selectable. Search has no generic adapter, so a provider without a search API of its own is rejected by the search test — that is where a wrong pick shows up." : "Every provider is selectable. One with no adapter on record for this model type is called as an OpenAI-compatible endpoint derived from its provider URL — add the model, then run the model test to see whether it answers.", )}

); } type ModelRow = ReturnType[number]; function ModelEditor({ row, sources, declared, onRemoved, }: { row: ModelRow; sources: ProviderSource[]; declared: (source: ProviderSource) => boolean; onRemoved: () => void; }) { const { t } = useTranslation(); const { draft, providers, connectionTargets, mutateCatalog, applying, } = useSettings(); const stageRegistry = async (edit: RegistryEdit) => { mutateCatalog((next) => stageRegistryAction(next, edit)); return true; }; const { service, profile, model } = row; const provider = modelProvider(draft, service, profile, model); const speechProvider = model?.provider_ref?.binding || profile.provider_ref?.binding || provider?.provider || profile.binding || "custom"; const speechOptions = providers[service]?.find(p => p.value === speechProvider)?.voice_options; const speechPreset = voiceModelOptions(speechOptions, model?.model ?? ""); const [listed, setListed] = useState<{ provider: string; models: { id: string }[]; } | null>(null); const name = model ? model.name || model.model || t("New model") : profile.display_name || profile.name; const managed = Boolean( model?.managed_by || profile.read_only || profile.managed_by, ); const saved = draft.services[service].profiles.find( (p) => p.id === profile.id, ); const savedModel = service === "search" ? Boolean(saved && !saved.provider_only) : saved?.models.some((m) => m.id === model?.id); const active = savedModel && draft.services[service].active_profile_id === profile.id && (!model || draft.services[service].active_model_id === model.id); const task = draft.services.task; const assignedToTask = Boolean(model && [task, ...Object.values(task.overrides ?? {})].some((choice) => (service === "llm" && choice.mode === "reference" && choice.selection?.profile_id === profile.id && choice.selection?.model_id === model.id) || (service === "task" && choice.mode === "profiles" && choice.active_profile_id === profile.id && choice.active_model_id === model.id) )); const update = (field: keyof CatalogModel, value: unknown) => mutateCatalog((next) => { const target = next.services[service].profiles .find((p) => p.id === profile.id) ?.models.find((m) => m.id === model?.id); if (!target) return; if (field === "model" && (!target.name || target.name === target.model)) target.name = String(value); if (field === "model" && (service === "tts" || service === "stt")) { const before = voiceModelOptions(speechOptions, target.model); const after = voiceModelOptions(speechOptions, String(value)); if (after && after !== speechOptions?.fallback) { if (before?.voices.some(v => v.id === target.voice) && !after.voices.some(v => v.id === target.voice)) target.voice = after.voices[0]?.id ?? ""; if (before?.formats.includes(target.response_format ?? "") && !after.formats.includes(target.response_format ?? "")) target.response_format = after.formats[0] ?? ""; if (before?.languages.some(l => l.id === target.language) && !after.languages.some(l => l.id === target.language)) target.language = ""; if (!after.instructions) delete target.instructions; if (!after.speed) delete target.speed; } } Object.assign(target, { [field]: value }); if (field === "name" && managed) target.user_name = String(value); if (field === "context_window") { target.context_window_source = value ? "manual" : "default"; delete target.context_window_tokens; delete target.context_window_detected_at; } }); const updateSearch = (field: string, value: unknown) => mutateCatalog((next) => { const target = next.services.search.profiles.find( (p) => p.id === profile.id, ); if (target) Object.assign(target, { [field]: value }); }); const chooseProvider = (id: string) => { const source = sources.find((p) => p.id === id); if (!source) return; const ref = providerAdapter(source, service, connectionTargets, providers); if (model) update("provider_ref", ref); else updateSearch("provider_ref", ref); setListed(null); }; const list = listed && listed.provider === provider?.id ? listed.models : provider?.source.discovery?.models || []; const remove = async () => { await stageRegistry({ kind: "model", service, profile_id: profile.id, model_id: model?.id, delete: true }); onRemoved(); }; return (
{/* Opaque on purpose: it stays put over the scrolling body. */}
{t("Currently configuring")} {t(SERVICE_TITLES[service])} {!savedModel && ( · {t("Not saved")} )}
model ? update("name", value) : updateSearch("display_name", value) } />
{provider?.name || t("Provider unavailable")}
{model?.model && (

{model.model}

)}
{service === "embedding" && model && }
{/* Why the test below matters more here: nothing vouches for this pairing yet, so say what request it will actually make. */} {provider && !declared(provider) && (

{t( service === "search" ? "No search adapter is on record for this provider, and search has no OpenAI-compatible fallback. Run the test below — it will say so rather than search with the wrong engine." : "No adapter for this model type is on record for this provider. DeepTutor calls it as an OpenAI-compatible endpoint derived from the provider URL; run the model test below to confirm it answers.", )}

)} {t("Manage provider connection")}
{model && (
m.id) ?? []), ...list.map((item) => item.id)])]} disabled={managed} onChange={(value) => update("model", value)} placeholder={t("Choose a listed model or enter a model ID")} />

{t( "The display name is used in chat. Double-click the name above or use the edit button to rename it.", )}

)} {service === "search" && (
updateSearch( "max_results", Math.max(1, Math.min(10, Number(value) || 5)), ) } />

{t( "Search APIs use an engine configuration rather than a model ID or context window.", )}

)}
{model && provider && !managed && service !== "search" && ( p.value === provider.provider, )?.base_url || providers[service]?.find((p) => p.value === provider.provider) ?.base_url, )} discovery={provider.source.discovery} listing onResult={(result) => setListed({ provider: provider.id, models: result.models }) } /> )} {model && (service === "tts" || service === "stt") ? ( ) : model && } {service === "tts" && model ? : }
); } function ModelParameters({ service, model, update, managed, }: { service: ServiceName; model: CatalogModel; update: (field: keyof CatalogModel, value: unknown) => void; managed: boolean; }) { const { t } = useTranslation(); const contextId = useId(); const language = service === "llm" || service === "task"; const fields: [keyof CatalogModel, string][] = service === "embedding" ? [ ["dimension", "Dimensions"], ["supported_dimensions", "Supported dimensions"], ] : service === "tts" ? [ ["voice", "Voice"], ["response_format", "Response format"], ] : service === "stt" ? [["language", "Language"]] : service === "imagegen" ? [ ["size", "Image size"], ["quality", "Quality"], ["style", "Style"], ["response_format", "Response format"], ] : service === "videogen" ? [ ["aspect_ratio", "Aspect ratio"], ["duration", "Duration (seconds)"], ["resolution", "Resolution"], ] : []; return (
{language && (
{/* Two knobs of the same kind, so they sit side by side instead of stacking into one more column of full-width inputs. */}
{/* The heading *is* this field's label. It used to sit above a second one that said the same thing, which read as a repeat and — the visible part — pushed this input a whole label row below the select beside it, so the pair never lined up. */}
update("context_window", e.target.value)} placeholder={t("Default")} />

{t( "Keep the default, enter a custom value, or use the detected value after testing. Testing does not overwrite your choice.", )}

{t("Reasoning effort")}

{t("Model capabilities")}
{(["tools", "vision", "json_output", "reasoning"] as const).map( (key) => ( ), )}
)} {!!fields.length && (
{fields.map(([field, label]) => ( update(field, v)} placeholder={t("Default")} /> ))}
)} {service === "embedding" && ( )} {managed && (

{t( "This signed-in provider manages model IDs, context, and capabilities. You can rename the model and choose its reasoning effort.", )}

)}
); }