PRINTFILM: AI short-video marketing and AI short-drama creation platform
feat(models): 增加后台模型启停并统一调用校验
yidd9863b5274c
diff --git a/admin/nginx.conf b/admin/nginx.confindex b82dba5..10f8f9e 100644--- a/admin/nginx.conf+++ b/admin/nginx.conf@@ -27,6 +27,11 @@ server {proxy_read_timeout 600s;}+ location = /index.html {+ root /usr/share/nginx/html;+ add_header Cache-Control "no-cache, no-store, must-revalidate" always;+ }+location / {root /usr/share/nginx/html;try_files $uri $uri/ /index.html;diff --git a/admin/package.json b/admin/package.jsonindex 19ba669..15a4c66 100644--- a/admin/package.json+++ b/admin/package.json@@ -7,6 +7,7 @@"dev": "vite","build": "tsc -b && vite build","lint": "oxlint",+ "test": "node --experimental-strip-types --test tests/*.test.mjs","preview": "vite preview"},"dependencies": {diff --git a/admin/src/api/types/settings.ts b/admin/src/api/types/settings.tsindex 3e0c98a..8573077 100644--- a/admin/src/api/types/settings.ts+++ b/admin/src/api/types/settings.ts@@ -121,6 +121,7 @@ export type AdminLogicalModel = {id: string;name: string;capability: "text" | "image" | "video" | "audio";+ strategy_id?: string | null;enabled: boolean;bindings: AdminLogicalModelBinding[];};diff --git a/admin/src/components/settings/RoutingSettingsPanel.tsx b/admin/src/components/settings/RoutingSettingsPanel.tsxindex 2d903b4..9145b35 100644--- a/admin/src/components/settings/RoutingSettingsPanel.tsx+++ b/admin/src/components/settings/RoutingSettingsPanel.tsx@@ -1,4 +1,5 @@import { Select } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";import { useCallback, useEffect, useState } from "react";import { Eye, EyeOff, ExternalLink } from "lucide-react";import { toast } from "sonner";@@ -14,12 +15,11 @@ import {allPresetChannelModels,CAPABILITY_LABELS,CAPABILITY_ORDER,- clampDefaultToPreset,- defaultPresetDefaults,detectDefaultRemaps,PRESET_MODELS,type ModelCapability,} from "@/lib/tokenfreeRecommendedModels";+import { enabledPresetModels, normalizeRoutingDefaults, routingModelSettings, setRoutingModelEnabled } from "@/lib/routingModels";import { cn } from "@/lib/utils";const TOKENFREE_CHANNEL_ID = "tokenfree";@@ -42,17 +42,7 @@ function buildReadiness(data: AdminRoutingSettings | null, hasKey: boolean) {] as const;}-function normalizeDefaults(raw: AdminRoutingSettings["default_models"] | undefined) {- const base = defaultPresetDefaults();- return {- text_model: clampDefaultToPreset("text", raw?.text_model || base.text_model),- image_model: clampDefaultToPreset("image", raw?.image_model || base.image_model),- video_model: clampDefaultToPreset("video", raw?.video_model || base.video_model),- audio_model: clampDefaultToPreset("audio", raw?.audio_model || base.audio_model),- };-}--// 开源版模型配置:固定 TokenFree + 四类预设下拉+// 模型启停与站点默认值共同保存,保留上游绑定与策略。export function RoutingSettingsPanel() {const [data, setData] = useState<AdminRoutingSettings | null>(null);const [apiKeyInput, setApiKeyInput] = useState("");@@ -72,10 +62,13 @@ export function RoutingSettingsPanel() {setLoading(true);try {const res = await api<AdminRoutingSettings>("/api/admin/settings/routing");- setDefaultRemaps(detectDefaultRemaps(res.default_models));+ const defaults = normalizeRoutingDefaults(res.default_models, res.logical_models);+ setDefaultRemaps(detectDefaultRemaps(res.default_models)+ .map((item) => ({ ...item, to: defaults[`${item.capability}_model`] }))+ .filter((item) => Boolean(item.to)));setData({...res,- default_models: normalizeDefaults(res.default_models),+ default_models: defaults,system_channels: res.system_channels.map((item) =>item.id === TOKENFREE_CHANNEL_ID? { ...item, models: allPresetChannelModels() }@@ -113,12 +106,11 @@ export function RoutingSettingsPanel() {function setDefaultModel(key: (typeof DEFAULT_KEYS)[number], value: string) {const cap = key.replace("_model", "") as ModelCapability;- const next = clampDefaultToPreset(cap, value);setData((prev) =>prev? {...prev,- default_models: { ...prev.default_models, [key]: next },+ default_models: { ...prev.default_models, [key]: enabledPresetModels(cap, prev.logical_models).find((model) => model.id === value)?.id ?? "" },}: prev,);@@ -128,7 +120,6 @@ export function RoutingSettingsPanel() {if (!data || saving || keyError || referenceErrorCount > 0) return;setSaving(true);try {- const defaults = normalizeDefaults(data.default_models);const res = await api<{ settings: AdminRoutingSettings }>("/api/admin/settings/routing", {method: "PATCH",body: JSON.stringify({@@ -145,13 +136,12 @@ export function RoutingSettingsPanel() {sort_order: 0,},],- default_models: defaults,- media_reference_limits: data.media_reference_limits,+ ...routingModelSettings(data),}),});setData({...res.settings,- default_models: normalizeDefaults(res.settings.default_models),+ default_models: normalizeRoutingDefaults(res.settings.default_models, res.settings.logical_models),});setDefaultRemaps([]);setApiKeyInput("");@@ -234,19 +224,41 @@ export function RoutingSettingsPanel() {</div></SettingsPanel>- <SettingsPanel title="默认生成模型" description="为每类任务选择站点默认模型。用户创作时仍可切换到其它预设模型。">+ <SettingsPanel title="模型使用与默认设置" description="开启允许用户使用的模型,再选择站点默认模型。保存后,停用模型不再用于新请求;已冻结路由的图、视频任务继续执行。"><div className="settings-field-grid settings-field-grid--2">{CAPABILITY_ORDER.map((cap) => {const key = `${cap}_model` as (typeof DEFAULT_KEYS)[number];- const options = PRESET_MODELS[cap];+ const options = enabledPresetModels(cap, data.logical_models);const hints: Record<ModelCapability, string> = { text: "用于脚本、摘要与分镜规划。", image: "用于角色、场景、道具等参考图生成。", video: "用于分镜视频生成。", audio: "用于角色配音;当前提供一款预设模型。" };return (- <LabeledControl key={key} label={`${CAPABILITY_LABELS[cap]}模型`} hint={hints[cap]} required>- <Select className="settings-select" value={data.default_models[key] ?? options[0]?.id ?? ""} required- aria-label={`${CAPABILITY_LABELS[cap]}默认模型`} onChange={(e) => setDefaultModel(key, e.target.value)}>- {options.map((row) => <option key={row.id} value={row.id}>{row.label}</option>)}- </Select>- </LabeledControl>+ <section key={cap} className="min-w-0 space-y-4 rounded-xl border border-[var(--admin-border)] p-4" aria-label={`${CAPABILITY_LABELS[cap]}模型使用设置`}>+ <div className="flex items-center justify-between gap-3">+ <h4 className="text-sm font-semibold">{CAPABILITY_LABELS[cap]}模型</h4>+ <span className="text-xs text-[var(--admin-muted)]">已启用 {options.length} / {PRESET_MODELS[cap].length}</span>+ </div>+ <p className="text-xs text-[var(--admin-muted)]">{hints[cap]}</p>+ <div className="space-y-2">+ {PRESET_MODELS[cap].map((row) => {+ const model = data.logical_models.find((item) => item.capability === cap && item.id === row.id);+ const enabled = Boolean(model?.enabled);+ return <div key={row.id} className="settings-toggle-row">+ <div className="min-w-0"><strong>{row.label}</strong><span className="block break-all">{row.id}</span></div>+ <div className="flex shrink-0 items-center gap-2">+ <span>{enabled ? "已启用" : "已停用"}</span>+ <Switch aria-label={`${row.label} 使用`} checked={enabled} disabled={!model}+ onCheckedChange={(value) => setData((prev) => prev ? setRoutingModelEnabled(prev, row.id, value) : prev)} />+ </div>+ </div>;+ })}+ </div>+ <LabeledControl label={`${CAPABILITY_LABELS[cap]}默认模型`} required={options.length > 0}+ hint={options.length === 0 ? "当前无可用模型,请开启模型后再使用该功能。" : "仅从已启用的模型中选择。"}>+ <Select className="settings-select" value={data.default_models[key]} required={options.length > 0} disabled={options.length === 0}+ aria-label={`${CAPABILITY_LABELS[cap]}默认模型`} onChange={(e) => setDefaultModel(key, e.target.value)}>+ {options.length === 0 ? <option value="">无可用模型</option> : options.map((row) => <option key={row.id} value={row.id}>{row.label}</option>)}+ </Select>+ </LabeledControl>+ </section>);})}</div>diff --git a/admin/src/lib/routingModels.ts b/admin/src/lib/routingModels.tsnew file mode 100644index 0000000..b6f74df--- /dev/null+++ b/admin/src/lib/routingModels.ts@@ -0,0 +1,35 @@+import type { AdminDefaultModels, AdminLogicalModel, AdminRoutingSettings } from "../api/types/settings.ts";+import { clampDefaultToPreset, PRESET_MODELS, type ModelCapability } from "./tokenfreeRecommendedModels.ts";++export function enabledPresetModels(capability: ModelCapability, models: readonly AdminLogicalModel[]) {+ return PRESET_MODELS[capability].filter((preset) => models.some((model) =>+ model.capability === capability && model.id === preset.id && model.enabled,+ ));+}++export function normalizeRoutingDefaults(raw: Partial<AdminDefaultModels> | undefined, models: readonly AdminLogicalModel[]): AdminDefaultModels {+ function defaultFor(capability: ModelCapability) {+ const options = enabledPresetModels(capability, models);+ const selected = clampDefaultToPreset(capability, raw?.[`${capability}_model`]);+ return options.find((model) => model.id === selected)?.id ?? options[0]?.id ?? "";+ }+ return {+ text_model: defaultFor("text"),+ image_model: defaultFor("image"),+ video_model: defaultFor("video"),+ audio_model: defaultFor("audio"),+ };+}++export function setRoutingModelEnabled(settings: AdminRoutingSettings, id: string, enabled: boolean): AdminRoutingSettings {+ const models = settings.logical_models.map((model) => model.id === id ? { ...model, enabled } : model);+ return { ...settings, logical_models: models, default_models: normalizeRoutingDefaults(settings.default_models, models) };+}++export function routingModelSettings(settings: AdminRoutingSettings) {+ return {+ logical_models: settings.logical_models,+ default_models: normalizeRoutingDefaults(settings.default_models, settings.logical_models),+ media_reference_limits: settings.media_reference_limits,+ };+}diff --git a/admin/tests/routing-models.test.mjs b/admin/tests/routing-models.test.mjsnew file mode 100644index 0000000..b7c1398--- /dev/null+++ b/admin/tests/routing-models.test.mjs@@ -0,0 +1,60 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { enabledPresetModels, normalizeRoutingDefaults, routingModelSettings, setRoutingModelEnabled } from '../src/lib/routingModels.ts'+import { CAPABILITY_ORDER, PRESET_MODELS } from '../src/lib/tokenfreeRecommendedModels.ts'++function settings() {+ return {+ system_channels: [],+ logical_models: CAPABILITY_ORDER.flatMap((capability) => PRESET_MODELS[capability].map(({ id, label }) => ({+ id, name: label, capability, strategy_id: `strategy-${id}`, enabled: true,+ bindings: [{ id: `binding-${id}`, channel_id: 'tokenfree', upstream_model: id, enabled: true, priority: 20, weight: 3 }],+ }))),+ default_models: Object.fromEntries(CAPABILITY_ORDER.map((capability) => [`${capability}_model`, PRESET_MODELS[capability][0].id])),+ media_reference_limits: { 'seedream-5.0-pro': { images: 9, videos: 0, audios: 0 } },+ validation_errors: [],+ }+}++test('停用当前默认模型后,只从启用的预设中选择下一个默认模型', () => {+ const original = settings()+ const updated = setRoutingModelEnabled(original, 'seedream-5.0-pro', false)+ assert.equal(updated.default_models.image_model, 'seedream-5.0')+ assert.deepEqual(enabledPresetModels('image', updated.logical_models).map(({ id }) => id), PRESET_MODELS.image.slice(1).map(({ id }) => id))+ assert.equal(updated.default_models.video_model, original.default_models.video_model)+ assert.equal(original.logical_models.find(({ id }) => id === 'seedream-5.0-pro').enabled, true)+})++test('停用非默认模型时保留当前默认模型', () => {+ const updated = setRoutingModelEnabled(settings(), 'seedream-5.0-flash', false)+ assert.equal(updated.default_models.image_model, 'seedream-5.0-pro')+})++test('某类模型全部停用后默认值为空,加载与保存都不会重新启用', () => {+ let updated = settings()+ for (const { id } of PRESET_MODELS.video) updated = setRoutingModelEnabled(updated, id, false)+ assert.equal(updated.default_models.video_model, '')+ assert.deepEqual(enabledPresetModels('video', updated.logical_models), [])+ assert.equal(normalizeRoutingDefaults({ ...updated.default_models, video_model: 'seedance-2.5' }, updated.logical_models).video_model, '')+ const payload = routingModelSettings(updated)+ assert.equal(payload.default_models.video_model, '')+ assert.ok(payload.logical_models.filter(({ capability }) => capability === 'video').every(({ enabled }) => !enabled))+})++test('重新启用模型后可作为默认模型,保存保留绑定、策略与参考上限', () => {+ const original = settings()+ const disabled = setRoutingModelEnabled(original, PRESET_MODELS.audio[0].id, false)+ const updated = setRoutingModelEnabled(disabled, PRESET_MODELS.audio[0].id, true)+ assert.equal(updated.default_models.audio_model, PRESET_MODELS.audio[0].id)+ const payload = routingModelSettings(updated)+ assert.deepEqual(payload.logical_models, original.logical_models)+ assert.deepEqual(payload.media_reference_limits, original.media_reference_limits)+})++test('历史别名可映射到启用的预设,但不会选中已停用模型', () => {+ const original = settings()+ const defaults = { ...original.default_models, image_model: 'seedream-5-0-flash' }+ assert.equal(normalizeRoutingDefaults(defaults, original.logical_models).image_model, 'seedream-5.0-flash')+ const disabled = setRoutingModelEnabled(original, 'seedream-5.0-flash', false)+ assert.equal(normalizeRoutingDefaults(defaults, disabled.logical_models).image_model, 'seedream-5.0-pro')+})diff --git a/backend/app/services/ark.py b/backend/app/services/ark.pyindex ab27b86..3b5eecf 100644--- a/backend/app/services/ark.py+++ b/backend/app/services/ark.py@@ -564,11 +564,15 @@ class ArkGateway:# 按逻辑路由解析 ARK 渠道凭证def _resolve_ark_route(self, capability: str, model_id: str | None) -> ResolvedModelRoute | None:operation = current_operation.get()- if current_snapshot.get():+ snapshot = current_snapshot.get()+ if snapshot and (capability in {"image", "video"} or any(+ item["capability"] == capability for item in snapshot.get("items", [])+ )):if not operation or operation["capability"] != capability:operation = operation_for(capability, model=model_id)if operation:return restore_route(operation["route"])+ resolve_upstream_model(capability, model_id)logical_id = resolve_logical_model_id(capability, model_id)route = resolve_logical_model(capability, logical_id)if route is None:@@ -701,6 +705,7 @@ class ArkGateway:allow_source_names: bool = False,) -> StoryboardResult:if self.mock:+ resolve_upstream_model("text", None)return await asyncio.to_thread(self._mock_storyboard,source_text,@@ -931,6 +936,7 @@ class ArkGateway:ark_model = resolvedif self.mock:+ self._resolve_ark_route("image", ark_model)local = await asyncio.to_thread(self._write_mock_image, prompt, size)# _write_mock_image returns /static/...; publish to OSS when enabledpath = storage.local_path_from_url(local)@@ -1845,12 +1851,14 @@ class ArkGateway:model: str | None = None,) -> bool:"""TokenFree 上 Qwen-TTS 的 /audio/speech 未实现,改走 Omni/Gemini chat。"""- base = (self.settings.ark_base_url or "").rstrip("/")- key = (self.settings.ark_api_key or "").strip()+ requested = (model or self._resolved_audio_model()).strip()+ route = self._resolve_ark_route("audio", requested)+ base = (route.base_url if route else self.settings.ark_base_url or "").rstrip("/")+ key = (route.api_key if route else self.settings.ark_api_key or "").strip()if not base or (not key and not getattr(self.settings, "local_media_mock", False)):return Falsemodel_id = tokenfree_tts_chat_model(- resolve_tokenfree_tts_model((model or self._resolved_audio_model()).strip())+ resolve_tokenfree_tts_model(route.upstream_model if route else requested))voice = tokenfree_speech_voice(voice, model_id)if tokenfree_tts_uses_chat_audio(model_id):@@ -1858,7 +1866,7 @@ class ArkGateway:async with httpx.AsyncClient(timeout=120.0) as client:resp = await self._request_media(client, "POST",f"{base}/audio/speech",- headers=self._headers(),+ headers=self._route_headers(route),json={"model": model_id,"input": text,@@ -1887,7 +1895,9 @@ class ArkGateway:model: str,) -> bool:"""Gemini 非流式 chat 出音频;Qwen-Omni 必须 SSE 流式。"""- base = (self.settings.ark_base_url or "").rstrip("/")+ route = self._resolve_ark_route("audio", model)+ model = tokenfree_tts_chat_model(resolve_tokenfree_tts_model(route.upstream_model if route else model))+ base = (route.base_url if route else self.settings.ark_base_url or "").rstrip("/")if not base:return Falseomni = tokenfree_tts_uses_omni_stream(model)@@ -1902,7 +1912,7 @@ class ArkGateway:})async with httpx.AsyncClient(timeout=120.0) as client:- resp = await self._request_media(client, "POST", f"{base}/chat/completions", headers=self._headers(), json=body)+ resp = await self._request_media(client, "POST", f"{base}/chat/completions", headers=self._route_headers(route), json=body)if resp.status_code >= 400:logger.warning("OpenAI chat-audio HTTP %s model=%s: %s",@@ -1944,6 +1954,7 @@ class ArkGateway:"""整片/单镜配音:TokenFree 多 TTS → edge-tts;失败则抛错,不写静音。"""if result_metadata is not None:result_metadata.clear()+ audio_model = self._resolved_audio_model()voice_map = {"narrator_calm": "zh_female_cancan_uranus_bigtts","warm_storyteller": "zh_female_tianmeixiaoyuan_uranus_bigtts",@@ -1976,10 +1987,12 @@ class ArkGateway:return Nonereturn storage.publish_local(dest)- audio_model = self._resolved_audio_model()-# TokenFree:默认模型 + Gemini / ElevenLabs / Qwen 其它 TTS 依次试for model_id in iter_tokenfree_tts_models(audio_model):+ try:+ resolve_upstream_model("audio", model_id)+ except ValueError:+ continuetry:ok = await self._tts_openai_speech(clean, speaker, dest, model=model_id)if ok:@@ -2349,6 +2362,7 @@ class ArkGateway:topic = (topic or "").strip() or "人工智能如何改变日常生活"mode = "script" if mode == "script" else "theme"if self.mock:+ resolve_upstream_model("text", None)return self._mock_expand_content(topic, mode)if mode == "script":diff --git a/backend/app/services/llm_client.py b/backend/app/services/llm_client.pyindex 224f982..0a63ae0 100644--- a/backend/app/services/llm_client.py+++ b/backend/app/services/llm_client.py@@ -9,7 +9,11 @@ from typing import Anyimport httpxfrom app.config import get_settings-from app.services.logical_model_router import resolve_logical_model, resolve_logical_model_id+from app.services.logical_model_router import (+ resolve_logical_model,+ resolve_logical_model_id,+ resolve_upstream_model,+)from app.services.tasks.upstream import observed_requestlogger = logging.getLogger(__name__)@@ -74,6 +78,11 @@ async def chat_completions(response_format: dict[str, Any] | None = None,) -> str:settings = get_settings()+ # Apply managed model switches before falling back to environment credentials.+ try:+ resolve_upstream_model("text", None)+ except ValueError as exc:+ raise LlmUnavailableError(str(exc)) from exclogical_id = resolve_logical_model_id("text", None)route = resolve_logical_model("text", logical_id)if route:diff --git a/backend/app/services/logical_model_router.py b/backend/app/services/logical_model_router.pyindex 202fbe6..f19758e 100644--- a/backend/app/services/logical_model_router.py+++ b/backend/app/services/logical_model_router.py@@ -9,6 +9,10 @@ from app.services.model_routing_config import (infer_model_capability,)from app.services.model_settings import get_routing_snapshot+from app.services.model_availability import (+ canonical_model_key, direct_binding_enabled, has_managed_models,+ is_managed_model, is_model_enabled,+)# 解析某逻辑模型的可用路由@@ -19,6 +23,8 @@ def _routes_for_logical_model(*,preferred_channel_id: str = "",) -> list[ResolvedModelRoute]:+ if not logical.enabled:+ return []bindings = sorted([binding for binding in logical.bindings if binding.enabled],key=lambda binding: (@@ -53,6 +59,10 @@ def resolve_logical_model_candidates(requested = (requested_model_id or "").strip()if not requested:requested = _default_model_id(snapshot.default_models, capability)+ if not requested and has_managed_models(capability, snapshot.logical_models):+ return []+ if requested and not is_model_enabled(capability, requested, snapshot.logical_models):+ return []if requested:logical = next(@@ -61,7 +71,7 @@ def resolve_logical_model_candidates(for model in snapshot.logical_modelsif model.enabledand model.capability == capability- and model.id.lower() == requested.lower()+ and canonical_model_key(capability, model.id) == canonical_model_key(capability, requested)),None,)@@ -74,6 +84,21 @@ def resolve_logical_model_candidates()if routes:return routes+ else:+ # Custom logical names may bind a known upstream alias (for example Qwen/Omni).+ key = canonical_model_key(capability, requested)+ routes = []+ for model in snapshot.logical_models:+ if not model.enabled or model.capability != capability:+ continue+ if not any(binding.enabled and canonical_model_key(capability, binding.upstream_model) == key+ for binding in model.bindings):+ continue+ routes.extend(route for route in _routes_for_logical_model(+ model, capability, snapshot.channels, preferred_channel_id=preferred_channel_id,+ ) if canonical_model_key(capability, route.upstream_model) == key)+ if routes:+ return routes# 用户点名的上游模型在渠道清单里时,不要静默换成同能力的另一个逻辑模型if requested:@@ -81,11 +106,15 @@ def resolve_logical_model_candidates(capability,requested,snapshot.channels,+ logical_models=snapshot.logical_models,preferred_channel_id=preferred_channel_id,)if direct:return direct+ if requested and is_managed_model(capability, requested, snapshot.logical_models):+ return []+# 默认/请求模型失效时,回落到同能力第一个可解析模型(DeepSeek / Kimi / 其它兼容均可)if capability in {"image", "video"}:# Media requests never switch model, including when the requested route is unavailable.@@ -113,6 +142,7 @@ def resolve_logical_model_candidates(capability,requested,snapshot.channels,+ logical_models=snapshot.logical_models,preferred_channel_id=preferred_channel_id,)@@ -122,6 +152,7 @@ def _direct_channel_routes(requested: str,channels: list[SystemModelChannel],*,+ logical_models: list[LogicalModel] | None = None,preferred_channel_id: str = "",) -> list[ResolvedModelRoute]:"""按渠道 models 清单精确匹配用户点名的上游模型。"""@@ -133,6 +164,8 @@ def _direct_channel_routes(]routes: list[ResolvedModelRoute] = []for channel in ordered:+ if not direct_binding_enabled(capability, requested, channel.id, logical_models or []):+ continueif not channel.enabled or not channel_connection_ready(channel):continueif not channel_supports_model(channel, requested):@@ -179,11 +212,26 @@ def resolve_upstream_model(capability: LogicalModelCapability,model_id: str | None,) -> str:+ if capability in {"image", "video"}:+ from app.services.media_models.runtime import current_snapshot, operation_for, restore_route++ if current_snapshot.get():+ operation = operation_for(capability, model=model_id)+ if operation:+ return restore_route(operation["route"]).upstream_model+ snapshot = get_routing_snapshot()+ if model_id and not is_model_enabled(capability, model_id, snapshot.logical_models):+ raise ValueError(f"model: {model_id} 已停用")logical_id = resolve_logical_model_id(capability, model_id)+ if not logical_id and has_managed_models(capability, snapshot.logical_models):+ raise ValueError(f"model: 未配置可用的默认{capability}模型")+ if logical_id and not is_model_enabled(capability, logical_id, snapshot.logical_models):+ raise ValueError(f"model: {logical_id} 已停用")route = resolve_logical_model(capability, logical_id)if route:return route.upstream_model- snapshot = get_routing_snapshot()+ if is_managed_model(capability, logical_id, snapshot.logical_models):+ raise ValueError(f"model: {logical_id} 没有启用的可用渠道绑定")fallback = _legacy_upstream_fallback(capability, model_id, snapshot.default_models)if fallback:return fallback@@ -245,8 +293,8 @@ def _capability_aliases(capability: LogicalModelCapability) -> dict[str, str]:if capability == "image":# 旧 UI 别名 → TokenFree 价目真实 id(逻辑模型与上游同名,不做换绑)return {- "seedream-5.0": "seedream-5-0-pro",- "seedream-5": "seedream-5-0-pro",+ "seedream-5.0": "seedream-5.0",+ "seedream-5": "seedream-5.0","5.0": "seedream-5-0-pro","seedream-4.5": "seedream-4-5","seedream-4": "seedream-4-5",@@ -281,9 +329,12 @@ def _legacy_upstream_fallback(raw = (model_id or "").strip()if capability == "image":mid = raw.lower()- if mid in {"", "seedream-5.0", "seedream-5", "5.0"}:+ if mid in {"", "5.0"}:route = resolve_logical_model("image", defaults.image_model or "seedream-5-0-pro")return route.upstream_model if route else settings.model_image+ if mid in {"seedream-5.0", "seedream-5"}:+ route = resolve_logical_model("image", "seedream-5.0")+ return route.upstream_model if route else "seedream-5.0"if mid in {"seedream-4.5", "seedream-4", "4.5"}:route = resolve_logical_model("image", "seedream-4-5")return route.upstream_model if route else ((settings.model_image_45 or "").strip() or settings.model_image)diff --git a/backend/app/services/media_catalog.py b/backend/app/services/media_catalog.pyindex 28b38f0..7106323 100644--- a/backend/app/services/media_catalog.py+++ b/backend/app/services/media_catalog.py@@ -7,6 +7,7 @@ from typing import Anyfrom app.config import get_settingsfrom app.schemas_routing import DefaultModels, LogicalModel, LogicalModelCapability, SystemModelChannelfrom app.services.model_routing_config import infer_model_capability, normalize_model_name+from app.services.model_availability import has_managed_models, is_model_enableddef _row(@@ -94,6 +95,10 @@ def build_media_catalog(default_image = _canon((defaults.image_model or "").strip())default_video = _canon((defaults.video_model or "").strip())+ if not is_model_enabled("image", default_image, logical_models):+ default_image = ""+ if not is_model_enabled("video", default_video, logical_models):+ default_video = ""def _append(*,@@ -102,7 +107,7 @@ def build_media_catalog(capability: LogicalModelCapability,) -> None:mid = _canon(model_id)- if not mid:+ if not mid or not is_model_enabled(capability, mid, logical_models):returnkey = normalize_model_name(mid)if capability == "image":@@ -159,9 +164,9 @@ def build_media_catalog(if cap in {"image", "video"}:_append(model_id=mid, label=mid, capability=cap) # type: ignore[arg-type]- if not default_image:+ if not default_image and not has_managed_models("image", logical_models):default_image = images[0]["id"] if images else _canon((fallback_image or "").strip())- if not default_video:+ if not default_video and not has_managed_models("video", logical_models):default_video = videos[0]["id"] if videos else _canon((fallback_video or "").strip())def _ensure_default_in_list(@@ -242,6 +247,9 @@ def is_valid_project_media_model(model_id: str | None, capability: LogicalModelCmid = (model_id or "").strip()if not mid:return True+ from app.services.model_settings import get_routing_snapshot+ if not is_model_enabled(capability, mid, get_routing_snapshot().logical_models):+ return Falsefrom app.services.logical_model_router import resolve_logical_model_candidatescat = catalog_payload()diff --git a/backend/app/services/media_models/catalog.py b/backend/app/services/media_models/catalog.pyindex deea6ff..c4e48be 100644--- a/backend/app/services/media_models/catalog.py+++ b/backend/app/services/media_models/catalog.py@@ -4,6 +4,9 @@ from .runtime import pin_routeasync def priced_catalog(db, catalog: dict) -> dict:from app.config import get_settings+ from app.services.model_availability import is_model_enabled+ from app.services.model_settings import get_routing_snapshot+ models = get_routing_snapshot().logical_modelscatalog["generation_defaults"] = {"image_resolution": "2K", "video_resolution": get_settings().ark_video_resolution}book = await active_book(db)catalog["price_version"] = book["version"] if book else None@@ -11,6 +14,8 @@ async def priced_catalog(db, catalog: dict) -> dict:for key in ("image_models", "video_models"):rows = []for row in catalog[key]:+ if not is_model_enabled("image" if key == "image_models" else "video", row["id"], models):+ continuetry:strategy = resolve_strategy(row["id"])except ValueError:diff --git a/backend/app/services/media_models/planning.py b/backend/app/services/media_models/planning.pyindex 48335f3..e2103c1 100644--- a/backend/app/services/media_models/planning.py+++ b/backend/app/services/media_models/planning.py@@ -9,6 +9,7 @@ from sqlalchemy.orm import selectinloadfrom app.config import get_settingsfrom app.models import Project+from app.services.logical_model_router import resolve_logical_model_id, resolve_upstream_modelfrom .prices import active_book, expected_price_version, resolve_strategyfrom .runtime import pin_routefrom . import MediaValidationError, get_strategy@@ -57,7 +58,11 @@ async def plan_items(db, task) -> list[dict]:def add(capability, params=None, *, model=None, target=None, shot_no=None, optional=False):if model is not None and not isinstance(model, str):raise MediaValidationError("model", "必须是模型 ID 字符串")- model = model or (settings.model_image if capability == "image" else settings.model_video)+ if not model:+ resolve_upstream_model(capability, None)+ model = resolve_logical_model_id(capability, None) or (+ settings.model_image if capability == "image" else settings.model_video+ )strategy = resolve_strategy(model)if strategy.capability != capability:raise MediaValidationError("model", "模型类型与生成任务不匹配")@@ -85,13 +90,13 @@ async def plan_items(db, task) -> list[dict]:if phase == "assets" and (kind != "project_pipeline" or not shot_image_ready(shot)):add("image", {"size": _image_size_for(project) or settings.ark_image_size,"aspect_ratio": _project_output_ratio(project) or "1:1"},- model=project.image_model or settings.model_image, target=shot.id, shot_no=shot.shot_no)+ model=project.image_model, target=shot.id, shot_no=shot.shot_no)if phase == "videos" and (kind != "project_pipeline" or not shot_video_ready(shot)):from app.services.seedance_resolutions import project_video_resolutionresolution = project_video_resolution(project, settings)add("video", {"duration": int(shot.duration or 5), "resolution": resolution,"aspect_ratio": _project_output_ratio(project) or "9:16"},- model=project.video_model or settings.model_video, target=shot.id, shot_no=shot.shot_no)+ model=project.video_model, target=shot.id, shot_no=shot.shot_no)return itemsif kind in {"asset_image", "tool_image"}:model = p.get("model_id") or p.get("model") or generation.get("model")diff --git a/backend/app/services/media_models/runtime.py b/backend/app/services/media_models/runtime.pyindex c2a4c0f..7ba2b67 100644--- a/backend/app/services/media_models/runtime.py+++ b/backend/app/services/media_models/runtime.py@@ -7,8 +7,9 @@ from urllib.parse import urlsplitfrom app.config import get_settingsfrom app.schemas_routing import ResolvedModelRoute-from app.services.logical_model_router import resolve_logical_model+from app.services.logical_model_router import resolve_logical_model, resolve_logical_model_id, resolve_upstream_modelfrom app.services.model_settings import get_routing_snapshot+from app.services.model_availability import is_managed_model, is_model_enabledfrom .prices import resolve_strategyfrom . import get_strategy@@ -25,11 +26,12 @@ def _public_route(route: dict) -> dict:def pin_route(capability: str, model_id: str) -> dict:settings = get_settings()- strategy = resolve_strategy(model_id)snapshot = get_routing_snapshot()- logical = next((model for model in getattr(snapshot, "logical_models", []) if model.id.lower() == model_id.lower()), None)- if logical is not None and not logical.enabled:+ models = getattr(snapshot, "logical_models", [])+ if not is_model_enabled(capability, model_id, models):raise ValueError(f"model: {model_id} 已停用")+ strategy = resolve_strategy(model_id)+ logical = next((model for model in getattr(snapshot, "logical_models", []) if model.id.lower() == model_id.lower()), None)route = resolve_logical_model(capability, model_id)if route is None and logical is None and model_id != strategy.model_id:route = resolve_logical_model(capability, strategy.model_id)@@ -37,6 +39,8 @@ def pin_route(capability: str, model_id: str) -> dict:if get_strategy(route.upstream_model).model_id != strategy.model_id:raise ValueError("route: 上游绑定与所选模型策略不匹配")return _public_route(route.model_dump(exclude={"api_key"}))+ if is_managed_model(capability, model_id, models):+ raise ValueError(f"route: {model_id} 没有启用的可用渠道绑定")if snapshot.channels and not (settings.ark_mock or settings.local_media_mock):raise ValueError(f"route: {model_id} 没有可用渠道,不会自动切换模型")return _public_route({"capability": capability, "logical_model_id": model_id,@@ -90,7 +94,11 @@ def execution_params(capability: str, params: dict, *, target: int | None = Nonevalidated = strategy.normalize_and_validate(merged)current_operation.set(operation)return strategy, validated, restore_route(operation["route"])- strategy = resolve_strategy(model or (get_settings().model_image if capability == "image" else get_settings().model_video))+ resolve_upstream_model(capability, model)+ selected = model or resolve_logical_model_id(capability, None) or (+ get_settings().model_image if capability == "image" else get_settings().model_video+ )+ strategy = resolve_strategy(selected)validated = strategy.normalize_and_validate(params)return strategy, validated, Nonediff --git a/backend/app/services/model_availability.py b/backend/app/services/model_availability.pynew file mode 100644index 0000000..1f32f9a--- /dev/null+++ b/backend/app/services/model_availability.py@@ -0,0 +1,78 @@+"""Shared model switches for new requests; immutable task routes are unaffected."""++from collections.abc import Sequence++from app.schemas_routing import LogicalModel, LogicalModelCapability+++def canonical_model_key(capability: LogicalModelCapability, model_id: str | None) -> str:+ # Imports stay local: presets and strategy registration also use routing helpers.+ from app.services.media_model_presets import resolve_preset_alias++ value = resolve_preset_alias(model_id)+ if capability == "audio" and value:+ from app.services.tokenfree_audio import resolve_tokenfree_tts_model, tokenfree_tts_chat_model++ value = tokenfree_tts_chat_model(resolve_tokenfree_tts_model(value))+ if capability in {"image", "video"} and value:+ from app.services.media_models import get_strategy++ try:+ strategy = get_strategy(value)+ if strategy.capability == capability:+ value = strategy.model_id+ except ValueError:+ pass+ return "".join(value.split()).lower()+++def has_managed_models(+ capability: LogicalModelCapability, logical_models: Sequence[LogicalModel],+) -> bool:+ return any(model.capability == capability for model in logical_models)+++def _matching_models(+ capability: LogicalModelCapability, model_id: str | None,+ logical_models: Sequence[LogicalModel],+) -> list[LogicalModel]:+ key = canonical_model_key(capability, model_id)+ if not key:+ return []+ models = [model for model in logical_models if model.capability == capability]+ direct = [model for model in models if canonical_model_key(capability, model.id) == key]+ if direct:+ return direct+ return [model for model in models if any(+ canonical_model_key(capability, binding.upstream_model) == key for binding in model.bindings+ )]+++def is_managed_model(+ capability: LogicalModelCapability, model_id: str | None,+ logical_models: Sequence[LogicalModel],+) -> bool:+ return bool(_matching_models(capability, model_id, logical_models))+++def is_model_enabled(+ capability: LogicalModelCapability, model_id: str | None,+ logical_models: Sequence[LogicalModel],+) -> bool:+ """Keep unmanaged custom names compatible; explicit switches cover their aliases."""+ matches = _matching_models(capability, model_id, logical_models)+ return not matches or all(model.enabled for model in matches)+++def direct_binding_enabled(+ capability: LogicalModelCapability, model_id: str, channel_id: str,+ logical_models: Sequence[LogicalModel],+) -> bool:+ """A raw upstream request must not bypass a managed model's channel bindings."""+ matches = _matching_models(capability, model_id, logical_models)+ if not matches:+ return True+ key = canonical_model_key(capability, model_id)+ return any(model.enabled and binding.enabled and binding.channel_id == channel_id+ and canonical_model_key(capability, binding.upstream_model) == key+ for model in matches for binding in model.bindings)diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.pyindex 9e95302..9353735 100644--- a/backend/app/services/model_settings.py+++ b/backend/app/services/model_settings.py@@ -226,8 +226,8 @@ def _merge_friendly_alias_models(# TokenFree 价目真实 id(兼容旧前端别名 → 同名逻辑模型,不做换绑)_TOKENFREE_IMAGE_IDS: dict[str, str] = {- "seedream-5.0": "seedream-5-0-pro",- "seedream-5": "seedream-5-0-pro",+ "seedream-5.0": "seedream-5.0",+ "seedream-5": "seedream-5.0","5.0": "seedream-5-0-pro","seedream-4.5": "seedream-4-5","seedream-4": "seedream-4-5",@@ -828,15 +828,8 @@ async def patch_admin_routing_settings(update={"image_model": clamp_default_to_preset("image", image_default)})defaults = normalize_default_models(defaults, logical_models, channels_after)- # normalize 可能清空不可解析项;再次钳回预设- defaults = defaults.model_copy(- update={- "text_model": clamp_default_to_preset("text", defaults.text_model),- "image_model": clamp_default_to_preset("image", defaults.image_model),- "video_model": clamp_default_to_preset("video", defaults.video_model),- "audio_model": clamp_default_to_preset("audio", defaults.audio_model),- }- )+ # An empty default means this capability has no enabled route. Keep it empty+ # instead of reintroducing a disabled preset when every model is switched off.errors = model_routing_validation_errors(logical_models, channels_after, defaults)if errors:diff --git a/backend/tests/test_llm_model_availability.py b/backend/tests/test_llm_model_availability.pynew file mode 100644index 0000000..f382e79--- /dev/null+++ b/backend/tests/test_llm_model_availability.py@@ -0,0 +1,79 @@+"""Managed text model switches must also block legacy environment requests."""++import json++import httpx+import pytest++from app.config import Settings+from app.schemas_routing import DefaultModels, LogicalModel, LogicalModelBinding, SystemModelChannel+from app.services import llm_client+from app.services.model_settings import RoutingSnapshot+++def text_client(monkeypatch):+ settings = Settings(_env_file=None, debug=False, openai_api_key="environment-key",+ openai_base_url="https://environment.test/v1", model_llm="kimi-k2.6")+ monkeypatch.setattr("app.config.get_settings", lambda: settings)+ monkeypatch.setattr(llm_client, "get_settings", lambda: settings)+ requests = []++ def respond(request):+ requests.append(request)+ return httpx.Response(200, json={"choices": [{"message": {"content": "model response"}}]})++ client_type = httpx.AsyncClient+ monkeypatch.setattr(llm_client.httpx, "AsyncClient", lambda **kwargs: client_type(+ transport=httpx.MockTransport(respond), **kwargs))++ def configure(*, managed=True, enabled=True, binding_enabled=True, default=True):+ channel = SystemModelChannel(id="alpha", name="Alpha", base_url="https://channel.test/v1",+ api_key="channel-key", has_api_key=True, models=["kimi-k2.6"])+ model = LogicalModel(id="kimi-k2.6", capability="text", enabled=enabled, bindings=[+ LogicalModelBinding(channel_id=channel.id, upstream_model="kimi-k2.6", enabled=binding_enabled),+ ])+ snapshot = RoutingSnapshot(channels=[channel] if managed else [],+ logical_models=[model] if managed else [],+ default_models=DefaultModels(text_model=model.id if managed and default else ""))+ monkeypatch.setattr("app.services.model_settings._routing_snapshot", snapshot)++ return configure, requests++[email protected]("options", [+ {"enabled": False},+ {"default": False},+ {"binding_enabled": False},+], ids=["disabled-model", "empty-managed-default", "disabled-bindings"])+async def test_managed_text_unavailable_never_uses_environment_credentials(text_client, options):+ configure, requests = text_client+ configure(**options)++ with pytest.raises(llm_client.LlmUnavailableError):+ await llm_client.chat_completions("system", "user")++ assert requests == []+++async def test_unmanaged_text_keeps_environment_compatibility(text_client):+ configure, requests = text_client+ configure(managed=False)++ assert await llm_client.chat_completions("system", "user") == "model response"++ assert len(requests) == 1+ assert str(requests[0].url) == "https://environment.test/v1/chat/completions"+ assert requests[0].headers["Authorization"] == "Bearer environment-key"+ assert json.loads(requests[0].content)["model"] == "kimi-k2.6"+++async def test_enabled_managed_text_uses_channel_credentials(text_client):+ configure, requests = text_client+ configure()++ assert await llm_client.chat_completions("system", "user") == "model response"++ assert len(requests) == 1+ assert str(requests[0].url) == "https://channel.test/v1/chat/completions"+ assert requests[0].headers["Authorization"] == "Bearer channel-key"diff --git a/backend/tests/test_model_availability.py b/backend/tests/test_model_availability.pynew file mode 100644index 0000000..af6a001--- /dev/null+++ b/backend/tests/test_model_availability.py@@ -0,0 +1,357 @@+"""Model switches must apply to catalogs and every new-call routing fallback."""++from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from app.config import Settings+from app.schemas_routing import DefaultModels, LogicalModel, LogicalModelBinding, SystemModelChannel+from app.services.logical_model_router import resolve_logical_model_candidates, resolve_upstream_model+from app.services.media_catalog import build_media_catalog, is_valid_project_media_model+from app.services.media_models.catalog import priced_catalog+from app.services.media_models.runtime import pin_route, restore_route+from app.services.model_settings import RoutingSnapshot+++MODELS = {"text": "kimi-k2.6", "image": "seedream-5.0-pro",+ "video": "seedance-2.5", "audio": "qwen-tts-2025-05-22"}+++def routing(monkeypatch):+ settings = Settings(_env_file=None, debug=False, ark_mock=False, local_media_mock=False)+ monkeypatch.setattr("app.config.get_settings", lambda: settings)+ monkeypatch.setattr("app.services.media_models.runtime.get_settings", lambda: settings)+ monkeypatch.setattr("app.services.media_models.planning.get_settings", lambda: settings)+ monkeypatch.setattr("app.services.media_catalog.get_settings", lambda: settings)+ from app.services.media_models.runtime import current_operation, current_snapshot+ snapshot_token = current_snapshot.set(None)+ operation_token = current_operation.set(None)++ def configure(capability="image", *, enabled=True, binding_enabled=True, default=True):+ model_id = MODELS[capability]+ channel = SystemModelChannel(id="alpha", name="Alpha", base_url="https://alpha.test/v1",+ api_key="test-key", has_api_key=True, models=[model_id])+ model = LogicalModel(id=model_id, capability=capability, enabled=enabled,+ bindings=[LogicalModelBinding(channel_id=channel.id, upstream_model=model_id, enabled=binding_enabled)])+ defaults = DefaultModels(**{f"{capability}_model": model_id if default else ""})+ snapshot = RoutingSnapshot(channels=[channel], logical_models=[model], default_models=defaults)+ monkeypatch.setattr("app.services.model_settings._routing_snapshot", snapshot)+ return snapshot++ yield configure+ current_operation.reset(operation_token)+ current_snapshot.reset(snapshot_token)++[email protected]("capability", MODELS)+def test_disabled_model_cannot_use_explicit_or_default_direct_channel_fallback(routing, capability):+ snapshot = routing(capability, enabled=False)+ model_id = MODELS[capability]+ assert resolve_logical_model_candidates(capability, model_id) == []+ assert resolve_logical_model_candidates(capability, "") == []+ with pytest.raises(ValueError):+ resolve_upstream_model(capability, model_id)+ assert snapshot.channels[0].enabled is True++[email protected]("capability,alias", [+ ("image", " seedream-5-0-pro "), ("video", "SEEDANCE-2-5"),+ ("video", "doubao-seedance-2-5-260628"),+])+def test_disabled_media_alias_cannot_be_admitted(routing, capability, alias):+ routing(capability, enabled=False)+ with pytest.raises(ValueError):+ pin_route(capability, alias)+ assert is_valid_project_media_model(alias, capability) is False++[email protected]("capability", MODELS)+def test_disabled_binding_cannot_be_replaced_by_direct_or_environment_fallback(routing, capability):+ routing(capability, binding_enabled=False)+ assert resolve_logical_model_candidates(capability, MODELS[capability]) == []+ with pytest.raises(ValueError):+ resolve_upstream_model(capability, MODELS[capability])++[email protected]("capability", MODELS)+def test_managed_capability_with_empty_default_cannot_reactivate_environment_model(routing, capability):+ routing(capability, enabled=False, default=False)+ assert resolve_logical_model_candidates(capability, "") == []+ with pytest.raises(ValueError):+ resolve_upstream_model(capability, None)+++def test_unmanaged_custom_model_keeps_legacy_direct_routing(routing):+ snapshot = routing(enabled=False)+ snapshot.channels[0].models.append("custom-image-model")+ candidates = resolve_logical_model_candidates("image", "custom-image-model")+ assert [route.upstream_model for route in candidates] == ["custom-image-model"]+ assert resolve_upstream_model("image", "custom-image-model") == "custom-image-model"+++def test_raw_upstream_request_respects_binding_switch_on_each_channel(routing):+ snapshot = routing()+ alpha = snapshot.channels[0]+ alpha.models = ["custom-image-model"]+ beta = alpha.model_copy(update={"id": "beta", "name": "Beta"})+ snapshot.channels.append(beta)+ snapshot.logical_models = [LogicalModel(id="friendly-image", capability="image", bindings=[+ LogicalModelBinding(channel_id="alpha", upstream_model="custom-image-model", enabled=False),+ LogicalModelBinding(channel_id="beta", upstream_model="custom-image-model", enabled=True),+ ])]+ candidates = resolve_logical_model_candidates("image", "custom-image-model")+ assert [route.channel_id for route in candidates] == ["beta"]++[email protected]("capability,bucket", [("image", "image_models"), ("video", "video_models")])+def test_catalog_presets_channels_and_default_cannot_reinsert_disabled_model(routing, capability, bucket):+ snapshot = routing(capability, enabled=False)+ result = build_media_catalog(logical_models=snapshot.logical_models, channels=snapshot.channels,+ defaults=snapshot.default_models)+ assert MODELS[capability] not in {row["id"] for row in result[bucket]}+ assert result["defaults"][f"{capability}_model"] == ""+++async def test_priced_catalog_also_excludes_disabled_rows(routing, monkeypatch):+ routing("image", enabled=False)+ monkeypatch.setattr("app.services.media_models.catalog.active_book", AsyncMock(return_value=None))+ result = await priced_catalog(SimpleNamespace(), {+ "image_models": [{"id": MODELS["image"]}], "video_models": [],+ })+ assert result["image_models"] == []++[email protected]("logical_enabled,binding_enabled", [(False, True), (True, False)])+def test_frozen_route_continues_when_only_model_or_binding_is_disabled(+ routing, logical_enabled, binding_enabled,+):+ snapshot = routing("video", enabled=logical_enabled, binding_enabled=binding_enabled)+ saved = {"capability": "video", "logical_model_id": MODELS["video"],+ "upstream_model": MODELS["video"], "channel_id": "alpha", "channel_name": "Alpha",+ "base_url": "https://original.test/v1", "protocol": "openai", "api_format": "openai"}+ restored = restore_route(saved)+ assert restored.base_url == saved["base_url"]+ assert restored.api_key == snapshot.channels[0].api_key++[email protected]("capability", MODELS)+def test_managed_model_without_enabled_bindings_cannot_switch_to_another_model(routing, capability):+ snapshot = routing(capability, binding_enabled=False)+ other = snapshot.logical_models[0].model_copy(deep=True)+ other.id = "other-model"+ other.bindings[0].upstream_model = "other-model"+ other.bindings[0].enabled = True+ snapshot.logical_models.append(other)+ snapshot.channels[0].models.append("other-model")+ assert resolve_logical_model_candidates(capability, MODELS[capability]) == []+ with pytest.raises(ValueError):+ resolve_upstream_model(capability, MODELS[capability])++[email protected]("capability", MODELS)+def test_ark_without_channels_cannot_reactivate_disabled_model_from_environment(routing, capability):+ from app.services.ark import ArkGateway++ snapshot = routing(capability, enabled=False)+ snapshot.channels.clear()+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False))+ with pytest.raises(ValueError):+ gateway._resolve_ark_route(capability, MODELS[capability])++[email protected]("capability", ["image", "video", "audio"])+async def test_mock_generation_respects_disabled_model_before_creating_output(routing, monkeypatch, capability):+ from app.services.ark import ArkGateway++ routing(capability, enabled=False)+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_mock=True))+ image = Mock(return_value="/static/mock.png")+ edge = AsyncMock()+ monkeypatch.setattr(gateway, "_write_mock_image", image)+ monkeypatch.setattr(gateway, "_tts_edge", edge)+ with pytest.raises(ValueError):+ if capability == "image":+ await gateway.gen_image("test", model=MODELS[capability])+ elif capability == "video":+ await gateway.gen_video_i2v("https://test/image.png", "test", 5, model=MODELS[capability])+ else:+ await gateway.tts("disabled audio", "Cherry")+ image.assert_not_called()+ edge.assert_not_called()++[email protected]("method", ["_tts_openai_speech", "_tts_openai_chat_audio"])+async def test_qwen_actual_upstream_cannot_bypass_disabled_logical_audio_switch(+ routing, monkeypatch, tmp_path, method,+):+ from app.services.ark import ArkGateway++ routing("audio", enabled=False)+ assert resolve_logical_model_candidates("audio", "qwen3-omni-flash") == []+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_api_key="env-key"))+ request = AsyncMock(return_value=SimpleNamespace(status_code=500, text="fail", content=b""))+ monkeypatch.setattr(gateway, "_request_media", request)+ with pytest.raises(ValueError):+ await getattr(gateway, method)("test", "Cherry", tmp_path / "audio.mp3", model="qwen3-omni-flash")+ request.assert_not_called()+++async def test_audio_request_uses_enabled_binding_credentials(routing, monkeypatch, tmp_path):+ from app.services.ark import ArkGateway++ snapshot = routing("audio")+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_api_key="env-key",+ ark_base_url="https://environment.test/v1"))+ request = AsyncMock(return_value=SimpleNamespace(status_code=500, text="fail", content=b""))+ monkeypatch.setattr(gateway, "_request_media", request)+ await gateway._tts_openai_chat_audio("test", "Cherry", tmp_path / "audio.mp3", model="qwen3-omni-flash")+ assert request.call_args.args[2] == snapshot.channels[0].base_url + "/chat/completions"+ assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer test-key"+++async def test_disabled_audio_fallback_is_skipped_before_calling_provider(routing, monkeypatch, tmp_path):+ from app.services.ark import ArkGateway++ snapshot = routing("audio", enabled=False)+ enabled = LogicalModel(id="gemini-2.5-pro-preview-tts", capability="audio", bindings=[+ LogicalModelBinding(channel_id="alpha", upstream_model="gemini-2.5-pro-preview-tts"),+ ])+ snapshot.logical_models.append(enabled)+ snapshot.channels[0].models.append(enabled.id)+ snapshot.default_models.audio_model = enabled.id+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_mock=False, ark_api_key="env-key"))+ speech = AsyncMock(return_value=False)+ monkeypatch.setattr(gateway, "_tts_openai_speech", speech)+ monkeypatch.setattr("app.services.ark.iter_tokenfree_tts_models", lambda _: [enabled.id, "qwen3-omni-flash"])+ monkeypatch.setattr("app.services.storage.project_dir", lambda _: tmp_path)+ monkeypatch.setattr("app.services.storage.publish_local", lambda _: "/audio.mp3")+ monkeypatch.setattr("app.services.ark.is_near_silent_audio", lambda _: False)++ async def edge(_text, dest, **_kwargs):+ dest.write_bytes(b"a" * 4000)++ monkeypatch.setattr(gateway, "_tts_edge", edge)+ assert await gateway.tts("test", "Cherry") == "/audio.mp3"+ assert [call.kwargs["model"] for call in speech.call_args_list] == [enabled.id]++[email protected]("method", ["expand_content", "chat_storyboard"])+async def test_mock_text_generation_cannot_bypass_disabled_model(routing, method):+ from app.services.ark import ArkGateway++ routing("text", enabled=False)+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_mock=True))+ with pytest.raises(ValueError):+ if method == "expand_content":+ await gateway.expand_content("test")+ else:+ await gateway.chat_storyboard("test", "theme", "", "", 5, 10, 5)+++def test_frozen_image_route_still_resolves_after_model_is_disabled(routing):+ from app.services.ark import ArkGateway+ from app.services.media_models.runtime import current_snapshot++ snapshot = routing("image", enabled=False)+ saved = {"capability": "image", "logical_model_id": MODELS["image"],+ "upstream_model": MODELS["image"], "channel_id": "alpha", "channel_name": "Alpha",+ "base_url": "https://original.test/v1", "protocol": "openai", "api_format": "openai"}+ current_snapshot.set({"items": [{"capability": "image", "model_id": MODELS["image"],+ "operation_id": "image:0", "route": saved}]})+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False))+ route = gateway._resolve_ark_route("image", MODELS["image"])+ assert route.base_url == saved["base_url"]+ assert route.api_key == snapshot.channels[0].api_key+++def test_image_snapshot_does_not_exempt_new_audio_from_disabled_guard(routing):+ from app.services.ark import ArkGateway+ from app.services.media_models.runtime import current_snapshot++ routing("audio", enabled=False)+ current_snapshot.set({"items": [{"capability": "image"}]})+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False))+ with pytest.raises(ValueError):+ gateway._resolve_ark_route("audio", None)++[email protected]("capability,stale_model", [("image", "gpt-image-2"), ("video", "seedance-2.0")])+async def test_task_planning_cannot_use_stale_environment_model_when_managed_default_is_empty(+ routing, capability, stale_model,+):+ from app.config import get_settings+ from app.services.media_models.planning import plan_items++ snapshot = routing(capability, enabled=False, default=False)+ snapshot.channels.clear()+ setattr(get_settings(), f"model_{capability}", stale_model)+ task = SimpleNamespace(domain="studio", task_type=f"tool_{capability}", payload={},+ asset_id=None, shot_id=None, fragment_id=None, drama_project_id=None)+ with pytest.raises(ValueError, match="默认"):+ await plan_items(None, task)+ task.payload = {"model_id": stale_model}+ items = await plan_items(None, task)+ assert items[0]["model_id"] == stale_model++[email protected]("capability,upstream", [+ ("image", "doubao-seedream-5-0-pro-260628"),+ ("video", "doubao-seedance-2-5-260628"),+])+def test_frozen_model_body_resolution_continues_after_new_requests_are_disabled(routing, capability, upstream):+ from app.services.drama.build_seedance_generate_body import resolve_seedance_model_endpoint+ from app.services.drama.seedream_options import resolve_seedream_model_endpoint+ from app.services.media_models.runtime import current_snapshot++ routing(capability, enabled=False, binding_enabled=False)+ saved = {"capability": capability, "logical_model_id": MODELS[capability],+ "upstream_model": upstream, "channel_id": "alpha", "channel_name": "Alpha",+ "base_url": "https://original.test/v1", "protocol": "openai", "api_format": "openai"}+ current_snapshot.set({"items": [{"capability": capability, "model_id": MODELS[capability],+ "operation_id": capability + ":0", "route": saved}]})+ assert resolve_upstream_model(capability, MODELS[capability]) == upstream+ if capability == "image":+ assert resolve_seedream_model_endpoint(MODELS[capability]) == upstream+ else:+ assert resolve_seedance_model_endpoint(MODELS[capability]) == MODELS[capability]+++def test_enabled_standard_seedream_is_independent_of_disabled_pro(routing):+ from app.config import get_settings+ from app.services.media_models.runtime import execution_params++ snapshot = routing("image", enabled=False)+ get_settings().model_image = MODELS["image"]+ snapshot.logical_models.append(LogicalModel(id="seedream-5.0", capability="image", bindings=[+ LogicalModelBinding(channel_id="alpha", upstream_model="seedream-5.0"),+ ]))+ snapshot.channels[0].models.append("seedream-5.0")+ snapshot.default_models.image_model = "seedream-5.0"+ assert resolve_upstream_model("image", "seedream-5.0") == "seedream-5.0"+ assert resolve_upstream_model("image", None) == "seedream-5.0"+ strategy, _, _ = execution_params("image", {"resolution": "2K"})+ assert strategy.model_id == "seedream-5.0"+++async def test_custom_audio_logical_name_keeps_qwen_channel_after_upstream_alias_conversion(+ routing, monkeypatch, tmp_path,+):+ from app.services.ark import ArkGateway++ snapshot = routing("audio")+ snapshot.logical_models[0].id = "friendly-voice"+ snapshot.default_models.audio_model = "friendly-voice"+ gateway = ArkGateway(settings=Settings(_env_file=None, debug=False, ark_mock=False,+ local_media_mock=True, ark_api_key="env-key"))+ request = AsyncMock(return_value=SimpleNamespace(status_code=200, content=b"simulated audio"))+ monkeypatch.setattr(gateway, "_request_media", request)+ monkeypatch.setattr("app.services.storage.project_dir", lambda _: tmp_path)+ metadata = {}+ await gateway.tts("test", "Cherry", result_metadata=metadata)+ assert request.call_count == 1+ assert request.call_args.args[2] == "https://alpha.test/v1/chat/completions"+ assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer test-key"+ assert request.call_args.kwargs["json"]["model"] == "qwen3-omni-flash"+ assert metadata["model_id"] == "qwen3-omni-flash"diff --git a/backend/tests/test_model_enable_settings.py b/backend/tests/test_model_enable_settings.pynew file mode 100644index 0000000..65969a8--- /dev/null+++ b/backend/tests/test_model_enable_settings.py@@ -0,0 +1,90 @@+"""Model switches persist across settings saves and cache reloads."""++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from app import config+from app.models_settings import AppSettings, SystemModelChannelRow+from app.schemas_routing import AdminRoutingSettingsPatch, default_models_to_dict+from app.services import model_settings+from app.services.media_model_presets import all_preset_channel_models+from app.services.tokenfree_gateway import locked_tokenfree_channel+++async def routing_db():+ previous_snapshot = model_settings.get_routing_snapshot()+ previous_overlay = model_settings.get_overlay_dict()+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as connection:+ await connection.run_sync(AppSettings.__table__.create)+ await connection.run_sync(SystemModelChannelRow.__table__.create)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ channel = locked_tokenfree_channel(api_key="test-key", models=all_preset_channel_models(), enabled=True)+ models, defaults = model_settings._bootstrap_logical_from_channels([channel])+ async with sessions() as db:+ db.add(SystemModelChannelRow(id=channel.id, name=channel.name, base_url=channel.base_url,+ api_key_ciphertext=model_settings._encrypt_secret(channel.api_key),+ models=channel.models, enabled=True, protocol=channel.protocol))+ db.add(AppSettings(id="default", config_json={"flat": {},+ "logical_models": [model.model_dump() for model in models],+ "default_models": default_models_to_dict(defaults)}))+ await db.commit()+ try:+ yield db+ finally:+ model_settings._routing_snapshot = previous_snapshot+ model_settings._refresh_overlay({"flat": previous_overlay})+ config.reload_settings()+ await engine.dispose()++[email protected]("capability", ["text", "image", "video", "audio"])+async def test_all_models_of_a_capability_can_be_disabled_and_reenabled(routing_db, capability):+ before = await model_settings.get_admin_routing_settings(routing_db)+ models = [model.model_copy(update={"enabled": False}) if model.capability == capability else model+ for model in before.logical_models]+ key = f"{capability}_model"+ assert any(model.capability == capability for model in models)+ saved, _ = await model_settings.patch_admin_routing_settings(routing_db,+ AdminRoutingSettingsPatch(logical_models=models, default_models=before.default_models))+ assert getattr(saved.default_models, key) == ""+ assert all(not model.enabled for model in saved.logical_models if model.capability == capability)+ # Reload and a subsequent ordinary save must not resurrect a preset/default.+ await model_settings.load_model_settings_cache(routing_db)+ saved, _ = await model_settings.patch_admin_routing_settings(routing_db, AdminRoutingSettingsPatch())+ assert getattr(saved.default_models, key) == ""+ assert all(not model.enabled for model in saved.logical_models if model.capability == capability)+ original = next(model for model in before.logical_models if model.capability == capability)+ models = [model.model_copy(update={"enabled": True}) if model.id == original.id else model+ for model in saved.logical_models]+ restored, _ = await model_settings.patch_admin_routing_settings(routing_db, AdminRoutingSettingsPatch(logical_models=models))+ assert getattr(restored.default_models, key) == original.id+ assert next(model for model in restored.logical_models if model.id == original.id).enabled+++async def test_disabling_default_selects_an_enabled_model_and_preserves_its_bindings(routing_db):+ before = await model_settings.get_admin_routing_settings(routing_db)+ previous = before.default_models.image_model+ models = [model.model_copy(update={"enabled": False}) if model.id == previous else model+ for model in before.logical_models]+ saved, _ = await model_settings.patch_admin_routing_settings(routing_db,+ AdminRoutingSettingsPatch(logical_models=models, default_models=before.default_models))+ assert saved.default_models.image_model and saved.default_models.image_model != previous+ disabled = next(model for model in saved.logical_models if model.id == previous)+ assert not disabled.enabled+ assert disabled.bindings == next(model for model in before.logical_models if model.id == previous).bindings+ await model_settings.load_model_settings_cache(routing_db)+ after = await model_settings.get_admin_routing_settings(routing_db)+ assert after.default_models.image_model == saved.default_models.image_model+ assert not next(model for model in after.logical_models if model.id == previous).enabled+++async def test_enabled_standard_image_default_is_not_changed_to_pro(routing_db):+ before = await model_settings.get_admin_routing_settings(routing_db)+ defaults = before.default_models.model_copy(update={"image_model": "seedream-5.0"})+ saved, _ = await model_settings.patch_admin_routing_settings(routing_db, AdminRoutingSettingsPatch(default_models=defaults))+ assert saved.default_models.image_model == "seedream-5.0"+ await model_settings.load_model_settings_cache(routing_db)+ after = await model_settings.get_admin_routing_settings(routing_db)+ assert after.default_models.image_model == "seedream-5.0"diff --git a/backend/tests/test_seedance_model_routing.py b/backend/tests/test_seedance_model_routing.pyindex 0dc0c69..da8fb4f 100644--- a/backend/tests/test_seedance_model_routing.py+++ b/backend/tests/test_seedance_model_routing.py@@ -81,6 +81,7 @@ def test_resolve_upstream_model_routes_seedance_2(monkeypatch):name="TokenFree",base_url="https://www.tokenfree.com/v1",api_key="test",+ has_api_key=True,api_format="openai",protocol="auto",models=["seedance-2.5", "seedance-2.0"],diff --git a/frontend/nginx.conf b/frontend/nginx.confindex ace5294..6e5d9c3 100644--- a/frontend/nginx.conf+++ b/frontend/nginx.conf@@ -35,6 +35,11 @@ server {proxy_read_timeout 600s;}+ location = /index.html {+ root /usr/share/nginx/html;+ add_header Cache-Control "no-cache, no-store, must-revalidate" always;+ }+location / {root /usr/share/nginx/html;try_files $uri $uri/ /index.html;diff --git a/frontend/src/hooks/useMediaModelsCatalog.ts b/frontend/src/hooks/useMediaModelsCatalog.tsindex d8525fc..5730b38 100644--- a/frontend/src/hooks/useMediaModelsCatalog.ts+++ b/frontend/src/hooks/useMediaModelsCatalog.ts@@ -1,6 +1,7 @@/** 拉取并缓存前台 TokenFree 图/视频模型目录。 */import { useEffect, useState } from 'react'import { api, type MediaModelOption, type MediaModelsCatalog } from '../api'+export { resolveCatalogModelSelection } from '../lib/mediaCatalogSelection'let cached: MediaModelsCatalog | null = nulllet inflight: Promise<MediaModelsCatalog> | null = nulldiff --git a/frontend/src/lib/mediaCatalogSelection.ts b/frontend/src/lib/mediaCatalogSelection.tsnew file mode 100644index 0000000..8b1d32b--- /dev/null+++ b/frontend/src/lib/mediaCatalogSelection.ts@@ -0,0 +1,15 @@+import type { MediaModelsCatalog } from '../api.ts'++/** Unknown data preserves a draft; a successful empty catalog clears unavailable choices. */+export function resolveCatalogModelSelection(+ catalog: MediaModelsCatalog | null,+ capability: 'image' | 'video',+ currentId: string,+): string {+ if (!catalog) return currentId+ const models = (capability === 'image' ? catalog.image_models : catalog.video_models)+ .filter(model => model.available !== false)+ if (models.some(model => model.id === currentId)) return currentId+ const defaultId = capability === 'image' ? catalog.defaults.image_model : catalog.defaults.video_model+ return models.find(model => model.id === defaultId)?.id || models[0]?.id || ''+}diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsxindex 6c984db..b257fd8 100644--- a/frontend/src/pages/drama/EpisodeEditPage.tsx+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx@@ -54,7 +54,7 @@ import { FragmentPlanSkillModal } from '../../components/drama/FragmentPlanSkillimport { DramaGenTaskDetail } from '../../components/drama/DramaGenTaskDetail'import { CircleAlert } from 'lucide-react'import { useDramaImageGenQueue } from '../../hooks/useDramaImageGenQueue'-import { useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'+import { resolveCatalogModelSelection, useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'import { enqueueDramaImageGen } from '../../lib/dramaImageGenQueue'import { defaultOptionsForAssetKind } from '../../lib/dramaGenerationOptions'import { dramaAssetImageGenButtonLabel } from '../../lib/dramaAssetImage'@@ -199,9 +199,7 @@ function EpisodeEditInner() {useEffect(() => {// 目录到达后,把旧 Kie/方舟 id 换成后台默认视频模型if (!mediaCatalog) return- const ids = mediaCatalog.video_models.map((m) => m.id)- if (!ids.length) return- setModelId((prev) => (ids.includes(prev) ? prev : mediaCatalog.defaults.video_model || ids[0]))+ setModelId(previous => resolveCatalogModelSelection(mediaCatalog, 'video', previous))}, [mediaCatalog])const selected = fragments[selectedIndex] || nulldiff --git a/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx b/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsxindex 8172240..a5a8efd 100644--- a/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx+++ b/frontend/src/pages/drama/canvas/nodes/DramaImageGenOptionsBar.tsx@@ -23,6 +23,7 @@ import {import {catalogImageModels,catalogModelLabel,+ resolveCatalogModelSelection,useMediaModelsCatalog,} from '../../../../hooks/useMediaModelsCatalog'import './dramaImageGenOptions.css'@@ -54,10 +55,12 @@ export function DramaImageGenOptionsBar({// 仅在模型为空/不在目录时补默认;用户已选合法模型时绝不覆盖。// 注意:不要依赖 disabled——发送后 busy 翻转会误触发,把选项打回 Seedream/3:4。if (!catalog) return- const ids = imageModels.map((m) => m.id)- if (!ids.length) return- if (value.model_id && ids.includes(value.model_id)) return- const nextModel = catalog.defaults.image_model || ids[0]+ const nextModel = resolveCatalogModelSelection(catalog, 'image', value.model_id)+ if (nextModel === value.model_id) return+ if (!nextModel) {+ onChange({ ...value, model_id: '' })+ return+ }const nextRatio = clampImageAspectRatioForModel(nextModel,value.aspect_ratio,diff --git a/frontend/src/pages/drama/canvas/nodes/DramaVideoGenOptionsBar.tsx b/frontend/src/pages/drama/canvas/nodes/DramaVideoGenOptionsBar.tsxindex fd4f87a..fdedd51 100644--- a/frontend/src/pages/drama/canvas/nodes/DramaVideoGenOptionsBar.tsx+++ b/frontend/src/pages/drama/canvas/nodes/DramaVideoGenOptionsBar.tsx@@ -25,6 +25,7 @@ import {import {catalogModelLabel,catalogVideoModels,+ resolveCatalogModelSelection,useMediaModelsCatalog,} from '../../../../hooks/useMediaModelsCatalog'import './dramaImageGenOptions.css'@@ -59,11 +60,13 @@ export function DramaVideoGenOptionsBar({useEffect(() => {// 目录到达后,把旧 Kie/方舟 id 换成后台默认视频模型if (!catalog || disabled) return- const ids = videoModels.map((m) => m.id)- if (!ids.length) return- if (value.model_id && ids.includes(value.model_id)) return- const next = catalog.defaults.video_model || ids[0]- if (next && next !== value.model_id) {+ const next = resolveCatalogModelSelection(catalog, 'video', value.model_id)+ if (next === value.model_id) return+ if (!next) {+ onChange({ ...value, model_id: '' })+ return+ }+ if (next !== value.model_id) {onChange({...value,model_id: next,@@ -72,7 +75,7 @@ export function DramaVideoGenOptionsBar({duration_sec: clampVideoDuration(value.duration_sec, next, catalog, videoModels),})}- }, [catalog, disabled])+ }, [catalog, disabled, value.model_id])useEffect(() => {// 换模型后:清晰度 / 比例 / 时长钳到允许范围(须已知目录行,避免 SAFE 误写)diff --git a/frontend/src/pages/studio/StyleConfigPage.tsx b/frontend/src/pages/studio/StyleConfigPage.tsxindex 34f2b11..3260d5f 100644--- a/frontend/src/pages/studio/StyleConfigPage.tsx+++ b/frontend/src/pages/studio/StyleConfigPage.tsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react'import { useNavigate, useParams } from 'react-router-dom'import { api, defaultsFromTemplate, resolveVoiceId } from '../../api'import type { MediaModelOption, PipelineMode, Project, Template, VoicePreset } from '../../api'-import { useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'+import { resolveCatalogModelSelection, useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'import { MediaCostNotice } from '../../components/billing/MediaCostNotice'import AppShell from '../../components/layout/AppShell'import Stepper from '../../components/ui/Stepper'@@ -68,9 +68,9 @@ export default function StyleConfigPage() {useEffect(() => {if (!mediaCatalog) return- setImageModel(previous => previous || mediaCatalog.defaults.image_model)- setVideoModel(previous => previous || mediaCatalog.defaults.video_model)- }, [mediaCatalog])+ setImageModel(previous => resolveCatalogModelSelection(mediaCatalog, 'image', previous))+ setVideoModel(previous => resolveCatalogModelSelection(mediaCatalog, 'video', previous))+ }, [mediaCatalog, imageModel, videoModel])useEffect(() => {if (!localStorage.getItem('token')) {diff --git a/frontend/tests/media-catalog-selection.test.mjs b/frontend/tests/media-catalog-selection.test.mjsnew file mode 100644index 0000000..c82c9b2--- /dev/null+++ b/frontend/tests/media-catalog-selection.test.mjs@@ -0,0 +1,34 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { resolveCatalogModelSelection } from '../src/lib/mediaCatalogSelection.ts'++const model = (id, available = true) => ({ id, available })+const catalog = (image_models = [], video_models = [], defaults = {}) => ({+ image_models, video_models, defaults: { image_model: '', video_model: '', ...defaults },+})++test('unknown catalog from an initial load or request failure preserves the draft selection', () => {+ assert.equal(resolveCatalogModelSelection(null, 'image', 'saved-image'), 'saved-image')+ assert.equal(resolveCatalogModelSelection(null, 'video', 'saved-video'), 'saved-video')+})++test('an authoritative empty capability clears a previously selected model without using a stale default', () => {+ const empty = catalog([], [], { image_model: 'disabled-image', video_model: 'disabled-video' })+ assert.equal(resolveCatalogModelSelection(empty, 'image', 'disabled-image'), '')+ assert.equal(resolveCatalogModelSelection(empty, 'video', 'disabled-video'), '')+})++test('catalog refresh preserves a valid choice and replaces removed models with a listed available default', () => {+ const refreshed = catalog([model('image-one'), model('image-two')], [model('video-one')], { image_model: 'image-two' })+ assert.equal(resolveCatalogModelSelection(refreshed, 'image', 'image-one'), 'image-one')+ assert.equal(resolveCatalogModelSelection(refreshed, 'image', 'removed-image'), 'image-two')+ assert.equal(resolveCatalogModelSelection(refreshed, 'video', 'removed-video'), 'video-one')+})++test('unavailable models and defaults outside the current catalog cannot become selected', () => {+ const partial = catalog([model('unpriced', false), model('usable')], [model('unpriced-video', false)], { image_model: 'unpriced', video_model: 'unpriced-video' })+ assert.equal(resolveCatalogModelSelection(partial, 'image', 'unpriced'), 'usable')+ assert.equal(resolveCatalogModelSelection(partial, 'video', 'unpriced-video'), '')+ partial.defaults.image_model = 'removed-default'+ assert.equal(resolveCatalogModelSelection(partial, 'image', ''), 'usable')+})