"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { ArrowDown, ArrowUp, Loader2, Plus, Trash2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import { inputClass } from "@/components/settings/shared"; import { useSettings } from "@/features/settings/store/SettingsStore"; import { apiFetch, apiUrl } from "@/lib/api"; import { availableChoices, fallbackChoices, sanitizeChain, withoutActive, type FallbackEntry, } from "./fallback-chain"; const MAX_FALLBACKS = 4; const emptyRow = (): FallbackEntry => ({ profile_id: "", model_id: "" }); /** * Edit `services.llm.fallbacks` (#2693): an ordered list of existing * profile/model pairs the turn may move to when the active one fails before * any output. The stored chain is what the runtime already reads; this editor * only writes it, through the same `apply/service` endpoint the provider * dialogs use. */ export function FallbackChainEditor() { const { t } = useTranslation(); const { catalog, reloadSettings } = useSettings(); const llm = catalog.services.llm; const choices = useMemo(() => fallbackChoices(llm.profiles || []), [llm.profiles]); const selectable = useMemo( () => // The active model is not a fallback of itself: offering it here would // let the operator build a chain entry the save silently drops. choices.filter( (choice) => !( choice.profileId === llm.active_profile_id && choice.modelId === llm.active_model_id ), ), [choices, llm.active_model_id, llm.active_profile_id], ); const stored = useMemo( () => (llm.fallbacks ?? []).map((entry) => ({ profile_id: entry.profile_id, model_id: entry.model_id, })), [llm.fallbacks], ); const [rows, setRows] = useState(stored); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [saved, setSaved] = useState(null); // The settings store loads asynchronously (and reloads after a save), so the // chain arrives *after* the first render. Without this sync a refresh shows an // empty editor even though the catalog holds a chain — and the next save would // then write that empty list back (#2693). const appliedSignature = useRef(null); const storedSignature = useMemo(() => JSON.stringify(stored), [stored]); useEffect(() => { if (appliedSignature.current === storedSignature) return; appliedSignature.current = storedSignature; setRows(stored); }, [stored, storedSignature]); const dirty = useMemo(() => { const next = sanitizeChain(rows, choices, MAX_FALLBACKS); return JSON.stringify(next) !== JSON.stringify(stored); }, [choices, rows, stored]); const update = (index: number, patch: Partial) => { setRows((current) => current.map((row, position) => (position === index ? { ...row, ...patch } : row)), ); setSaved(null); }; const move = (index: number, delta: number) => { setRows((current) => { const target = index + delta; if (target < 0 || target >= current.length) return current; const next = [...current]; [next[index], next[target]] = [next[target], next[index]]; return next; }); setSaved(null); }; const save = async () => { setSaving(true); setError(null); setSaved(null); try { const chain = withoutActive(sanitizeChain(rows, choices, MAX_FALLBACKS), { profile_id: llm.active_profile_id, model_id: llm.active_model_id, }); const response = await apiFetch(apiUrl("/api/settings/apply/service"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ service: "llm", config: { ...llm, fallbacks: chain }, }), }); const data = (await response.json().catch(() => ({}))) as { detail?: string }; if (!response.ok) { throw new Error(data.detail || t("Could not save the fallback chain.")); } await reloadSettings(); setSaved(t("Fallback chain saved.")); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSaving(false); } }; return (
{t("Fallback chain ({{count}} configured)", { count: stored.length })}
{t( "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends.", )}
{t( "Applies to chat and to background task models. Image, video, speech, search and embedding models are not affected.", )}
{rows.length === 0 ? (

{t("No fallback configured. The turn fails when the active model fails.")}

) : (
    {rows.map((row, index) => { const selected = choices.find( (choice) => choice.profileId === row.profile_id && choice.modelId === row.model_id, ); return (
  • ); })}
)}
{saved && {saved}} {error && {error}} {t("Order matters · up to {{max}}", { max: MAX_FALLBACKS })}
); }