feat(settings): edit the fallback chain from the language models page

This commit is contained in:
yaqi
2026-11-25 09:36:07 +08:00
parent 4b48ca1493
commit 874ea33d76
6 changed files with 442 additions and 36 deletions

View File

@@ -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<FallbackEntry[]>(stored.length ? stored : []);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState<string | null>(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<FallbackEntry>) => {
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 (
<div className="mb-6 rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-[13px] font-medium">
{t("Fallback chain ({{count}} configured)", { count: stored.length })}
</div>
<div className="mt-0.5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
{t(
"When the active model fails before any output, DeepTutor tries these in order and returns to the primary once its cooldown ends.",
)}
</div>
</div>
<button
type="button"
className="rounded-lg border border-[var(--border)] px-2.5 py-1 text-[12px] font-medium disabled:opacity-40"
onClick={() => {
setRows((current) => [...current, emptyRow()]);
setSaved(null);
}}
disabled={rows.length >= MAX_FALLBACKS}
>
<Plus className="mr-1 inline h-3.5 w-3.5" />
{t("Add fallback")}
</button>
</div>
{rows.length === 0 ? (
<p className="mt-3 text-[12px] text-[var(--muted-foreground)]">
{t("No fallback configured. The turn fails when the active model fails.")}
</p>
) : (
<ul className="mt-3 space-y-2">
{rows.map((row, index) => {
const selected = choices.find(
(choice) =>
choice.profileId === row.profile_id && choice.modelId === row.model_id,
);
return (
<li key={`fallback-${index}`} className="flex items-center gap-2">
<select
className={`${inputClass} flex-1`}
aria-label={t("Fallback {{index}}", { index: index + 1 })}
value={selected ? `${selected.profileId}:${selected.modelId}` : ""}
onChange={(event) => {
const [profileId, modelId] = event.target.value.split(":");
update(index, { profile_id: profileId, model_id: modelId });
}}
>
<option value="">{t("Choose a configured model")}</option>
{choices.map((choice) => (
<option
key={`${choice.profileId}:${choice.modelId}`}
value={`${choice.profileId}:${choice.modelId}`}
>
{choice.label}
</option>
))}
</select>
<button
type="button"
className="rounded p-1 disabled:opacity-30"
onClick={() => move(index, -1)}
disabled={index === 0}
aria-label={t("Move up")}
>
<ArrowUp className="h-3.5 w-3.5" />
</button>
<button
type="button"
className="rounded p-1 disabled:opacity-30"
onClick={() => move(index, 1)}
disabled={index === rows.length - 1}
aria-label={t("Move down")}
>
<ArrowDown className="h-3.5 w-3.5" />
</button>
<button
type="button"
className="rounded p-1 text-red-600 dark:text-red-400"
onClick={() => {
setRows((current) => current.filter((_, position) => position !== index));
setSaved(null);
}}
aria-label={t("Remove fallback")}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</li>
);
})}
</ul>
)}
<div className="mt-3 flex items-center gap-3">
<button
type="button"
className="rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] disabled:opacity-40"
onClick={() => void save()}
disabled={!dirty || saving}
>
{saving ? <Loader2 className="mr-1 inline h-3.5 w-3.5 animate-spin" /> : null}
{t("Save fallback chain")}
</button>
{saved && <span className="text-[11.5px] text-emerald-600">{saved}</span>}
{error && <span className="text-[11.5px] text-red-600 dark:text-red-300">{error}</span>}
<span className="ml-auto text-[11px] text-[var(--muted-foreground)]">
{t("Order matters · up to {{max}}", { max: MAX_FALLBACKS })}
</span>
</div>
</div>
);
}

View File

@@ -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 (
<div className="mb-6 rounded-xl border border-[var(--border)]/60 bg-[var(--card)] px-4 py-3 text-[12.5px] leading-relaxed">
<div className="font-medium">
{t("Fallback chain: {{count}} configured", { count: chain.length })}
</div>
<div className="mt-1 text-[var(--muted-foreground)]">
{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.",
)}
</div>
<ul className="mt-1.5 list-disc pl-5 text-[var(--muted-foreground)]">
{chain.map((entry) => (
<li key={`${entry.profile_id}:${entry.model_id}`}>
{entry.profile_id} / {entry.model_id}
</li>
))}
</ul>
</div>
);
}
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.",
)}
/>
<FallbackChainNotice />
<FallbackChainEditor />
<ModelsWorkspace page="llm" />
</div>
);

View File

@@ -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<string>();
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);
}

View File

@@ -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.",

View File

@@ -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 在现代浏览器中生效。",

View File

@@ -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);
});
});