From 874ea33d76d562e115f660d0d20c1eb2163da2dc Mon Sep 17 00:00:00 2001 From: yaqi <1360968891@qq.com> Date: Wed, 25 Nov 2026 09:36:07 +0800 Subject: [PATCH] feat(settings): edit the fallback chain from the language models page --- .../sections/models/FallbackChainEditor.tsx | 213 ++++++++++++++++++ .../sections/models/LlmSettingsSection.tsx | 34 +-- .../sections/models/fallback-chain.ts | 94 ++++++++ web/locales/en/app.json | 15 +- web/locales/zh/app.json | 15 +- web/tests/fallback-chain.spec.ts | 107 +++++++++ 6 files changed, 442 insertions(+), 36 deletions(-) create mode 100644 web/features/settings/sections/models/FallbackChainEditor.tsx create mode 100644 web/features/settings/sections/models/fallback-chain.ts create mode 100644 web/tests/fallback-chain.spec.ts diff --git a/web/features/settings/sections/models/FallbackChainEditor.tsx b/web/features/settings/sections/models/FallbackChainEditor.tsx new file mode 100644 index 000000000..98811aafc --- /dev/null +++ b/web/features/settings/sections/models/FallbackChainEditor.tsx @@ -0,0 +1,213 @@ +"use client"; + +import { useMemo, 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 { + 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 stored = useMemo( + () => + (llm.fallbacks ?? []).map((entry) => ({ + profile_id: entry.profile_id, + model_id: entry.model_id, + })), + [llm.fallbacks], + ); + + const [rows, setRows] = useState(stored.length ? stored : []); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(null); + + 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.", + )} +
+
+ +
+ + {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 })} + +
+
+ ); +} diff --git a/web/features/settings/sections/models/LlmSettingsSection.tsx b/web/features/settings/sections/models/LlmSettingsSection.tsx index 2ac0e26c8..7f52ab008 100644 --- a/web/features/settings/sections/models/LlmSettingsSection.tsx +++ b/web/features/settings/sections/models/LlmSettingsSection.tsx @@ -4,38 +4,8 @@ import { useTranslation } from "react-i18next"; import { ModelsWorkspace } from "@/components/settings/ModelsWorkspace"; import { SettingsPageHeader } from "@/components/settings/shared"; -import { useSettings } from "@/features/settings/store/SettingsStore"; -/** - * The ordered fallback chain (#2693) is configured outside this page for now. - * Show it read-only so an operator can tell whether a failover path exists — - * an Apply on this page preserves the chain, it does not create one. - */ -function FallbackChainNotice() { - const { t } = useTranslation(); - const { catalog } = useSettings(); - const chain = catalog.services.llm.fallbacks ?? []; - if (chain.length === 0) return null; - return ( -
-
- {t("Fallback chain: {{count}} configured", { count: chain.length })} -
-
- {t( - "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends. Edited in the catalog, not on this page.", - )} -
-
    - {chain.map((entry) => ( -
  • - {entry.profile_id} / {entry.model_id} -
  • - ))} -
-
- ); -} +import { FallbackChainEditor } from "./FallbackChainEditor"; export default function LlmSettingsPage() { const { t } = useTranslation(); @@ -48,7 +18,7 @@ export default function LlmSettingsPage() { "Manage language models and their context, capabilities, and connection tests.", )} /> - + ); diff --git a/web/features/settings/sections/models/fallback-chain.ts b/web/features/settings/sections/models/fallback-chain.ts new file mode 100644 index 000000000..5325a9844 --- /dev/null +++ b/web/features/settings/sections/models/fallback-chain.ts @@ -0,0 +1,94 @@ +/** + * Pure helpers for the fallback-chain editor (#2693 P3). + * + * The chain is one ordered list on `services.llm`, pointing at profiles and + * models that already exist in the catalog — the editor never creates them. + */ + +export type FallbackEntry = { profile_id: string; model_id: string }; + +export type FallbackChoice = { + /** `profile_id` used by the payload. */ + profileId: string; + /** `models[].id` used by the payload. */ + modelId: string; + /** Human label shown in the selects. */ + label: string; +}; + +type ProfileLike = { + id: string; + name?: string; + display_name?: string; + models?: { id: string; name?: string; model?: string }[]; +}; + +/** Every selectable (profile, model) pair in one flat, ordered list. */ +export function fallbackChoices(profiles: ProfileLike[]): FallbackChoice[] { + const choices: FallbackChoice[] = []; + for (const profile of profiles) { + const profileName = profile.display_name || profile.name || profile.id; + for (const model of profile.models || []) { + if (!profile.id || !model.id) continue; + const modelName = model.name || model.model || model.id; + choices.push({ + profileId: profile.id, + modelId: model.id, + label: `${profileName} / ${modelName}`, + }); + } + } + return choices; +} + +export function choiceKey(entry: { profile_id: string; model_id: string }): string { + return `${entry.profile_id}\u0000${entry.model_id}`; +} + +/** + * Drop entries that no longer resolve, collapse duplicates, cap the length. + * + * The backend applies the same rules on save; doing it here too keeps a stale + * row (a deleted profile) from being submitted and bouncing with a 400. + */ +export function sanitizeChain( + entries: FallbackEntry[], + choices: FallbackChoice[], + max = 4, +): FallbackEntry[] { + const valid = new Set(choices.map((choice) => `${choice.profileId}\u0000${choice.modelId}`)); + const cleaned: FallbackEntry[] = []; + const seen = new Set(); + for (const entry of entries) { + const profileId = String(entry?.profile_id || "").trim(); + const modelId = String(entry?.model_id || "").trim(); + if (!profileId || !modelId) continue; + const key = `${profileId}\u0000${modelId}`; + if (!valid.has(key) || seen.has(key)) continue; + seen.add(key); + cleaned.push({ profile_id: profileId, model_id: modelId }); + if (cleaned.length >= max) break; + } + return cleaned; +} + +export function chainsEqual(a: FallbackEntry[], b: FallbackEntry[]): boolean { + if (a.length !== b.length) return false; + return a.every( + (entry, index) => + entry.profile_id === b[index].profile_id && entry.model_id === b[index].model_id, + ); +} + +/** + * The chain with the active model removed: retrying the model that just failed + * as its own fallback would only waste the cooldown. + */ +export function withoutActive( + entries: FallbackEntry[], + active: { profile_id?: string | null; model_id?: string | null } | null, +): FallbackEntry[] { + if (!active?.profile_id || !active.model_id) return entries; + const key = `${active.profile_id}\u0000${active.model_id}`; + return entries.filter((entry) => choiceKey(entry) !== key); +} diff --git a/web/locales/en/app.json b/web/locales/en/app.json index a201c932e..5986a0c3d 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -1747,8 +1747,19 @@ "Public API base": "Public API base", "Leave blank for local Docker. Use the externally reachable backend URL, including any proxy path.": "Leave blank for local Docker. Use the externally reachable backend URL, including any proxy path.", "CORS origins": "CORS origins", - "Fallback chain: {{count}} configured": "Fallback chain: {{count}} configured", - "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends. Edited in the catalog, not on this page.": "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends. Edited in the catalog, not on this page.", + "Fallback chain ({{count}} configured)": "Fallback chain ({{count}} configured)", + "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends.": "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends.", + "Add fallback": "Add fallback", + "No fallback configured. The turn fails when the active model fails.": "No fallback configured. The turn fails when the active model fails.", + "Fallback {{index}}": "Fallback {{index}}", + "Choose a configured model": "Choose a configured model", + "Move up": "Move up", + "Move down": "Move down", + "Remove fallback": "Remove fallback", + "Save fallback chain": "Save fallback chain", + "Order matters · up to {{max}}": "Order matters · up to {{max}}", + "Could not save the fallback chain.": "Could not save the fallback chain.", + "Fallback chain saved.": "Fallback chain saved.", "Only required for authenticated cross-origin deployments. Use frontend origins, not API URLs.": "Only required for authenticated cross-origin deployments. Use frontend origins, not API URLs.", "Comma, semicolon, and newline separators are accepted. Bare host:port values are stored as http://host:port.": "Comma, semicolon, and newline separators are accepted. Bare host:port values are stored as http://host:port.", "Auth is enabled but secure cookies are off. Cross-site HTTPS deployments should set auth.cookie_secure=true and restart so SameSite=None cookies work in modern browsers.": "Auth is enabled but secure cookies are off. Cross-site HTTPS deployments should set auth.cookie_secure=true and restart so SameSite=None cookies work in modern browsers.", diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json index bbd2d0b29..1df2eb391 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -1163,8 +1163,19 @@ "Public API base": "公共 API base", "Leave blank for local Docker. Use the externally reachable backend URL, including any proxy path.": "本机 Docker 留空即可。远程部署填写浏览器可访问的后端 URL,可包含代理路径。", "CORS origins": "CORS 来源", - "Fallback chain: {{count}} configured": "回退链:已配置 {{count}} 个", - "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends. Edited in the catalog, not on this page.": "当前模型在产生输出前失败时,会按顺序尝试这些候选;主模型冷却结束后自动回切。该配置在目录中编辑,不在本页修改。", + "Fallback chain ({{count}} configured)": "回退链(已配置 {{count}} 个)", + "When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends.": "当前模型在产生输出前失败时,会按顺序尝试这些候选;主模型冷却结束后自动回切。", + "Add fallback": "添加回退", + "No fallback configured. The turn fails when the active model fails.": "尚未配置回退:当前模型失败时,本轮会直接失败。", + "Fallback {{index}}": "回退 {{index}}", + "Choose a configured model": "选择一个已配置的模型", + "Move up": "上移", + "Move down": "下移", + "Remove fallback": "删除回退", + "Save fallback chain": "保存回退链", + "Order matters · up to {{max}}": "顺序即优先级 · 最多 {{max}} 个", + "Could not save the fallback chain.": "回退链保存失败。", + "Fallback chain saved.": "回退链已保存。", "Only required for authenticated cross-origin deployments. Use frontend origins, not API URLs.": "仅认证跨域部署需要填写。这里填前端页面来源,不是 API URL。", "Comma, semicolon, and newline separators are accepted. Bare host:port values are stored as http://host:port.": "支持逗号、分号和换行分隔。裸 host:port 会按 http://host:port 保存。", "Auth is enabled but secure cookies are off. Cross-site HTTPS deployments should set auth.cookie_secure=true and restart so SameSite=None cookies work in modern browsers.": "认证已启用,但安全 Cookie 未开启。跨站 HTTPS 部署应设置 auth.cookie_secure=true 并重启,使 SameSite=None Cookie 在现代浏览器中生效。", diff --git a/web/tests/fallback-chain.spec.ts b/web/tests/fallback-chain.spec.ts new file mode 100644 index 000000000..9996d8a5b --- /dev/null +++ b/web/tests/fallback-chain.spec.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from "vitest"; + +import { + fallbackChoices, + chainsEqual, + sanitizeChain, + withoutActive, + type FallbackEntry, +} from "../features/settings/sections/models/fallback-chain"; + +const PROFILES = [ + { + id: "deepseek", + name: "DeepSeek", + models: [ + { id: "ds-chat", name: "deepseek-chat", model: "deepseek-chat" }, + { id: "ds-reasoner", name: "deepseek-reasoner", model: "deepseek-reasoner" }, + ], + }, + { + id: "local", + display_name: "Local vLLM", + models: [{ id: "local-qwen", model: "qwen3-32b" }], + }, + { id: "empty", models: [] }, +]; + +const entry = (profile: string, model: string): FallbackEntry => ({ + profile_id: profile, + model_id: model, +}); + +describe("fallbackChoices", () => { + it("offers every configured model with a readable label", () => { + expect(fallbackChoices(PROFILES)).toEqual([ + { profileId: "deepseek", modelId: "ds-chat", label: "DeepSeek / deepseek-chat" }, + { + profileId: "deepseek", + modelId: "ds-reasoner", + label: "DeepSeek / deepseek-reasoner", + }, + { profileId: "local", modelId: "local-qwen", label: "Local vLLM / qwen3-32b" }, + ]); + }); + + it("ignores profiles without models", () => { + expect(fallbackChoices([{ id: "empty", models: [] }])).toEqual([]); + }); +}); + +describe("sanitizeChain", () => { + const choices = fallbackChoices(PROFILES); + + it("drops entries that no longer exist and collapses duplicates", () => { + expect( + sanitizeChain( + [ + entry("local", "local-qwen"), + entry("gone", "missing"), + entry("local", "local-qwen"), + entry("deepseek", "ds-chat"), + ], + choices, + ), + ).toEqual([entry("local", "local-qwen"), entry("deepseek", "ds-chat")]); + }); + + it("caps the chain at four candidates", () => { + const many = Array.from({ length: 6 }, (_, index) => + entry("deepseek", `model-${index}`), + ); + const padded = fallbackChoices([ + { + id: "deepseek", + models: many.map((_, index) => ({ id: `model-${index}` })), + }, + ]); + + expect(sanitizeChain(many, padded)).toHaveLength(4); + }); +}); + +describe("withoutActive", () => { + it("removes the active model so it is not its own fallback", () => { + expect( + withoutActive([entry("deepseek", "ds-chat"), entry("local", "local-qwen")], { + profile_id: "deepseek", + model_id: "ds-chat", + }), + ).toEqual([entry("local", "local-qwen")]); + }); + + it("is a no-op when there is no active selection", () => { + const chain = [entry("local", "local-qwen")]; + expect(withoutActive(chain, null)).toEqual(chain); + }); +}); + +describe("chainsEqual", () => { + it("compares order, not just membership", () => { + const a = [entry("local", "local-qwen"), entry("deepseek", "ds-chat")]; + const b = [entry("deepseek", "ds-chat"), entry("local", "local-qwen")]; + + expect(chainsEqual(a, a)).toBe(true); + expect(chainsEqual(a, b)).toBe(false); + }); +});