PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(tasks): keep steps before freeze to avoid leased stuck
yib1b8bd949a4d
diff --git a/admin/src/api/client.ts b/admin/src/api/client.tsindex a27aebf..af2c0a5 100644--- a/admin/src/api/client.ts+++ b/admin/src/api/client.ts@@ -414,6 +414,8 @@ export type AdminTaskRow = {drama_project_id?: number | null;episode_id?: number | null;fragment_id?: number | null;+ asset_id?: number | null;+ script_id?: number | null;created_at?: string | null;started_at?: string | null;finished_at?: string | null;@@ -421,6 +423,10 @@ export type AdminTaskRow = {billing_charged_fen?: number;billing_refunded_fen?: number;billing_status?: string;+ /** 提交参数(入队 payload) */+ payload?: Record<string, unknown> | null;+ /** 执行结果 */+ result_payload?: Record<string, unknown> | null;};export type AdminUsageEventBrief = {diff --git a/admin/src/components/settings/ArkVolcMediaPanel.tsx b/admin/src/components/settings/ArkVolcMediaPanel.tsxindex fbdda71..b8bb7c5 100644--- a/admin/src/components/settings/ArkVolcMediaPanel.tsx+++ b/admin/src/components/settings/ArkVolcMediaPanel.tsx@@ -39,7 +39,7 @@ function modelOptions(/** 火山方舟生图/视频:固定渠道 + 手动拉取模型 */export function ArkVolcMediaPanel({- channelId,+ channelId: _channelId,hasApiKey,apiKeyInput,onApiKeyChange,@@ -94,12 +94,12 @@ export function ArkVolcMediaPanel({return (<SettingsPanelclassName="settings-panel--compact"- title="火山方舟(生图 / 视频)"- description={`固定 Base URL · ${ARK_BASE} · 渠道 ${channelId}`}+ title="2. 火山方舟媒体专区"+ description={`固定 Base URL · ${ARK_BASE}`}actions={<buttontype="button"- className="admin-quick-btn !inline-flex !w-auto items-center gap-1.5 px-3 py-1.5 text-xs"+ className="admin-btn admin-btn-secondary settings-mini-btn"disabled={fetching || !canFetch}onClick={() => void fetchModels()}>diff --git a/admin/src/components/settings/OssSettingsPanel.tsx b/admin/src/components/settings/OssSettingsPanel.tsxindex 6b7275f..8d10182 100644--- a/admin/src/components/settings/OssSettingsPanel.tsx+++ b/admin/src/components/settings/OssSettingsPanel.tsx@@ -1,10 +1,14 @@import { useMemo, useState } from "react";-import { Cloud } from "lucide-react";-import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";+import {+ LabeledControl,+ SettingsLoading,+ SettingsPanel,+ SettingsStatusBar,+ SettingsTabShell,+} from "@/components/settings/SettingsPanel";import { SecretField } from "@/components/settings/SecretField";import { Switch } from "@/components/ui/switch";import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";-import { cn } from "@/lib/utils";// OSS / TOS / CDN 存储配置export function OssSettingsPanel() {@@ -27,6 +31,13 @@ export function OssSettingsPanel() {return Boolean(form.oss_bucket && hasCreds && hasSecret);}, [form, clearOssId, clearOssSecret, ossKeyIdInput, ossKeySecretInput]);+ const tosConfigured = useMemo(() => {+ if (!form) return false;+ const hasKey = (form.has_tos_access_key && !clearTosKey) || tosKeyInput.trim().length > 0;+ const hasSecret = (form.has_tos_secret_key && !clearTosSecret) || tosSecretInput.trim().length > 0;+ return Boolean(form.tos_bucket && hasKey && hasSecret);+ }, [form, clearTosKey, clearTosSecret, tosKeyInput, tosSecretInput]);+async function handleSave() {if (!form) return;await save(@@ -69,25 +80,52 @@ export function OssSettingsPanel() {return (<SettingsTabShell onSave={() => void handleSave()} saving={saving}>- <SettingsSurface>- <SectionTitle icon={<Cloud className="h-4 w-4" />} title="OSS 状态" />- <div className="mt-2 flex flex-wrap items-center gap-2">- <span className={cn("admin-status-pill", ossReady ? "is-done" : form.oss_enabled ? "is-warn" : "")}>- {form.oss_enabled ? (ossReady ? "OSS 已就绪" : "已启用但凭证不完整") : "OSS 未启用"}+ <SettingsStatusBar+ title="存储就绪状态"+ items={[+ {+ id: "oss",+ label: "阿里云 OSS",+ ready: ossReady,+ readyText: "已就绪",+ pendingText: form.oss_enabled ? "凭证不完整" : "未启用",+ },+ {+ id: "async",+ label: "异步上传",+ ready: form.oss_upload_async,+ readyText: "已开启",+ pendingText: "已关闭",+ },+ {+ id: "tos",+ label: "火山 TOS",+ ready: tosConfigured,+ readyText: "已配置",+ pendingText: "可选",+ },+ ]}+ extra={+ <span className="settings-status-extra">+ 配置来源:{form.source === "db" ? "管理端" : "环境变量"}</span>- <span className="text-xs text-[#909399]">配置来源:{form.source === "db" ? "管理端" : "环境变量"}</span>- </div>- </SettingsSurface>+ }+ />- <SettingsPanel title="阿里云 OSS" description="生成文件先落本地,再异步上传 OSS">- <div className="settings-toggle-row">- <div>- <strong>启用 OSS</strong>- <span>关闭后仅使用本地静态目录</span>+ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="1. 阿里云 OSS"+ description="生成文件先落本地,再异步上传 OSS"+ >+ <div className="settings-toggle-row">+ <div>+ <strong>启用 OSS</strong>+ <span>关闭后仅使用本地静态目录</span>+ </div>+ <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} /></div>- <Switch checked={form.oss_enabled} onCheckedChange={(v) => patchField("oss_enabled", v)} />- </div>- <div className="settings-field-grid mt-2">+ <div className="settings-field-grid mt-3"><LabeledControl label="Endpoint"><inputclassName="settings-input"@@ -119,7 +157,7 @@ export function OssSettingsPanel() {onChange={(e) => patchField("oss_folder", e.target.value)}/></LabeledControl>- <LabeledControl label="公网访问基址" hint="留空则自动拼 https://{bucket}.{endpoint}">+ <LabeledControl label="公网访问基址" hint="留空则自动拼 https://{bucket}.{endpoint}" className="settings-field-span-full"><inputclassName="settings-input"placeholder="https://cdn.example.com"@@ -155,17 +193,21 @@ export function OssSettingsPanel() {}}/></div>- <div className="settings-toggle-row mt-2">- <div>- <strong>异步上传</strong>- <span>先返回本地 URL,后台队列上传 OSS</span>+ <div className="settings-toggle-row mt-3">+ <div>+ <strong>异步上传</strong>+ <span>先返回本地 URL,后台队列上传 OSS</span>+ </div>+ <Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} /></div>- <Switch checked={form.oss_upload_async} onCheckedChange={(v) => patchField("oss_upload_async", v)} />- </div>- </SettingsPanel>+ </SettingsPanel>- <SettingsPanel title="火山 TOS(可选)" description="历史存储方案,新项目可只配 OSS">- <div className="settings-field-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="2. 火山 TOS(可选)"+ description="历史存储方案,新项目可只配 OSS"+ >+ <div className="settings-field-grid"><LabeledControl label="Endpoint"><inputclassName="settings-input"@@ -180,7 +222,7 @@ export function OssSettingsPanel() {onChange={(e) => patchField("tos_bucket", e.target.value)}/></LabeledControl>- <LabeledControl label="CDN 基址">+ <LabeledControl label="CDN 基址" className="settings-field-span-full"><inputclassName="settings-input"placeholder="http://localhost:8000/static"@@ -207,9 +249,10 @@ export function OssSettingsPanel() {setTosSecretInput("");setClearTosSecret(true);}}- />- </div>- </SettingsPanel>+ />+ </div>+ </SettingsPanel>+ </div></SettingsTabShell>);}diff --git a/admin/src/components/settings/PaymentSettingsPanel.tsx b/admin/src/components/settings/PaymentSettingsPanel.tsxindex 750c320..c991f38 100644--- a/admin/src/components/settings/PaymentSettingsPanel.tsx+++ b/admin/src/components/settings/PaymentSettingsPanel.tsx@@ -1,10 +1,14 @@import { useMemo, useState } from "react";-import { BarChart3, Bell, CreditCard, Mail, Wallet } from "lucide-react";-import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";+import {+ LabeledControl,+ SettingsLoading,+ SettingsPanel,+ SettingsStatusBar,+ SettingsTabShell,+} from "@/components/settings/SettingsPanel";import { SecretField } from "@/components/settings/SecretField";import { Switch } from "@/components/ui/switch";import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";-import { cn } from "@/lib/utils";// 易支付与 Token 计费配置export function PaymentSettingsPanel() {@@ -24,6 +28,19 @@ export function PaymentSettingsPanel() {return Boolean(form.epay_pid && form.epay_api_url && hasKey);}, [form, clearEpayKey, epayKeyInput]);+ const volcReady = useMemo(() => {+ if (!form) return false;+ const hasAk = (form.has_volc_access_key_id && !clearVolcAk) || volcAkInput.trim().length > 0;+ const hasSk = (form.has_volc_secret_access_key && !clearVolcSk) || volcSkInput.trim().length > 0;+ return Boolean(form.volc_ark_usage_enabled && hasAk && hasSk);+ }, [form, clearVolcAk, clearVolcSk, volcAkInput, volcSkInput]);++ const smtpReady = useMemo(() => {+ if (!form?.smtp_enabled) return false;+ const hasPass = (form.has_smtp_password && !clearSmtpPassword) || smtpPasswordInput.trim().length > 0;+ return Boolean(form.smtp_host && form.smtp_from && hasPass);+ }, [form, clearSmtpPassword, smtpPasswordInput]);+async function handleSave() {if (!form) return;await save(@@ -88,20 +105,47 @@ export function PaymentSettingsPanel() {return (<SettingsTabShell onSave={() => void handleSave()} saving={saving}>- <SettingsSurface>- <SectionTitle icon={<CreditCard className="h-4 w-4" />} title="支付就绪" />- <div className="mt-2 flex flex-wrap gap-2">- <span className={cn("admin-status-pill", epayReady ? "is-done" : "is-warn")}>- {epayReady ? "易支付已配置" : "易支付未完整配置"}- </span>- <span className={cn("admin-status-pill", form.billing_enabled ? "is-done" : "")}>- {form.billing_enabled ? "Token 计费已开启" : "Token 计费已关闭"}- </span>- </div>- </SettingsSurface>+ <SettingsStatusBar+ title="支付就绪状态"+ items={[+ {+ id: "epay",+ label: "易支付",+ ready: epayReady,+ readyText: "已配置",+ pendingText: "未完整",+ },+ {+ id: "billing",+ label: "Token 计费",+ ready: form.billing_enabled,+ readyText: "已开启",+ pendingText: "已关闭",+ },+ {+ id: "volc",+ label: "上游成本",+ ready: volcReady,+ readyText: "已启用",+ pendingText: form.volc_ark_usage_enabled ? "缺凭证" : "未启用",+ },+ {+ id: "smtp",+ label: "SMTP",+ ready: smtpReady,+ readyText: "已配置",+ pendingText: form.smtp_enabled ? "不完整" : "未启用",+ },+ ]}+ />- <SettingsPanel title="易支付 Epay" description="生产回调请用 /epay/notify,勿含 /api/">- <div className="settings-field-grid">+ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="1. 易支付 Epay"+ description="生产回调请用 /epay/notify,勿含 /api/"+ >+ <div className="settings-field-grid"><LabeledControl label="网关地址"><inputclassName="settings-input"@@ -127,14 +171,14 @@ export function PaymentSettingsPanel() {setClearEpayKey(true);}}/>- <LabeledControl label="异步通知 URL" hint="生产:{域名}/epay/notify">+ <LabeledControl label="异步通知 URL" hint="生产:{域名}/epay/notify" className="settings-field-span-full"><inputclassName="settings-input"value={form.epay_notify_url}onChange={(e) => patchField("epay_notify_url", e.target.value)}/></LabeledControl>- <LabeledControl label="同步跳转 URL">+ <LabeledControl label="同步跳转 URL" className="settings-field-span-full"><inputclassName="settings-input"value={form.epay_return_url}@@ -142,18 +186,21 @@ export function PaymentSettingsPanel() {/></LabeledControl></div>- </SettingsPanel>+ </SettingsPanel>- <SettingsPanel title="Token 计费" description="按上游成本 × markup 扣费">- <SectionTitle icon={<Wallet className="h-4 w-4" />} title="开关与系数" />- <div className="settings-toggle-row">+ <SettingsPanel+ className="settings-panel--compact"+ title="2. Token 计费"+ description="按上游成本 × markup 扣费"+ >+ <div className="settings-toggle-row"><div><strong>启用 Token 计费</strong>- <span>关闭后生成不扣余额(管理员可单独豁免)</span>+ <span>关闭后生成不扣余额</span></div><Switch checked={form.billing_enabled} onCheckedChange={(v) => patchField("billing_enabled", v)} /></div>- <div className="settings-field-grid mt-2">+ <div className="settings-field-grid mt-3"><LabeledControl label="加价系数 markup"><inputclassName="settings-input"@@ -185,8 +232,8 @@ export function PaymentSettingsPanel() {</LabeledControl></div>- <SectionTitle icon={<Wallet className="h-4 w-4" />} title="单价(元 / 百万 token)" />- <div className="settings-field-grid mt-2">+ <div className="settings-subsection-title">单价(元 / 百万 token)</div>+ <div className="settings-field-grid"><LabeledControl label="LLM"><inputclassName="settings-input"@@ -234,8 +281,8 @@ export function PaymentSettingsPanel() {</LabeledControl></div>- <SectionTitle icon={<Wallet className="h-4 w-4" />} title="估算 token(缺 usage 时)" />- <div className="settings-field-grid mt-2">+ <div className="settings-subsection-title">估算 token(缺 usage 时)</div>+ <div className="settings-field-grid"><LabeledControl label="LLM 估算"><inputclassName="settings-input"@@ -270,14 +317,14 @@ export function PaymentSettingsPanel() {</LabeledControl></div>- <div className="settings-toggle-row mt-2">+ <div className="settings-toggle-row mt-3"><div>- <strong>旧版次数配额(quota_enabled)</strong>+ <strong>旧版次数配额</strong><span>与 Token 计费并存时以 billing_enabled 为准</span></div><Switch checked={form.quota_enabled} onCheckedChange={(v) => patchField("quota_enabled", v)} /></div>- <div className="settings-field-grid mt-2">+ <div className="settings-field-grid mt-2"><LabeledControl label="新用户默认次数"><inputclassName="settings-input"@@ -288,22 +335,27 @@ export function PaymentSettingsPanel() {/></LabeledControl></div>- </SettingsPanel>+ </SettingsPanel>+ </div>- <SettingsPanel title="额度告警" description="用户消费提醒与平台费用邮件告警">- <SectionTitle icon={<Bell className="h-4 w-4" />} title="用户消费提醒" />+ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="3. 额度告警与 SMTP"+ description="用户消费提醒与平台费用邮件"+ ><div className="settings-toggle-row"><div>- <strong>启用用户弹窗提醒</strong>- <span>用户累计扣费每达间隔档位弹出一次提示</span>+ <strong>用户弹窗提醒</strong>+ <span>累计扣费每达间隔档位弹出一次</span></div><Switchchecked={form.billing_user_alert_enabled}onCheckedChange={(v) => patchField("billing_user_alert_enabled", v)}/></div>- <div className="settings-field-grid mt-2">- <LabeledControl label="提醒间隔(分)" hint="1000 = ¥10;100000 = ¥1000">+ <div className="settings-field-grid mt-2">+ <LabeledControl label="提醒间隔(分)" hint="1000 = ¥10"><inputclassName="settings-input"type="number"@@ -314,19 +366,18 @@ export function PaymentSettingsPanel() {</LabeledControl></div>- <SectionTitle icon={<Mail className="h-4 w-4" />} title="平台费用邮件告警" />- <div className="settings-toggle-row">+ <div className="settings-toggle-row mt-3"><div>- <strong>启用管理员邮件告警</strong>- <span>按上游 cost 汇总,达到阈值后发送邮件</span>+ <strong>管理员邮件告警</strong>+ <span>按上游 cost 汇总达阈值后发信</span></div><Switchchecked={form.billing_admin_cost_alert_enabled}onCheckedChange={(v) => patchField("billing_admin_cost_alert_enabled", v)}/></div>- <div className="settings-field-grid mt-2">- <LabeledControl label="告警阈值(分)" hint="例:500000 = ¥5000">+ <div className="settings-field-grid mt-2">+ <LabeledControl label="告警阈值(分)"><inputclassName="settings-input"type="number"@@ -339,7 +390,7 @@ export function PaymentSettingsPanel() {</LabeledControl><LabeledControl label="统计周期"><select- className="settings-input"+ className="settings-select"value={form.billing_admin_cost_alert_period}onChange={(e) => patchField("billing_admin_cost_alert_period", e.target.value)}>@@ -348,31 +399,24 @@ export function PaymentSettingsPanel() {<option value="all_time">累计</option></select></LabeledControl>- <LabeledControl label="收件邮箱" hint="逗号分隔;留空则发给全部管理员">+ <LabeledControl label="收件邮箱" hint="逗号分隔" className="settings-field-span-full"><inputclassName="settings-input"- placeholder="[email protected],[email protected]"+ placeholder="[email protected]"value={form.billing_admin_cost_alert_emails}onChange={(e) => patchField("billing_admin_cost_alert_emails", e.target.value)}/></LabeledControl></div>- {(form.billing_admin_cost_alert_last_period_key || form.billing_admin_cost_alert_last_level > 0) && (- <p className="mt-2 text-xs text-[#909399]">- 上次告警:周期 {form.billing_admin_cost_alert_last_period_key || "—"},档位{" "}- {form.billing_admin_cost_alert_last_level}- </p>- )}- <SectionTitle icon={<Mail className="h-4 w-4" />} title="SMTP 发信" />- <div className="settings-toggle-row">+ <div className="settings-toggle-row mt-3"><div><strong>启用 SMTP</strong>- <span>邮件告警依赖 SMTP 配置</span>+ <span>邮件告警依赖 SMTP</span></div><Switch checked={form.smtp_enabled} onCheckedChange={(v) => patchField("smtp_enabled", v)} /></div>- <div className="settings-field-grid mt-2">+ <div className="settings-field-grid mt-2"><LabeledControl label="SMTP 主机"><inputclassName="settings-input"@@ -390,15 +434,14 @@ export function PaymentSettingsPanel() {onChange={(e) => patchField("smtp_port", Number(e.target.value))}/></LabeledControl>- <LabeledControl label="发件人地址">+ <LabeledControl label="发件人"><inputclassName="settings-input"- placeholder="[email protected]"value={form.smtp_from}onChange={(e) => patchField("smtp_from", e.target.value)}/></LabeledControl>- <LabeledControl label="SMTP 用户名">+ <LabeledControl label="用户名"><inputclassName="settings-input"value={form.smtp_user}@@ -415,30 +458,30 @@ export function PaymentSettingsPanel() {setClearSmtpPassword(true);}}/>- <LabeledControl label="TLS">- <div className="settings-toggle-row !mt-0">- <Switch- checked={form.smtp_use_tls}- onCheckedChange={(v) => patchField("smtp_use_tls", v)}- />+ <LabeledControl label="使用 TLS">+ <div className="settings-inline-switch">+ <Switch checked={form.smtp_use_tls} onCheckedChange={(v) => patchField("smtp_use_tls", v)} /></div></LabeledControl></div>- </SettingsPanel>+ </SettingsPanel>- <SettingsPanel title="上游成本监控" description="火山 GetInferenceUsage,与方舟 API Key 分离">- <SectionTitle icon={<BarChart3 className="h-4 w-4" />} title="火山 Access Key" />+ <SettingsPanel+ className="settings-panel--compact"+ title="4. 上游成本监控"+ description="火山 GetInferenceUsage,与方舟 API Key 分离"+ ><div className="settings-toggle-row"><div><strong>启用官方用量拉取</strong>- <span>关闭后仪表盘仅展示本地 seedance 成本</span>+ <span>关闭后仪表盘仅展示本地成本</span></div><Switchchecked={form.volc_ark_usage_enabled}onCheckedChange={(v) => patchField("volc_ark_usage_enabled", v)}/></div>- <div className="settings-field-grid mt-2">+ <div className="settings-field-grid mt-3"><SecretFieldlabel="Access Key ID"value={volcAkInput}@@ -467,7 +510,8 @@ export function PaymentSettingsPanel() {/></LabeledControl></div>- </SettingsPanel>+ </SettingsPanel>+ </div></SettingsTabShell>);}diff --git a/admin/src/components/settings/RoutingSettingsPanel.tsx b/admin/src/components/settings/RoutingSettingsPanel.tsxindex 1f78cd6..e8518eb 100644--- a/admin/src/components/settings/RoutingSettingsPanel.tsx+++ b/admin/src/components/settings/RoutingSettingsPanel.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from "react";-import { Mic, Plus, Trash2, Type } from "lucide-react";+import { Loader2, Plus, RefreshCw, Trash2 } from "lucide-react";import { toast } from "sonner";import { api, type AdminRoutingSettings } from "@/api/client";import {@@ -7,13 +7,19 @@ import {ARK_BASE,ARK_VOLC_CHANNEL_ID,consolidateArkVolcChannels,- DEFAULT_IMAGE_MODEL,DEFAULT_VIDEO_MODEL,inferVolcMediaDraft,resolveDefaultModelsFromUpstream,type VolcMediaDraft,} from "@/components/settings/ArkVolcMediaPanel";-import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";+import {+ LabeledControl,+ SettingsLoading,+ SettingsPanel,+ SettingsSurface,+ SettingsTabShell,+} from "@/components/settings/SettingsPanel";+import { Switch } from "@/components/ui/switch";import { cn } from "@/lib/utils";type ChannelDraft = AdminRoutingSettings["system_channels"][number] & {@@ -22,6 +28,8 @@ type ChannelDraft = AdminRoutingSettings["system_channels"][number] & {type Capability = "text" | "image" | "video" | "audio";+type UpstreamModelOption = { id: string; label: string; capability: string };+const CAPABILITY_LABELS: Record<Capability, string> = {text: "文本",image: "图像",@@ -29,6 +37,13 @@ const CAPABILITY_LABELS: Record<Capability, string> = {audio: "语音",};+const PROTOCOL_LABELS: Record<string, string> = {+ auto: "自动",+ openai: "OpenAI 兼容",+ ark: "ARK(生图/视频)",+ volc_tts: "豆包 TTS",+};+// 与后端 infer_model_capability 对齐,用于渠道能力徽标function inferCapability(model: string, protocol: string): Capability {const mid = (model || "").trim().toLowerCase().replace(/\s+/g, "");@@ -56,13 +71,35 @@ function channelCapabilities(channel: AdminRoutingSettings["system_channels"][nureturn Array.from(caps);}-// 渠道 + 逻辑模型路由配置面板+// 计算路由就绪条+function buildReadiness(data: AdminRoutingSettings | null) {+ const channels = data?.system_channels ?? [];+ const enabled = channels.filter((c) => c.enabled);+ const hasCap = (cap: Capability) =>+ enabled.some(+ (c) =>+ (c.has_api_key || Boolean(c.api_key)) &&+ (channelCapabilities(c).includes(cap) || c.models.some((m) => inferCapability(m, c.protocol) === cap)),+ );+ return [+ { id: "text", label: "文本路由", ready: hasCap("text") || Boolean(data?.default_models.text_model) },+ { id: "image", label: "图像路由", ready: hasCap("image") || Boolean(data?.default_models.image_model) },+ { id: "video", label: "视频路由", ready: hasCap("video") || Boolean(data?.default_models.video_model) },+ { id: "audio", label: "语音路由", ready: hasCap("audio") || Boolean(data?.default_models.audio_model) },+ { id: "secret", label: "密钥加密存储", ready: true },+ ] as const;+}++// 渠道 + 逻辑模型路由配置面板(设计稿:就绪条 + 主从渠道 + 方舟专区 + 逻辑路由表)export function RoutingSettingsPanel() {const [data, setData] = useState<AdminRoutingSettings | null>(null);const [apiKeyInputs, setApiKeyInputs] = useState<Record<string, string>>({});const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [selectedChannelId, setSelectedChannelId] = useState("");+ const [upstreamModels, setUpstreamModels] = useState<UpstreamModelOption[]>([]);+ const [fetchingModels, setFetchingModels] = useState(false);+ const [manualModel, setManualModel] = useState("");const [volcDraft, setVolcDraft] = useState<VolcMediaDraft>({imageModel: "",image45Model: "",@@ -80,6 +117,7 @@ export function RoutingSettingsPanel() {setData(res);setSelectedChannelId((prev) => prev || res.system_channels[0]?.id || "");setApiKeyInputs({});+ setUpstreamModels([]);} catch (err) {toast.error(err instanceof Error ? err.message : "加载路由配置失败");} finally {@@ -100,16 +138,27 @@ export function RoutingSettingsPanel() {[apiKeyInputs, data],);- const otherChannels = useMemo(- () => channels.filter((item) => item.id !== ARK_VOLC_CHANNEL_ID),- [channels],- );const selectedChannel =- otherChannels.find((item) => item.id === selectedChannelId) ?? otherChannels[0];+ channels.find((item) => item.id === selectedChannelId) ?? channels[0] ?? null;const arkVolcChannel =channels.find((c) => c.id === ARK_VOLC_CHANNEL_ID) ?? channels.find((c) => c.protocol === "ark");- const hasVideoChannel = Boolean(volcDraft.videoModel || arkVolcChannel);- const videoLogicalModels = (data?.logical_models ?? []).filter((m) => m.capability === "video");+ const readiness = buildReadiness(data);++ const catalogModels = useMemo(() => {+ if (!selectedChannel) return [] as UpstreamModelOption[];+ const map = new Map<string, UpstreamModelOption>();+ for (const m of upstreamModels) map.set(m.id, m);+ for (const id of selectedChannel.models) {+ if (!map.has(id)) {+ map.set(id, {+ id,+ label: id,+ capability: inferCapability(id, selectedChannel.protocol),+ });+ }+ }+ return Array.from(map.values());+ }, [selectedChannel, upstreamModels]);function updateChannel(channelId: string, patch: Partial<AdminRoutingSettings["system_channels"][number]>) {setData((prev) =>@@ -134,9 +183,10 @@ export function RoutingSettingsPanel() {: prev,);setSelectedChannelId(channel.id);+ setUpstreamModels([]);}- // 空白通用渠道+ // 新增空白 OpenAI 兼容渠道function addChannel() {const id = `channel-${Date.now()}`;insertChannel({@@ -146,71 +196,6 @@ export function RoutingSettingsPanel() {api_key: "",has_api_key: false,api_format: "openai",- protocol: "auto",- models: [],- enabled: true,- sort_order: channels.length,- });- }-- // 快捷新增:视频 / 图像 / 文本 / 语音- function addPreset(kind: Capability) {- const stamp = Date.now();- if (kind === "video") {- insertChannel({- id: `ark-video-${stamp}`,- name: "火山方舟视频",- base_url: ARK_BASE,- api_key: "",- has_api_key: false,- api_format: "ark",- protocol: "ark",- models: [DEFAULT_VIDEO_MODEL],- enabled: true,- sort_order: channels.length,- });- toast.message("已加入视频渠道草稿", {- description: "填写方舟 API Key,确认上游 Seedance 模型 ID 后点「保存路由」",- });- return;- }- if (kind === "image") {- insertChannel({- id: `ark-image-${stamp}`,- name: "火山方舟生图",- base_url: ARK_BASE,- api_key: "",- has_api_key: false,- api_format: "ark",- protocol: "ark",- models: [DEFAULT_IMAGE_MODEL],- enabled: true,- sort_order: channels.length,- });- return;- }- if (kind === "audio") {- insertChannel({- id: `volc-tts-${stamp}`,- name: "豆包语音 TTS",- base_url: "",- api_key: "",- has_api_key: false,- api_format: "openai",- protocol: "volc_tts",- models: ["zh_female_cancan_mars_bigtts"],- enabled: true,- sort_order: channels.length,- });- return;- }- insertChannel({- id: `openai-text-${stamp}`,- name: "OpenAI 兼容文本",- base_url: "https://api.openai.com/v1",- api_key: "",- has_api_key: false,- api_format: "openai",protocol: "openai",models: [],enabled: true,@@ -219,6 +204,10 @@ export function RoutingSettingsPanel() {}function removeChannel(channelId: string) {+ if (channelId === ARK_VOLC_CHANNEL_ID) {+ toast.error("火山方舟媒体渠道请通过下方专区管理,不可直接删除");+ return;+ }setData((prev) =>prev? {@@ -233,6 +222,58 @@ export function RoutingSettingsPanel() {}: prev,);+ setUpstreamModels([]);+ }++ // 从上游 /models 拉取可用模型+ async function fetchUpstreamModels() {+ if (!selectedChannel) return;+ const keyInput = apiKeyInputs[selectedChannel.id]?.trim();+ if (!selectedChannel.has_api_key && !keyInput) {+ toast.error("请先填写 API Key");+ return;+ }+ if (selectedChannel.protocol === "volc_tts") {+ toast.error("豆包 TTS 请手动填写音色 ID");+ return;+ }+ setFetchingModels(true);+ try {+ const res = await api<{ models: UpstreamModelOption[] }>("/api/admin/settings/upstream/models", {+ method: "POST",+ body: JSON.stringify({+ channel_id: selectedChannel.id,+ protocol: selectedChannel.protocol,+ base_url: selectedChannel.base_url,+ api_key: keyInput || undefined,+ capability: "all",+ }),+ });+ setUpstreamModels(res.models);+ toast.success(`已拉取 ${res.models.length} 个可用模型`);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "拉取模型失败");+ } finally {+ setFetchingModels(false);+ }+ }++ function toggleModel(modelId: string, checked: boolean) {+ if (!selectedChannel) return;+ const next = checked+ ? [...new Set([...selectedChannel.models, modelId])]+ : selectedChannel.models.filter((id) => id !== modelId);+ updateChannel(selectedChannel.id, { models: next });+ }++ function addManualModel() {+ if (!selectedChannel) return;+ const id = manualModel.trim();+ if (!id) return;+ if (!selectedChannel.models.includes(id)) {+ updateChannel(selectedChannel.id, { models: [...selectedChannel.models, id] });+ }+ setManualModel("");}async function handleSave() {@@ -256,9 +297,14 @@ export function RoutingSettingsPanel() {api_key: apiKeyInputs[channel.id]?.trim() || undefined,api_format: channel.api_format,protocol: channel.protocol,- models: channel.id === ARK_VOLC_CHANNEL_ID- ? [...new Set([volcDraft.imageModel, volcDraft.image45Model, volcDraft.videoModel].filter(Boolean))]- : channel.models,+ models:+ channel.id === ARK_VOLC_CHANNEL_ID+ ? [+ ...new Set(+ [volcDraft.imageModel, volcDraft.image45Model, volcDraft.videoModel].filter(Boolean),+ ),+ ]+ : channel.models,enabled: channel.enabled,sort_order: channel.sort_order,})),@@ -319,7 +365,20 @@ export function RoutingSettingsPanel() {}return (- <SettingsTabShell onSave={() => void handleSave()} saving={saving} saveLabel="保存路由">+ <SettingsTabShell onSave={() => void handleSave()} saving={saving} saveLabel="保存">+ <SettingsSurface className="settings-readiness-bar">+ <div className="settings-readiness-title">路由就绪状态</div>+ <div className="settings-readiness-row">+ {readiness.map((item) => (+ <div key={item.id} className={cn("settings-readiness-item", item.ready && "is-ready")}>+ <span className={cn("settings-readiness-dot", item.ready ? "is-on" : "is-off")} />+ <span>{item.label}</span>+ <em>{item.ready ? (item.id === "secret" ? "已启用" : "已配置") : "未就绪"}</em>+ </div>+ ))}+ </div>+ </SettingsSurface>+{(data?.validation_errors.length ?? 0) > 0 ? (<SettingsSurface className="border-[#fde2e2] bg-[#fef0f0]"><div className="text-xs font-medium text-[#f56c6c]">配置校验</div>@@ -331,314 +390,320 @@ export function RoutingSettingsPanel() {</SettingsSurface>) : null}- <ArkVolcMediaPanel- channelId={ARK_VOLC_CHANNEL_ID}- hasApiKey={Boolean(arkVolcChannel?.has_api_key)}- apiKeyInput={apiKeyInputs[ARK_VOLC_CHANNEL_ID] ?? ""}- onApiKeyChange={(value) => setApiKeyInputs((prev) => ({ ...prev, [ARK_VOLC_CHANNEL_ID]: value }))}- draft={volcDraft}- onDraftChange={(patch) => setVolcDraft((prev) => ({ ...prev, ...patch }))}- />-- {!hasVideoChannel ? (- <SettingsSurface className="border-[#faecd8] bg-[#fdf6ec]">- <div className="text-xs font-medium text-[#e6a23c]">请在上方选择默认视频模型并保存</div>- </SettingsSurface>- ) : null}-- <SettingsPanel- className="settings-panel--compact"- title="其他上游渠道"- description="文本 LLM、语音 TTS 等"- >- <div className="mb-2 flex flex-wrap gap-1.5">- <button- type="button"- className="admin-quick-btn !inline-flex !w-auto !flex-row items-center gap-1.5 px-3 py-1.5 text-xs"- onClick={() => addPreset("text")}- >- <Type className="h-3.5 w-3.5" />- 添加文本渠道- </button>- <button- type="button"- className="admin-quick-btn !inline-flex !w-auto !flex-row items-center gap-1.5 px-3 py-1.5 text-xs"- onClick={() => addPreset("audio")}- >- <Mic className="h-3.5 w-3.5" />- 添加语音渠道- </button>- <button- type="button"- className="rounded-lg border border-dashed border-[#dcdfe6] px-3 py-1.5 text-xs text-[#606266] hover:border-[#67c23a]"- onClick={addChannel}- >- <Plus className="mr-1 inline h-3.5 w-3.5" />- 空白渠道- </button>- </div>-- <div className="grid gap-2 xl:grid-cols-[200px_minmax(0,1fr)]">- <div className="space-y-1.5">- {otherChannels.map((channel) => {+ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="1. 渠道管理"+ description="启用上游渠道并维护凭证"+ actions={+ <button type="button" className="admin-btn admin-btn-secondary settings-mini-btn" onClick={addChannel}>+ <Plus className="h-3.5 w-3.5" />+ 添加渠道+ </button>+ }+ >+ <div className="settings-channel-list">+ {channels.map((channel) => {const caps = channelCapabilities(channel);return (<buttonkey={channel.id}type="button"className={cn(- "w-full rounded-lg border px-2.5 py-1.5 text-left text-sm transition-colors",- selectedChannel?.id === channel.id- ? "border-[#67c23a] bg-[#f0f9eb]"- : "border-[#ebeef5] bg-white hover:border-[#dcdfe6]",+ "settings-channel-item",+ selectedChannel?.id === channel.id && "is-active",)}- onClick={() => setSelectedChannelId(channel.id)}+ onClick={() => {+ setSelectedChannelId(channel.id);+ setUpstreamModels([]);+ setManualModel("");+ }}>- <div className="font-medium text-[#303133]">{channel.name}</div>- <div className="mt-0.5 truncate font-mono text-[11px] text-[#909399]">{channel.id}</div>- <div className="mt-1.5 flex flex-wrap gap-1">+ <div className="settings-channel-item-top">+ <strong>{channel.name}</strong>+ <span+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ role="presentation"+ >+ <Switch+ checked={channel.enabled}+ onCheckedChange={(checked) => {+ updateChannel(channel.id, { enabled: checked });+ }}+ />+ </span>+ </div>+ <div className="settings-channel-item-meta">{caps.map((cap) => (- <span- key={cap}- className={cn(- "rounded px-1.5 py-0.5 text-[10px]",- cap === "video"- ? "bg-[#ecf5ff] text-[#409eff]"- : cap === "image"- ? "bg-[#f0f9eb] text-[#67c23a]"- : cap === "audio"- ? "bg-[#fdf6ec] text-[#e6a23c]"- : "bg-[#f4f4f5] text-[#909399]",- )}- >+ <span key={cap} className={cn("settings-cap-tag", `is-${cap}`)}>{CAPABILITY_LABELS[cap]}</span>))}- {!channel.enabled ? (- <span className="rounded bg-[#fef0f0] px-1.5 py-0.5 text-[10px] text-[#f56c6c]">停用</span>- ) : null}{channel.has_api_key ? (- <span className="rounded bg-[#f4f4f5] px-1.5 py-0.5 text-[10px] text-[#909399]">已有 Key</span>+ <span className="settings-cap-tag">已有 Key</span>) : (- <span className="rounded bg-[#fef0f0] px-1.5 py-0.5 text-[10px] text-[#f56c6c]">缺 Key</span>+ <span className="settings-cap-tag is-warn">缺 Key</span>)}</div></button>);})}+ {channels.length === 0 ? (+ <div className="settings-empty-hint">暂无渠道,点击右上角添加</div>+ ) : null}</div>+ </SettingsPanel>+ <SettingsPanel+ className="settings-panel--compact"+ title={`渠道配置${selectedChannel ? `(当前: ${selectedChannel.name})` : ""}`}+ description="密钥留空保存不修改;可用模型从上游拉取"+ actions={+ selectedChannel && selectedChannel.id !== ARK_VOLC_CHANNEL_ID ? (+ <button+ type="button"+ className="admin-btn admin-btn-danger settings-mini-btn"+ onClick={() => removeChannel(selectedChannel.id)}+ >+ <Trash2 className="h-3.5 w-3.5" />+ 删除+ </button>+ ) : null+ }+ >{selectedChannel ? (- <SettingsSurface>- <div className="mb-3 flex items-center justify-between gap-2">- <SectionTitle icon={<Plus className="h-4 w-4" />} title="渠道详情" />- <button- type="button"- className="rounded-lg border border-[#fde2e2] px-2 py-1 text-xs text-[#f56c6c]"- onClick={() => removeChannel(selectedChannel.id)}+ <div className="settings-field-grid">+ <LabeledControl label="名称">+ <input+ className="settings-input"+ value={selectedChannel.name}+ onChange={(e) => updateChannel(selectedChannel.id, { name: e.target.value })}+ />+ </LabeledControl>+ <LabeledControl label="协议">+ <select+ className="settings-select"+ value={selectedChannel.protocol}+ onChange={(e) =>+ updateChannel(selectedChannel.id, {+ protocol: e.target.value as AdminRoutingSettings["system_channels"][number]["protocol"],+ api_format:+ e.target.value === "ark"+ ? "ark"+ : selectedChannel.api_format === "ark"+ ? "openai"+ : selectedChannel.api_format,+ })+ }>- <Trash2 className="mr-1 inline h-3.5 w-3.5" />- 删除- </button>- </div>- {channelCapabilities(selectedChannel).includes("video") ? (- <div className="mb-3 rounded-lg border border-[#d9ecff] bg-[#ecf5ff] px-3 py-2 text-xs text-[#409eff]">- 当前为视频相关渠道:协议请保持 ARK,上游模型需含 seedance(如{" "}- <span className="font-mono">{DEFAULT_VIDEO_MODEL}</span>),并填写方舟 API Key。- </div>- ) : null}- <div className="settings-field-grid">- <LabeledControl label="名称">+ {Object.entries(PROTOCOL_LABELS).map(([value, label]) => (+ <option key={value} value={value}>+ {label}+ </option>+ ))}+ </select>+ </LabeledControl>+ <LabeledControl label="Base URL" className="settings-field-span-full">+ <input+ className="settings-input"+ value={selectedChannel.base_url}+ onChange={(e) => updateChannel(selectedChannel.id, { base_url: e.target.value })}+ placeholder={selectedChannel.protocol === "ark" ? ARK_BASE : "https://api.example.com/v1"}+ />+ </LabeledControl>+ <LabeledControl+ label="API Key"+ hint={selectedChannel.has_api_key ? "已保存,留空不修改" : "未配置"}+ className="settings-field-span-full"+ >+ <div className="settings-secret-row"><input- className="settings-input"- value={selectedChannel.name}- onChange={(e) => updateChannel(selectedChannel.id, { name: e.target.value })}- />- </LabeledControl>- <LabeledControl label="启用">- <select- className="settings-select"- value={selectedChannel.enabled ? "1" : "0"}+ className="settings-input is-secret"+ type="password"+ placeholder={selectedChannel.has_api_key ? "已保存,留空则不修改" : "输入 API Key"}+ value={selectedChannel.api_key_input}onChange={(e) =>- updateChannel(selectedChannel.id, { enabled: e.target.value === "1" })+ setApiKeyInputs((prev) => ({ ...prev, [selectedChannel.id]: e.target.value }))}+ />+ {selectedChannel.has_api_key || selectedChannel.api_key_input ? (+ <button+ type="button"+ className="admin-btn admin-btn-secondary settings-mini-btn"+ onClick={() => setApiKeyInputs((prev) => ({ ...prev, [selectedChannel.id]: "" }))}+ >+ 清除密钥+ </button>+ ) : null}+ </div>+ </LabeledControl>++ <LabeledControl+ className="settings-field-span-full"+ label="可用模型"+ hint={+ selectedChannel.protocol === "volc_tts"+ ? "TTS 请手动填写音色 ID"+ : "点击「从上游拉取」后勾选;也可手动追加"+ }+ >+ <div className="settings-model-toolbar">+ <button+ type="button"+ className="admin-btn admin-btn-secondary settings-mini-btn"+ disabled={fetchingModels || selectedChannel.protocol === "volc_tts"}+ onClick={() => void fetchUpstreamModels()}>- <option value="1">启用</option>- <option value="0">停用</option>- </select>- </LabeledControl>- <LabeledControl label="Base URL">+ {fetchingModels ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ 从上游拉取+ </button>+ <span className="settings-model-count">+ 已选 {selectedChannel.models.length}+ {upstreamModels.length > 0 ? ` / 上游 ${upstreamModels.length}` : ""}+ </span>+ </div>+ <div className="settings-model-catalog">+ {catalogModels.length === 0 ? (+ <div className="settings-empty-hint">+ {selectedChannel.protocol === "volc_tts"+ ? "在下方手动添加音色 ID"+ : "尚未拉取,请先配置 Key 后点击「从上游拉取」"}+ </div>+ ) : (+ catalogModels.map((model) => {+ const checked = selectedChannel.models.includes(model.id);+ return (+ <label key={model.id} className={cn("settings-model-option", checked && "is-checked")}>+ <input+ type="checkbox"+ checked={checked}+ onChange={(e) => toggleModel(model.id, e.target.checked)}+ />+ <span className="font-mono text-xs">{model.id}</span>+ <em className={cn("settings-cap-tag", `is-${model.capability}`)}>+ {CAPABILITY_LABELS[(model.capability as Capability) || "text"] || model.capability}+ </em>+ </label>+ );+ })+ )}+ </div>+ <div className="settings-model-manual"><inputclassName="settings-input"- value={selectedChannel.base_url}- onChange={(e) => updateChannel(selectedChannel.id, { base_url: e.target.value })}- placeholder={ARK_BASE}+ value={manualModel}+ onChange={(e) => setManualModel(e.target.value)}+ placeholder={+ selectedChannel.protocol === "volc_tts"+ ? "手动添加音色 ID"+ : `手动追加(如 ${DEFAULT_VIDEO_MODEL})`+ }+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ addManualModel();+ }+ }}/>- </LabeledControl>- <LabeledControl label="协议" hint="视频必须选 ARK">+ <button type="button" className="admin-btn admin-btn-secondary settings-mini-btn" onClick={addManualModel}>+ 添加+ </button>+ </div>+ </LabeledControl>+ </div>+ ) : (+ <div className="settings-empty-hint">请选择左侧渠道</div>+ )}+ </SettingsPanel>+ </div>++ <div className="settings-routing-grid">+ <ArkVolcMediaPanel+ channelId={ARK_VOLC_CHANNEL_ID}+ hasApiKey={Boolean(arkVolcChannel?.has_api_key)}+ apiKeyInput={apiKeyInputs[ARK_VOLC_CHANNEL_ID] ?? ""}+ onApiKeyChange={(value) => setApiKeyInputs((prev) => ({ ...prev, [ARK_VOLC_CHANNEL_ID]: value }))}+ draft={volcDraft}+ onDraftChange={(patch) => setVolcDraft((prev) => ({ ...prev, ...patch }))}+ />++ <SettingsPanel+ className="settings-panel--compact"+ title="3. 逻辑模型路由"+ description="能力 → 默认渠道 / 上游模型"+ >+ <div className="settings-field-grid settings-field-grid--2 mb-3">+ {(["text_model", "image_model", "video_model", "audio_model"] as const).map((key) => {+ const cap = key.replace("_model", "") as Capability;+ const options = (data?.logical_models ?? []).filter((model) => model.capability === cap);+ return (+ <LabeledControl key={key} label={`${CAPABILITY_LABELS[cap]}默认`}><selectclassName="settings-select"- value={selectedChannel.protocol}+ value={data?.default_models[key] ?? ""}onChange={(e) =>- updateChannel(selectedChannel.id, {- protocol: e.target.value as AdminRoutingSettings["system_channels"][number]["protocol"],- api_format:- e.target.value === "ark"- ? "ark"- : selectedChannel.api_format === "ark"- ? "openai"- : selectedChannel.api_format,- })+ setData((prev) =>+ prev+ ? {+ ...prev,+ default_models: { ...prev.default_models, [key]: e.target.value },+ }+ : prev,+ )}>- <option value="auto">自动</option>- <option value="openai">OpenAI(仅文本)</option>- <option value="ark">ARK(生图/视频)</option>- <option value="volc_tts">豆包 TTS</option>+ <option value="">未设置</option>+ {options.map((model) => (+ <option key={model.id} value={model.id}>+ {model.name || model.id}+ </option>+ ))}</select></LabeledControl>- <LabeledControl- label="API Key"- hint={selectedChannel.has_api_key ? "已保存,留空不修改" : "视频请填火山方舟 Key"}- >- <input- className="settings-input is-secret"- type="password"- placeholder={selectedChannel.has_api_key ? "已保存,留空则不修改" : "未配置"}- value={selectedChannel.api_key_input}- onChange={(e) =>- setApiKeyInputs((prev) => ({ ...prev, [selectedChannel.id]: e.target.value }))- }- />- </LabeledControl>- <LabeledControl- className="settings-field-span-full"- label="上游模型(每行一个)"- hint="视频示例:doubao-seedance-2-5-260628"- >- <textarea- className="settings-input min-h-[96px] py-2 font-mono text-xs"- value={selectedChannel.models.join("\n")}- onChange={(e) =>- updateChannel(selectedChannel.id, {- models: e.target.value- .split("\n")- .map((line) => line.trim())- .filter(Boolean),- })- }- />- </LabeledControl>- </div>- </SettingsSurface>- ) : null}- </div>- </SettingsPanel>-- <SettingsPanel- className="settings-panel--compact"- title="逻辑模型"- description="保存渠道后自动同步"- >- <div className="space-y-3">- {(["video", "image", "text", "audio"] as const).map((cap) => {- const models = (data?.logical_models ?? []).filter((m) => m.capability === cap);- if (models.length === 0 && cap !== "video") return null;- return (- <div key={cap}>- <div className="mb-2 text-xs font-medium text-[#909399]">- {CAPABILITY_LABELS[cap]}- {cap === "video" && models.length === 0 ? " · 暂无,请先添加并保存视频渠道" : ""}- </div>- {models.length === 0 && cap === "video" ? (- <SettingsSurface className="text-xs text-[#909399]">- 保存含 Seedance 的 ARK 渠道后,这里会出现视频逻辑模型。- </SettingsSurface>- ) : (- <div className="space-y-3">- {models.map((model) => (- <SettingsSurface key={model.id}>- <div className="flex flex-wrap items-center justify-between gap-2">- <div>- <div className="text-sm font-medium text-[#303133]">{model.name || model.id}</div>- <div className="font-mono text-[11px] text-[#909399]">- {model.id} · {CAPABILITY_LABELS[model.capability]}- </div>- </div>- </div>- <div className="mt-3 admin-table-wrap">- <table>- <thead>- <tr>- <th>渠道</th>- <th>上游模型</th>- <th>优先级</th>- </tr>- </thead>- <tbody>- {model.bindings.map((binding) => {- const channel = data?.system_channels.find(- (item) => item.id === binding.channel_id,- );- return (- <tr key={binding.id}>- <td>{channel?.name ?? binding.channel_id}</td>- <td className="font-mono text-xs">{binding.upstream_model}</td>- <td>{binding.priority}</td>- </tr>- );- })}- </tbody>- </table>- </div>- </SettingsSurface>- ))}- </div>+ );+ })}+ </div>+ <div className="admin-table-wrap settings-logic-table">+ <table>+ <thead>+ <tr>+ <th>能力</th>+ <th>默认渠道</th>+ <th>上游模型</th>+ <th>优先级</th>+ </tr>+ </thead>+ <tbody>+ {(data?.logical_models ?? []).flatMap((model) =>+ model.bindings.map((binding) => {+ const channel = data?.system_channels.find((item) => item.id === binding.channel_id);+ return (+ <tr key={`${model.id}-${binding.id}`}>+ <td>{CAPABILITY_LABELS[model.capability]}</td>+ <td>{channel?.name ?? binding.channel_id}</td>+ <td className="font-mono text-xs">{binding.upstream_model}</td>+ <td>{binding.priority}</td>+ </tr>+ );+ }),)}- </div>- );- })}- </div>- </SettingsPanel>-- <SettingsPanel className="settings-panel--compact" title="默认模型" description="各能力默认逻辑模型">- <div className="settings-field-grid settings-field-grid--4">- {(["text_model", "image_model", "video_model", "audio_model"] as const).map((key) => {- const cap = key.replace("_model", "") as Capability;- const options = (data?.logical_models ?? []).filter((model) => model.capability === cap);- return (- <LabeledControl key={key} label={CAPABILITY_LABELS[cap] + "默认"}>- <select- className="settings-select"- value={data?.default_models[key] ?? ""}- onChange={(e) =>- setData((prev) =>- prev- ? {- ...prev,- default_models: { ...prev.default_models, [key]: e.target.value },- }- : prev,- )- }- >- <option value="">未设置</option>- {options.map((model) => (- <option key={model.id} value={model.id}>- {model.name || model.id}- </option>- ))}- </select>- {key === "video_model" && options.length === 0 ? (- <div className="mt-1 text-[11px] text-[#e6a23c]">- 无视频逻辑模型(当前 {videoLogicalModels.length} 个)— 请添加视频渠道并保存- </div>+ {(data?.logical_models ?? []).every((m) => m.bindings.length === 0) ? (+ <tr>+ <td colSpan={4} className="text-center text-[#909399]">+ 保存渠道后将自动同步逻辑路由+ </td>+ </tr>) : null}- </LabeledControl>- );- })}- </div>- </SettingsPanel>+ </tbody>+ </table>+ </div>+ </SettingsPanel>+ </div></SettingsTabShell>);}diff --git a/admin/src/components/settings/RuntimeSettingsPanel.tsx b/admin/src/components/settings/RuntimeSettingsPanel.tsxindex aa83d4b..1644aa7 100644--- a/admin/src/components/settings/RuntimeSettingsPanel.tsx+++ b/admin/src/components/settings/RuntimeSettingsPanel.tsx@@ -1,10 +1,15 @@import { useCallback, useEffect, useMemo, useState } from "react";-import { Activity, CircleGauge, SlidersHorizontal, Sparkles } from "lucide-react";+import { Activity } from "lucide-react";import { toast } from "sonner";import { api, type AdminModelSettings } from "@/api/client";-import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsSurface, SettingsTabShell } from "@/components/settings/SettingsPanel";+import {+ LabeledControl,+ SettingsLoading,+ SettingsPanel,+ SettingsStatusBar,+ SettingsTabShell,+} from "@/components/settings/SettingsPanel";import { Switch } from "@/components/ui/switch";-import { cn } from "@/lib/utils";// 运行参数配置(并发、质量、Mock 等 flat 字段)export function RuntimeSettingsPanel() {@@ -28,8 +33,15 @@ export function RuntimeSettingsPanel() {void load();}, [load]);- const readinessReady = useMemo(- () => form?.readiness?.every((item) => item.ready) ?? false,+ const statusItems = useMemo(+ () =>+ (form?.readiness ?? []).map((item) => ({+ id: item.capability,+ label: item.label,+ ready: item.ready,+ readyText: item.model || "就绪",+ pendingText: "未就绪",+ })),[form?.readiness],);@@ -75,102 +87,187 @@ export function RuntimeSettingsPanel() {return (<SettingsTabShell onSave={() => void handleSave()} saving={saving}>- <SettingsSurface>- <SectionTitle icon={<Sparkles className="h-4 w-4" />} title="路由就绪状态" />- <div className="mt-2 flex flex-wrap items-center justify-between gap-2">- <span className={cn("admin-status-pill", readinessReady ? "is-done" : "is-warn")}>- {readinessReady ? "四类能力已就绪" : "请在「模型路由」补全渠道"}+ <SettingsStatusBar+ title="路由就绪状态"+ items={+ statusItems.length > 0+ ? statusItems+ : [{ id: "empty", label: "能力路由", ready: false, pendingText: "请先配置模型路由" }]+ }+ extra={+ <span className="settings-status-extra">+ {form.readiness?.every((item) => item.ready) ? "四类能力已就绪" : "请在「模型路由」补全渠道"}</span>- </div>- <div className="settings-readiness mt-2">- {(form.readiness ?? []).map((item) => (- <div key={item.capability} className={cn("settings-readiness-card", item.ready && "is-ready")}>- <div className="flex items-center justify-between gap-2">- <span className="text-sm font-medium">{item.label}</span>- <span className={cn("text-xs", item.ready ? "text-[#67c23a]" : "text-[#e6a23c]")}>- {item.ready ? "就绪" : "未就绪"}- </span>- </div>- <div className="mt-1 font-mono text-[11px] text-[#909399]">{item.model || "—"}</div>- <div className="mt-1 text-[11px] text-[#909399]">{item.message}</div>- </div>- ))}- </div>- </SettingsSurface>+ }+ />- <SettingsPanel title="质量与默认值" description="生图尺寸、视频清晰度、Seedance 时长与轮询">- <SectionTitle icon={<SlidersHorizontal className="h-4 w-4" />} title="生成默认值" />- <div className="settings-field-grid">+ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="1. 质量与默认值"+ description="生图尺寸、视频清晰度、Seedance 时长与轮询"+ >+ <div className="settings-field-grid"><LabeledControl label="默认生图尺寸">- <input className="settings-input" value={form.ark_image_size} onChange={(e) => patchField("ark_image_size", e.target.value)} />+ <input+ className="settings-input"+ value={form.ark_image_size}+ onChange={(e) => patchField("ark_image_size", e.target.value)}+ /></LabeledControl><LabeledControl label="默认视频清晰度">- <input className="settings-input" value={form.ark_video_resolution} onChange={(e) => patchField("ark_video_resolution", e.target.value)} />+ <input+ className="settings-input"+ value={form.ark_video_resolution}+ onChange={(e) => patchField("ark_video_resolution", e.target.value)}+ /></LabeledControl><LabeledControl label="默认视频比例">- <input className="settings-input" value={form.ark_video_ratio} onChange={(e) => patchField("ark_video_ratio", e.target.value)} />+ <input+ className="settings-input"+ value={form.ark_video_ratio}+ onChange={(e) => patchField("ark_video_ratio", e.target.value)}+ /></LabeledControl><LabeledControl label="Seedance 最小时长(秒)">- <input className="settings-input" type="number" min={1} value={form.seedance_duration_min} onChange={(e) => patchField("seedance_duration_min", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.seedance_duration_min}+ onChange={(e) => patchField("seedance_duration_min", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="Seedance 最大时长(秒)">- <input className="settings-input" type="number" min={1} value={form.seedance_duration_max} onChange={(e) => patchField("seedance_duration_max", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.seedance_duration_max}+ onChange={(e) => patchField("seedance_duration_max", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="视频轮询间隔(秒)">- <input className="settings-input" type="number" step="0.5" value={form.ark_video_poll_interval} onChange={(e) => patchField("ark_video_poll_interval", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ step="0.5"+ value={form.ark_video_poll_interval}+ onChange={(e) => patchField("ark_video_poll_interval", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="视频轮询超时(秒)">- <input className="settings-input" type="number" value={form.ark_video_poll_timeout} onChange={(e) => patchField("ark_video_poll_timeout", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ value={form.ark_video_poll_timeout}+ onChange={(e) => patchField("ark_video_poll_timeout", Number(e.target.value))}+ /></LabeledControl></div>- </SettingsPanel>+ </SettingsPanel>- <SettingsPanel title="并发与限制" description="管线并发、任务槽位与漫剧分镜上限">- <SectionTitle icon={<CircleGauge className="h-4 w-4" />} title="并发上限" />- <div className="settings-field-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="2. 并发与限制"+ description="管线并发、任务槽位与漫剧分镜上限"+ >+ <div className="settings-field-grid"><LabeledControl label="生图并发">- <input className="settings-input" type="number" min={1} value={form.pipeline_image_concurrency} onChange={(e) => patchField("pipeline_image_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.pipeline_image_concurrency}+ onChange={(e) => patchField("pipeline_image_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="视频并发">- <input className="settings-input" type="number" min={1} value={form.pipeline_video_concurrency} onChange={(e) => patchField("pipeline_video_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.pipeline_video_concurrency}+ onChange={(e) => patchField("pipeline_video_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="配音并发">- <input className="settings-input" type="number" min={1} value={form.pipeline_audio_concurrency} onChange={(e) => patchField("pipeline_audio_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.pipeline_audio_concurrency}+ onChange={(e) => patchField("pipeline_audio_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="任务平台槽位(全站)">- <input className="settings-input" type="number" min={1} value={form.task_runtime_max_concurrency} onChange={(e) => patchField("task_runtime_max_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.task_runtime_max_concurrency}+ onChange={(e) => patchField("task_runtime_max_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="单用户任务槽位">- <input className="settings-input" type="number" min={1} value={form.task_user_max_concurrency} onChange={(e) => patchField("task_user_max_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.task_user_max_concurrency}+ onChange={(e) => patchField("task_user_max_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="Selector 轮询并发">- <input className="settings-input" type="number" min={1} value={form.task_poll_max_concurrency} onChange={(e) => patchField("task_poll_max_concurrency", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.task_poll_max_concurrency}+ onChange={(e) => patchField("task_poll_max_concurrency", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="单用户漫剧视频在途上限">- <input className="settings-input" type="number" min={1} value={form.drama_user_video_job_limit} onChange={(e) => patchField("drama_user_video_job_limit", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.drama_user_video_job_limit}+ onChange={(e) => patchField("drama_user_video_job_limit", Number(e.target.value))}+ /></LabeledControl><LabeledControl label="分镜视频最大尝试次数">- <input className="settings-input" type="number" min={1} value={form.drama_fragment_max_attempts} onChange={(e) => patchField("drama_fragment_max_attempts", Number(e.target.value))} />+ <input+ className="settings-input"+ type="number"+ min={1}+ value={form.drama_fragment_max_attempts}+ onChange={(e) => patchField("drama_fragment_max_attempts", Number(e.target.value))}+ /></LabeledControl></div>- <div className="settings-toggle-row mt-2">- <div>- <strong>ARK Mock 模式</strong>- <span>开发环境模拟生成,不调用真实上游</span>+ <div className="settings-toggle-row mt-3">+ <div>+ <strong>ARK Mock 模式</strong>+ <span>开发环境模拟生成,不调用真实上游</span>+ </div>+ <Switch checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} /></div>- <Switch checked={form.ark_mock} onCheckedChange={(v) => patchField("ark_mock", v)} />- </div>- </SettingsPanel>+ </SettingsPanel>+ </div>- <SettingsPanel title="运行时" description="Worker 槽位与 Selector 轮询">- <div className="flex flex-col gap-1.5 text-sm text-[#606266]">- <div className="flex items-center gap-2">- <Activity className="h-3.5 w-3.5 text-[#67c23a]" />- Worker 槽位 {form.task_runtime_max_concurrency} · 单用户 {form.task_user_max_concurrency}+ <SettingsPanel className="settings-panel--compact" title="3. 运行时摘要" description="当前生效的 Worker / Selector 槽位">+ <div className="settings-runtime-summary">+ <div className="settings-runtime-summary-row">+ <Activity className="h-4 w-4 text-[var(--admin-forest)]" />+ <span>+ Worker 槽位 <strong>{form.task_runtime_max_concurrency}</strong> · 单用户{" "}+ <strong>{form.task_user_max_concurrency}</strong>+ </span></div>- <div className="text-xs text-[#909399]">+ <p className="settings-runtime-summary-hint">Selector 每轮最多 {form.task_poll_max_concurrency} 路上游非阻塞查询;awaiting_poll 不计入 Worker 占用。- </div>+ </p></div></SettingsPanel></SettingsTabShell>diff --git a/admin/src/components/settings/SecretField.tsx b/admin/src/components/settings/SecretField.tsxindex ee01ef8..e82b9eb 100644--- a/admin/src/components/settings/SecretField.tsx+++ b/admin/src/components/settings/SecretField.tsx@@ -36,7 +36,7 @@ export function SecretField({autoComplete="new-password"/>{configured && onClear ? (- <button type="button" className="admin-quick-btn shrink-0 px-3 text-xs" onClick={onClear}>+ <button type="button" className="admin-btn admin-btn-secondary settings-mini-btn" onClick={onClear}>清除</button>) : null}diff --git a/admin/src/components/settings/SettingsPanel.tsx b/admin/src/components/settings/SettingsPanel.tsxindex 9c36155..b15443d 100644--- a/admin/src/components/settings/SettingsPanel.tsx+++ b/admin/src/components/settings/SettingsPanel.tsx@@ -1,6 +1,8 @@import type { ReactNode } from "react";-import { Loader2, Save } from "lucide-react";+import { useEffect, useRef } from "react";+import { Loader2 } from "lucide-react";import { cn } from "@/lib/utils";+import { useSettingsSaveSlot } from "@/components/settings/SettingsSaveContext";type PanelProps = {title: string;@@ -33,23 +35,27 @@ type SettingsTabShellProps = {saveLabel?: string;};-// Tab 内容区:右上角统一保存按钮+// Tab 内容区:把保存动作注册到页头,不再单独占一行工具条export function SettingsTabShell({ children, onSave, saving, saveLabel = "保存" }: SettingsTabShellProps) {+ const { registerSave } = useSettingsSaveSlot();+ const onSaveRef = useRef(onSave);+ onSaveRef.current = onSave;++ useEffect(() => {+ if (!onSave) {+ registerSave(null);+ return () => registerSave(null);+ }+ registerSave({+ onSave: () => onSaveRef.current?.(),+ saving,+ label: saveLabel,+ });+ return () => registerSave(null);+ }, [onSave ? true : false, saving, saveLabel, registerSave]);+return (<div className="settings-tab-shell">- {onSave ? (- <div className="settings-tab-toolbar">- <button- type="button"- className="admin-quick-btn settings-save-btn"- disabled={saving}- onClick={() => void onSave()}- >- {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}- {saveLabel}- </button>- </div>- ) : null}<div className="settings-tab-body">{children}</div></div>);@@ -100,3 +106,40 @@ export function LabeledControl({export function SettingsSurface({ children, className = "" }: { children: ReactNode; className?: string }) {return <div className={cn("settings-surface", className)}>{children}</div>;}++export type SettingsStatusItem = {+ id: string;+ label: string;+ ready: boolean;+ readyText?: string;+ pendingText?: string;+};++// 顶部就绪/状态条(与模型路由一致)+export function SettingsStatusBar({+ title,+ items,+ extra,+}: {+ title: string;+ items: SettingsStatusItem[];+ extra?: ReactNode;+}) {+ return (+ <SettingsSurface className="settings-readiness-bar">+ <div className="settings-readiness-title-row">+ <div className="settings-readiness-title">{title}</div>+ {extra}+ </div>+ <div className="settings-readiness-row">+ {items.map((item) => (+ <div key={item.id} className={cn("settings-readiness-item", item.ready && "is-ready")}>+ <span className={cn("settings-readiness-dot", item.ready ? "is-on" : "is-off")} />+ <span>{item.label}</span>+ <em>{item.ready ? item.readyText ?? "已配置" : item.pendingText ?? "未就绪"}</em>+ </div>+ ))}+ </div>+ </SettingsSurface>+ );+}diff --git a/admin/src/components/settings/SettingsSaveContext.tsx b/admin/src/components/settings/SettingsSaveContext.tsxnew file mode 100644index 0000000..8c59dcd--- /dev/null+++ b/admin/src/components/settings/SettingsSaveContext.tsx@@ -0,0 +1,62 @@+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";++export type SettingsSaveAction = {+ onSave: () => void | Promise<void>;+ saving?: boolean;+ label?: string;+};++type SettingsSaveContextValue = {+ action: SettingsSaveAction | null;+ registerSave: (action: SettingsSaveAction | null) => void;+};++const SettingsSaveContext = createContext<SettingsSaveContextValue | null>(null);++// 设置页:子 Tab 注册保存动作,页头渲染统一「保存」按钮+export function SettingsSaveProvider({ children }: { children: ReactNode }) {+ const [action, setAction] = useState<SettingsSaveAction | null>(null);+ const registerSave = useCallback((next: SettingsSaveAction | null) => {+ setAction((prev) => {+ if (!prev && !next) return prev;+ if (+ prev &&+ next &&+ prev.saving === next.saving &&+ (prev.label ?? "保存") === (next.label ?? "保存")+ ) {+ // 同步最新 onSave,避免闭包过期;不触发无意义重渲染依赖+ prev.onSave = next.onSave;+ return prev;+ }+ return next;+ });+ }, []);+ const value = useMemo(() => ({ action, registerSave }), [action, registerSave]);+ return <SettingsSaveContext.Provider value={value}>{children}</SettingsSaveContext.Provider>;+}++export function useSettingsSaveSlot() {+ const ctx = useContext(SettingsSaveContext);+ if (!ctx) {+ throw new Error("useSettingsSaveSlot must be used within SettingsSaveProvider");+ }+ return ctx;+}++// Tab 挂载时注册保存;卸载时清空+export function useRegisterSettingsSave(action: SettingsSaveAction | null) {+ const { registerSave } = useSettingsSaveSlot();+ useEffect(() => {+ registerSave(action);+ return () => registerSave(null);+ }, [action, registerSave]);+}diff --git a/admin/src/components/settings/SiteSettingsPanel.tsx b/admin/src/components/settings/SiteSettingsPanel.tsxindex fda8bee..a594ae6 100644--- a/admin/src/components/settings/SiteSettingsPanel.tsx+++ b/admin/src/components/settings/SiteSettingsPanel.tsx@@ -1,5 +1,10 @@-import { Globe, Wrench } from "lucide-react";-import { LabeledControl, SectionTitle, SettingsLoading, SettingsPanel, SettingsTabShell } from "@/components/settings/SettingsPanel";+import {+ LabeledControl,+ SettingsLoading,+ SettingsPanel,+ SettingsStatusBar,+ SettingsTabShell,+} from "@/components/settings/SettingsPanel";import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";// 站点 URL 与本地工具路径@@ -22,45 +27,88 @@ export function SiteSettingsPanel() {return <SettingsLoading />;}+ const hasPublic = Boolean(form.public_base_url?.trim());+ const hasFfmpeg = Boolean(form.ffmpeg_path?.trim());+ const hasFfprobe = Boolean(form.ffprobe_path?.trim());+return (<SettingsTabShell onSave={() => void handleSave()} saving={saving}>- <SettingsPanel title="公网地址" description="支付回调、分享链接与 OSS 回填">- <SectionTitle icon={<Globe className="h-4 w-4" />} title="PUBLIC_BASE_URL" />- <div className="settings-field-grid">- <LabeledControl label="后端公网基址" hint="例:https://api.example.com">- <input- className="settings-input"- value={form.public_base_url}- onChange={(e) => patchField("public_base_url", e.target.value)}- />- </LabeledControl>- </div>- <p className="mt-2 text-xs leading-relaxed text-[#909399]">- 数据库、Redis、SECRET_KEY 等基础设施仍通过服务器环境变量配置,不在此页修改。- </p>- </SettingsPanel>+ <SettingsStatusBar+ title="站点工具状态"+ items={[+ {+ id: "public",+ label: "公网地址",+ ready: hasPublic,+ readyText: "已配置",+ pendingText: "未填写",+ },+ {+ id: "ffmpeg",+ label: "ffmpeg",+ ready: hasFfmpeg,+ readyText: form.ffmpeg_path || "已配置",+ pendingText: "使用默认 PATH",+ },+ {+ id: "ffprobe",+ label: "ffprobe",+ ready: hasFfprobe,+ readyText: form.ffprobe_path || "已配置",+ pendingText: "使用默认 PATH",+ },+ ]}+ />++ <div className="settings-routing-grid">+ <SettingsPanel+ className="settings-panel--compact"+ title="1. 公网地址"+ description="支付回调、分享链接与 OSS 回填"+ >+ <div className="settings-field-grid">+ <LabeledControl+ label="后端公网基址"+ hint="例:https://www.printfilm.com"+ className="settings-field-span-full"+ >+ <input+ className="settings-input"+ value={form.public_base_url}+ onChange={(e) => patchField("public_base_url", e.target.value)}+ />+ </LabeledControl>+ </div>+ <p className="settings-panel-footnote">+ 数据库、Redis、SECRET_KEY 等基础设施仍通过服务器环境变量配置,不在此页修改。+ </p>+ </SettingsPanel>- <SettingsPanel title="媒体工具" description="合成与抽帧依赖本机 ffmpeg / ffprobe">- <SectionTitle icon={<Wrench className="h-4 w-4" />} title="FFmpeg" />- <div className="settings-field-grid">- <LabeledControl label="ffmpeg 路径">- <input- className="settings-input"- placeholder="ffmpeg"- value={form.ffmpeg_path}- onChange={(e) => patchField("ffmpeg_path", e.target.value)}- />- </LabeledControl>- <LabeledControl label="ffprobe 路径">- <input- className="settings-input"- placeholder="ffprobe"- value={form.ffprobe_path}- onChange={(e) => patchField("ffprobe_path", e.target.value)}- />- </LabeledControl>- </div>- </SettingsPanel>+ <SettingsPanel+ className="settings-panel--compact"+ title="2. 媒体工具"+ description="合成与抽帧依赖本机 ffmpeg / ffprobe"+ >+ <div className="settings-field-grid">+ <LabeledControl label="ffmpeg 路径">+ <input+ className="settings-input"+ placeholder="ffmpeg"+ value={form.ffmpeg_path}+ onChange={(e) => patchField("ffmpeg_path", e.target.value)}+ />+ </LabeledControl>+ <LabeledControl label="ffprobe 路径">+ <input+ className="settings-input"+ placeholder="ffprobe"+ value={form.ffprobe_path}+ onChange={(e) => patchField("ffprobe_path", e.target.value)}+ />+ </LabeledControl>+ </div>+ </SettingsPanel>+ </div></SettingsTabShell>);}diff --git a/admin/src/components/tasks/TaskDetailDialog.tsx b/admin/src/components/tasks/TaskDetailDialog.tsxindex 49630de..646f03c 100644--- a/admin/src/components/tasks/TaskDetailDialog.tsx+++ b/admin/src/components/tasks/TaskDetailDialog.tsx@@ -1,10 +1,19 @@-import { useEffect, useMemo, useState } from "react";+import {+ Children,+ isValidElement,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";import { Ban, Loader2, RefreshCw } from "lucide-react";import { toast } from "sonner";import { api, type AdminTaskDetail } from "@/api/client";+import { AdminEntityLink } from "@/components/admin/AdminEntityLink";import { AdminModal } from "@/components/admin/AdminModal";import { Button } from "@/components/ui/button";import { taskDomainLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";+import { hasJsonContent, prettyJson } from "@/lib/jsonPreview";import { cn, fenToYuan } from "@/lib/utils";type TaskDetailDialogProps = {@@ -18,6 +27,28 @@ type DetailTab = "overview" | "billing" | "steps" | "events" | "json";const TERMINAL = new Set(["succeeded", "failed", "cancelled"]);+const PAYLOAD_FIELD_LABELS: Record<string, string> = {+ prompt: "提示词",+ name: "名称",+ kind: "类型",+ model_id: "模型",+ image_style_id: "风格",+ aspect_ratio: "画幅",+ resolution: "分辨率",+ duration_sec: "时长(秒)",+ duration: "时长",+ force: "强制重跑",+ total: "总数",+ project_id: "科普项目 ID",+ user_id: "用户 ID",+ asset_id: "资产 ID",+ episode_count: "集数",+ phase: "阶段",+ sync: "同步",+ refresh_prompts: "刷新提示词",+ reextract_props: "重抽道具",+};+// 格式化时间为本地字符串function fmtTime(value: string | null | undefined): string {if (!value) return "—";@@ -26,12 +57,7 @@ function fmtTime(value: string | null | undefined): string {// 美化 JSON 展示function fmtJson(value: unknown): string {- if (value == null) return "—";- try {- return JSON.stringify(value, null, 2);- } catch {- return String(value);- }+ return prettyJson(value);}// 状态 pill 样式@@ -43,6 +69,59 @@ function statusClass(status: string): string {return "is-warn";}+// 仅在有值时渲染一行定义列表项+function DlRow({ label, children }: { label: string; children: ReactNode }) {+ if (children == null || children === "" || children === "—") return null;+ return (+ <div>+ <dt>{label}</dt>+ <dd>{children}</dd>+ </div>+ );+}++// DlRow 未渲染时 children 仍是元素描述符;按 props 判断是否会出内容。+function dlRowWillShow(child: ReactNode): boolean {+ if (child == null || child === false) return false;+ if (!isValidElement(child)) return Boolean(child);+ if (child.type !== DlRow) return true;+ const c = (child.props as { children?: ReactNode }).children;+ return c != null && c !== "" && c !== "—";+}++// 有内容才包一层 section,避免「标识」等空壳标题+function DetailSection({ title, children }: { title: string; children: ReactNode }) {+ const visible = Children.toArray(children).filter(dlRowWillShow);+ if (visible.length === 0) return null;+ return (+ <section className="task-detail-section">+ <h4>{title}</h4>+ <dl className="task-detail-dl">{visible}</dl>+ </section>+ );+}++// 从 payload 抽出可读字段摘要(其余仍看下方 JSON)+function payloadSummaryRows(+ payload: Record<string, unknown> | null | undefined,+): Array<{ key: string; label: string; value: string }> {+ if (!payload || typeof payload !== "object") return [];+ const rows: Array<{ key: string; label: string; value: string }> = [];+ for (const [key, label] of Object.entries(PAYLOAD_FIELD_LABELS)) {+ if (!(key in payload)) continue;+ const raw = payload[key];+ if (raw == null || raw === "") continue;+ if (typeof raw === "boolean") {+ rows.push({ key, label, value: raw ? "是" : "否" });+ continue;+ }+ const text = String(raw).trim();+ if (!text) continue;+ rows.push({ key, label, value: text.length > 240 ? `${text.slice(0, 240)}…` : text });+ }+ return rows;+}+// 任务详情弹窗:概览 / 步骤 / 事件 / 原始 JSONexport function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: TaskDetailDialogProps) {const [task, setTask] = useState<AdminTaskDetail | null>(null);@@ -81,6 +160,8 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Tareturn task.status === "pending" && !task.next_action_at && Boolean(task.batch_key);}, [task]);+ const payloadRows = useMemo(() => payloadSummaryRows(task?.payload ?? null), [task?.payload]);+async function handleCancel() {if (!task || !canCancel) return;if (!window.confirm(`确定取消任务 #${task.id}?`)) return;@@ -184,84 +265,57 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta{task.current_step_status ? ` · ${task.current_step_status}` : ""}</p>) : null}- {task.error_message ? (- <pre className="task-detail-error">{task.error_message}</pre>+ {task.error_code || task.error_message ? (+ <pre className="task-detail-error">+ {[task.error_code, task.error_message].filter(Boolean).join(" · ")}+ </pre>) : null}</section>- <section className="task-detail-section">- <h4>调度</h4>- <dl className="task-detail-dl">- <div>- <dt>优先级</dt>- <dd>{task.priority}</dd>- </div>- <div>- <dt>next_action_at</dt>- <dd>{fmtTime(task.next_action_at)}</dd>- </div>- <div>- <dt>scheduled_at</dt>- <dd>{fmtTime(task.scheduled_at)}</dd>- </div>- <div>- <dt>租约到期</dt>- <dd>{fmtTime(task.lease_until)}</dd>- </div>- <div>- <dt>provider_task_id</dt>- <dd className="font-mono text-xs">{task.provider_task_id ?? "—"}</dd>- </div>- </dl>- </section>+ <DetailSection title="调度">+ <DlRow label="优先级">{task.priority}</DlRow>+ <DlRow label="scheduled_at">{task.scheduled_at ? fmtTime(task.scheduled_at) : null}</DlRow>+ <DlRow label="next_action_at">{task.next_action_at ? fmtTime(task.next_action_at) : null}</DlRow>+ <DlRow label="租约到期">{task.lease_until ? fmtTime(task.lease_until) : null}</DlRow>+ <DlRow label="provider_task_id">+ {task.provider_task_id ? (+ <span className="font-mono text-xs break-all">{task.provider_task_id}</span>+ ) : null}+ </DlRow>+ </DetailSection>- <section className="task-detail-section">- <h4>关联实体</h4>- <dl className="task-detail-dl">- <div>- <dt>用户</dt>- <dd>{task.user_email ?? `#${task.requested_by}`}</dd>- </div>- <div>- <dt>漫剧项目</dt>- <dd>{task.drama_project_id ?? "—"}</dd>- </div>- <div>- <dt>分集</dt>- <dd>{task.episode_id ?? "—"}</dd>- </div>- <div>- <dt>分镜</dt>- <dd>{task.fragment_id ?? "—"}</dd>- </div>- <div>- <dt>科普项目</dt>- <dd>{task.project_id ?? "—"}</dd>- </div>- <div>- <dt>镜头</dt>- <dd>{task.shot_id ?? "—"}</dd>- </div>- </dl>- </section>+ <DetailSection title="关联实体">+ <DlRow label="用户">+ <AdminEntityLink kind="user" id={task.requested_by} label={task.user_email ?? undefined} />+ </DlRow>+ <DlRow label="漫剧项目">+ {task.drama_project_id ? <AdminEntityLink kind="drama" id={task.drama_project_id} /> : null}+ </DlRow>+ <DlRow label="资产">+ {task.asset_id ? <AdminEntityLink kind="drama_asset" id={task.asset_id} /> : null}+ </DlRow>+ <DlRow label="剧本">{task.script_id ? `#${task.script_id}` : null}</DlRow>+ <DlRow label="分集">{task.episode_id ? `#${task.episode_id}` : null}</DlRow>+ <DlRow label="分镜">{task.fragment_id ? `#${task.fragment_id}` : null}</DlRow>+ <DlRow label="科普项目">+ {task.project_id ? <AdminEntityLink kind="project" id={task.project_id} /> : null}+ </DlRow>+ <DlRow label="镜头">{task.shot_id ? `#${task.shot_id}` : null}</DlRow>+ </DetailSection>- <section className="task-detail-section">- <h4>标识</h4>- <dl className="task-detail-dl">- <div>- <dt>batch_key</dt>- <dd className="font-mono text-xs break-all">{task.batch_key ?? "—"}</dd>- </div>- <div>- <dt>dedupe_key</dt>- <dd className="font-mono text-xs break-all">{task.dedupe_key ?? "—"}</dd>- </div>- <div>- <dt>client_request_id</dt>- <dd className="font-mono text-xs break-all">{task.client_request_id ?? "—"}</dd>- </div>- </dl>- </section>+ <DetailSection title="标识">+ <DlRow label="dedupe_key">+ {task.dedupe_key ? <span className="font-mono text-xs break-all">{task.dedupe_key}</span> : null}+ </DlRow>+ <DlRow label="batch_key">+ {task.batch_key ? <span className="font-mono text-xs break-all">{task.batch_key}</span> : null}+ </DlRow>+ <DlRow label="client_request_id">+ {task.client_request_id ? (+ <span className="font-mono text-xs break-all">{task.client_request_id}</span>+ ) : null}+ </DlRow>+ </DetailSection><section className="task-detail-section task-detail-section--full"><h4>时间线</h4>@@ -285,12 +339,35 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta</dl></section>- {task.result_payload && Object.keys(task.result_payload).length > 0 ? (- <section className="task-detail-section task-detail-section--full">- <h4>结果摘要</h4>+ <section className="task-detail-section task-detail-section--full">+ <h4>提交参数</h4>+ {payloadRows.length > 0 ? (+ <dl className="task-detail-dl task-detail-dl--payload mb-3">+ {payloadRows.map((row) => (+ <div key={row.key}>+ <dt>{row.label}</dt>+ <dd className={row.key === "prompt" ? "whitespace-pre-wrap break-words" : "break-all"}>+ {row.value}+ </dd>+ </div>+ ))}+ </dl>+ ) : null}+ {hasJsonContent(task.payload) ? (+ <pre className="task-detail-json">{fmtJson(task.payload)}</pre>+ ) : (+ <p className="task-detail-meta">无提交参数</p>+ )}+ </section>++ <section className="task-detail-section task-detail-section--full">+ <h4>结果</h4>+ {hasJsonContent(task.result_payload) ? (<pre className="task-detail-json">{fmtJson(task.result_payload)}</pre>- </section>- ) : null}+ ) : (+ <p className="task-detail-meta">暂无结果(未完成或未回写 result_payload)</p>+ )}+ </section></div>) : null}diff --git a/admin/src/index.css b/admin/src/index.cssindex 3c69f39..655fe28 100644--- a/admin/src/index.css+++ b/admin/src/index.css@@ -2592,10 +2592,26 @@ textarea.admin-control {.settings-page {display: flex;flex-direction: column;- gap: 10px;+ gap: 14px;min-height: 0;}+.settings-page-hero {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px 16px;+}++.settings-page-title {+ margin: 0 0 4px;+ font-size: 22px;+ font-weight: 700;+ letter-spacing: -0.02em;+ color: #0f1c17;+}+.settings-head {display: flex;flex-wrap: wrap;@@ -2611,41 +2627,62 @@ textarea.admin-control {.settings-head-desc {margin: 0;flex: 1 1 220px;- font-size: 12px;- line-height: 1.45;+ font-size: 13px;+ line-height: 1.5;color: var(--admin-muted);}.settings-tabs {display: flex;flex-wrap: wrap;- gap: 6px;+ gap: 4px;+ padding: 4px;+ border-radius: 12px;+ background: #fff;+ border: 1px solid var(--admin-border);+ box-shadow: var(--admin-shadow);}.settings-tab {- min-height: 32px;- padding: 0 12px;- font-size: 12px;+ min-height: 36px;+ padding: 0 16px;+ border: 0;+ border-radius: 9px;+ background: transparent;+ color: var(--admin-muted);+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+}++.settings-tab:hover {+ color: var(--admin-text);+ background: #f3f6f4;+}++.settings-tab.is-active {+ background: var(--admin-forest);+ color: #f7faf8;+ box-shadow: 0 4px 12px rgba(31, 92, 72, 0.28);}.settings-main {display: flex;flex-direction: column;- gap: 10px;+ gap: 12px;min-width: 0;}.settings-tab-shell {display: flex;flex-direction: column;- gap: 10px;+ gap: 12px;min-width: 0;}.settings-tab-toolbar {- display: flex;- justify-content: flex-end;- gap: 8px;+ display: none;}.settings-save-btn {@@ -2653,15 +2690,25 @@ textarea.admin-control {width: auto !important;align-items: center;gap: 6px;- min-height: 32px;- padding: 0 12px !important;+ min-height: 34px;+ padding: 0 14px !important;+ font-size: 13px;+}++.settings-mini-btn {+ display: inline-flex !important;+ width: auto !important;+ align-items: center;+ gap: 6px;+ min-height: 30px;+ padding: 0 10px;font-size: 12px;}.settings-tab-body {display: flex;flex-direction: column;- gap: 10px;+ gap: 12px;min-width: 0;}@@ -2678,6 +2725,310 @@ textarea.admin-control {color: var(--admin-muted);}+.settings-readiness-bar {+ padding: 12px 14px !important;+}++.settings-readiness-title {+ margin-bottom: 0;+ font-size: 12px;+ font-weight: 600;+ color: #303133;+}++.settings-readiness-title-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ margin-bottom: 10px;+}++.settings-status-extra {+ font-size: 11px;+ color: #909399;+}++.settings-subsection-title {+ margin: 14px 0 8px;+ font-size: 12px;+ font-weight: 600;+ color: #303133;+}++.settings-panel-footnote {+ margin: 12px 0 0;+ font-size: 12px;+ line-height: 1.5;+ color: #909399;+}++.settings-runtime-summary {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.settings-runtime-summary-row {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+ color: #303133;+}++.settings-runtime-summary-hint {+ margin: 0;+ font-size: 12px;+ line-height: 1.5;+ color: #909399;+}++.settings-inline-switch {+ display: flex;+ align-items: center;+ min-height: 32px;+}++.settings-page .settings-toggle-row {+ padding: 10px 12px;+ border: 1px solid var(--admin-border);+ border-radius: 10px;+ background: #f8faf9;+ gap: 12px;+}++.settings-page .settings-panel {+ border: 1px solid var(--admin-border);+ box-shadow: var(--admin-shadow);+}++.settings-page .settings-panel-header {+ background: #f7faf8;+}++.settings-readiness-row {+ display: flex;+ flex-wrap: wrap;+ gap: 8px 18px;+}++.settings-readiness-item {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: #606266;+}++.settings-readiness-item em {+ font-style: normal;+ color: #909399;+ font-size: 11px;+}++.settings-readiness-item.is-ready em {+ color: var(--admin-forest);+}++.settings-readiness-dot {+ width: 8px;+ height: 8px;+ border-radius: 999px;+ background: #d1d5db;+}++.settings-readiness-dot.is-on {+ background: #22c55e;+ box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.18);+}++.settings-readiness-dot.is-off {+ background: #f59e0b;+}++.settings-routing-grid {+ display: grid;+ gap: 12px;+ grid-template-columns: minmax(280px, 0.9fr) minmax(0, 1.2fr);+ align-items: stretch;+}++@media (max-width: 1100px) {+ .settings-routing-grid {+ grid-template-columns: 1fr;+ }+}++.settings-routing-grid > .settings-panel {+ height: 100%;+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.settings-routing-grid > .settings-panel .settings-panel-body {+ flex: 1 1 auto;+ min-height: 0;+ display: flex;+ flex-direction: column;+}++.settings-channel-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ flex: 1 1 auto;+ min-height: 240px;+ max-height: none;+ overflow: auto;+}++.settings-channel-item {+ width: 100%;+ text-align: left;+ border: 1px solid var(--admin-border);+ border-radius: 12px;+ background: #fff;+ padding: 10px 12px;+ cursor: pointer;+ transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;+}++.settings-channel-item:hover {+ border-color: #c5d4cc;+}++.settings-channel-item.is-active {+ border-color: rgba(31, 92, 72, 0.45);+ background: #f3faf6;+ box-shadow: 0 0 0 3px var(--admin-accent-ring);+}++.settings-channel-item-top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}++.settings-channel-item-top strong {+ font-size: 13px;+ color: #1f2937;+}++.settings-channel-item-meta {+ margin-top: 8px;+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+}++.settings-cap-tag {+ display: inline-flex;+ align-items: center;+ border-radius: 999px;+ padding: 1px 8px;+ font-size: 10px;+ background: #f4f4f5;+ color: #71717a;+}++.settings-cap-tag.is-text {+ background: #f4f4f5;+ color: #71717a;+}++.settings-cap-tag.is-image {+ background: #ecfdf3;+ color: #067647;+}++.settings-cap-tag.is-video {+ background: #eff6ff;+ color: #1d4ed8;+}++.settings-cap-tag.is-audio {+ background: #fff7ed;+ color: #c2410c;+}++.settings-cap-tag.is-warn {+ background: #fef2f2;+ color: #dc2626;+}++.settings-secret-row,+.settings-model-manual,+.settings-model-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+}++.settings-secret-row .settings-input,+.settings-model-manual .settings-input {+ flex: 1 1 180px;+}++.settings-model-count {+ font-size: 11px;+ color: #909399;+}++.settings-model-catalog {+ margin-top: 8px;+ max-height: 220px;+ overflow: auto;+ border: 1px solid var(--admin-border);+ border-radius: 10px;+ background: #fafbfc;+ padding: 6px;+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.settings-model-option {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ border-radius: 8px;+ cursor: pointer;+}++.settings-model-option:hover,+.settings-model-option.is-checked {+ background: #fff;+}++.settings-model-option input {+ accent-color: var(--admin-forest);+}++.settings-model-manual {+ margin-top: 8px;+}++.settings-empty-hint {+ padding: 16px 8px;+ text-align: center;+ font-size: 12px;+ color: #909399;+}++.settings-logic-table {+ margin-top: 4px;+}++.settings-field-grid--2 {+ grid-template-columns: repeat(2, minmax(0, 1fr));+}+.settings-readiness {display: grid;gap: 8px;@@ -3493,8 +3844,30 @@ textarea.admin-control {grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));}-.task-detail-dl--inline > div {- grid-template-columns: 1fr;+.task-detail-dl--payload > div {+ grid-template-columns: 100px 1fr;+}++.task-detail-dl--payload dd {+ font-size: 12px;+ line-height: 1.5;+}++.task-list-json-cell {+ max-width: 180px;+ vertical-align: top;+}++.task-list-json {+ margin: 0;+ max-width: 180px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 10px;+ line-height: 1.4;+ color: #606266;}.task-detail-json {diff --git a/admin/src/lib/jsonPreview.ts b/admin/src/lib/jsonPreview.tsnew file mode 100644index 0000000..e81dbfd--- /dev/null+++ b/admin/src/lib/jsonPreview.ts@@ -0,0 +1,43 @@+/** Compact JSON preview for admin task list / tooltips. */++// 将对象压成单行摘要;空值返回 —+export function compactJsonPreview(value: unknown, maxLen = 96): string {+ if (value == null) return "—";+ if (typeof value === "string") {+ const t = value.trim();+ if (!t) return "—";+ return t.length > maxLen ? `${t.slice(0, maxLen)}…` : t;+ }+ if (typeof value !== "object") {+ const s = String(value);+ return s.length > maxLen ? `${s.slice(0, maxLen)}…` : s;+ }+ if (Array.isArray(value) && value.length === 0) return "[]";+ if (!Array.isArray(value) && Object.keys(value as object).length === 0) return "—";+ try {+ const s = JSON.stringify(value);+ if (!s || s === "{}" || s === "[]") return "—";+ return s.length > maxLen ? `${s.slice(0, maxLen)}…` : s;+ } catch {+ return "—";+ }+}++// 美化多行 JSON(详情弹窗)+export function prettyJson(value: unknown): string {+ if (value == null) return "—";+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);+ }+}++// 是否有可展示的 JSON 内容+export function hasJsonContent(value: unknown): boolean {+ if (value == null) return false;+ if (typeof value === "string") return value.trim().length > 0;+ if (Array.isArray(value)) return value.length > 0;+ if (typeof value === "object") return Object.keys(value as object).length > 0;+ return true;+}diff --git a/admin/src/pages/QueuesPage.tsx b/admin/src/pages/QueuesPage.tsxindex 6ebed65..218c8fd 100644--- a/admin/src/pages/QueuesPage.tsx+++ b/admin/src/pages/QueuesPage.tsx@@ -11,6 +11,7 @@ import { TaskDetailDialog } from "@/components/tasks/TaskDetailDialog";import { PageHeader, Toolbar } from "@/components/ui/page";import { PaginationBar } from "@/components/PaginationBar";import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";+import { compactJsonPreview, hasJsonContent } from "@/lib/jsonPreview";import { cn, fenToYuan } from "@/lib/utils";import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";import { taskDomainLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";@@ -32,10 +33,34 @@ function formatTime(value: string | null | undefined): string {return new Date(value).toLocaleString();}+// 阻止冒泡到行 onClick,避免链接跳转时同时打开详情+function stopRowClick(e: { stopPropagation: () => void }) {+ e.stopPropagation();+}+function scopeLinks(task: AdminTaskRow): ReactNode {const parts: ReactNode[] = [];- if (task.drama_project_id) parts.push(<AdminEntityLink key="drama" kind="drama" id={task.drama_project_id} />);- if (task.project_id) parts.push(<AdminEntityLink key="project" kind="project" id={task.project_id} />);+ if (task.drama_project_id) {+ parts.push(+ <span key="drama" onClick={stopRowClick}>+ <AdminEntityLink kind="drama" id={task.drama_project_id} />+ </span>,+ );+ }+ if (task.project_id) {+ parts.push(+ <span key="project" onClick={stopRowClick}>+ <AdminEntityLink kind="project" id={task.project_id} />+ </span>,+ );+ }+ if (task.asset_id) {+ parts.push(+ <span key="asset" onClick={stopRowClick}>+ <AdminEntityLink kind="drama_asset" id={task.asset_id} />+ </span>,+ );+ }if (task.episode_id) parts.push(<span key="ep">分集#{task.episode_id}</span>);if (task.fragment_id) parts.push(<span key="frag">分镜#{task.fragment_id}</span>);if (parts.length === 0) return <span className="text-[#909399]">—</span>;@@ -46,6 +71,20 @@ function canCancel(task: AdminTaskRow): boolean {return task.cancelable && !TERMINAL_STATUSES.has(task.status);}+// 列表单元格:参数/结果单行摘要;title 也截断,避免巨 payload 塞进 DOM+function jsonCell(value: Record<string, unknown> | null | undefined) {+ if (!hasJsonContent(value)) {+ return <span className="text-[#909399]">—</span>;+ }+ const preview = compactJsonPreview(value, 72);+ const tip = compactJsonPreview(value, 280);+ return (+ <pre className="task-list-json" title={tip}>+ {preview}+ </pre>+ );+}+// 统一任务平台监控页export function QueuesPage() {/*@@ -371,6 +410,8 @@ export function QueuesPage() {<th>状态</th><th>进度</th><th>费用</th>+ <th>提交参数</th>+ <th>结果</th><th>时间</th><th>操作</th></tr>@@ -378,7 +419,7 @@ export function QueuesPage() {<tbody>{(data?.items.length ?? 0) === 0 ? (<tr>- <td colSpan={9}>+ <td colSpan={11}><div className="admin-empty !py-10"><div className="admin-empty-title">暂无任务</div><div className="admin-empty-desc">切换到「全部」查看历史任务</div>@@ -399,7 +440,7 @@ export function QueuesPage() {{taskTypeLabel(task.task_type)}</div></td>- <td>+ <td onClick={stopRowClick}><AdminEntityLinkkind="user"id={task.requested_by}@@ -407,7 +448,9 @@ export function QueuesPage() {className="text-xs"/></td>- <td className="max-w-[200px] text-xs">{scopeLinks(task)}</td>+ <td className="max-w-[200px] text-xs" onClick={stopRowClick}>+ {scopeLinks(task)}+ </td><td><span className={`admin-status-pill ${statusClass(task.status)}`}>{taskStatusLabel(task.status)}@@ -426,6 +469,8 @@ export function QueuesPage() {? `预扣 ¥${fenToYuan(task.billing_estimate_fen ?? 0)}`: "—"}</td>+ <td className="task-list-json-cell">{jsonCell(task.payload)}</td>+ <td className="task-list-json-cell">{jsonCell(task.result_payload)}</td><td className="text-xs text-[#909399]"><div>创建 {formatTime(task.created_at)}</div>{task.started_at ? <div>开始 {formatTime(task.started_at)}</div> : null}diff --git a/admin/src/pages/SettingsPage.tsx b/admin/src/pages/SettingsPage.tsxindex 836e382..4eacc46 100644--- a/admin/src/pages/SettingsPage.tsx+++ b/admin/src/pages/SettingsPage.tsx@@ -1,55 +1,90 @@-import { useState } from "react";-import { OssSettingsPanel } from "@/components/settings/OssSettingsPanel";-import { PaymentSettingsPanel } from "@/components/settings/PaymentSettingsPanel";-import { RoutingSettingsPanel } from "@/components/settings/RoutingSettingsPanel";-import { RuntimeSettingsPanel } from "@/components/settings/RuntimeSettingsPanel";-import { SiteSettingsPanel } from "@/components/settings/SiteSettingsPanel";-import { cn } from "@/lib/utils";--type SettingsTab = "routing" | "runtime" | "oss" | "payment" | "site";--const TABS: { id: SettingsTab; label: string }[] = [- { id: "routing", label: "模型路由" },- { id: "runtime", label: "运行参数" },- { id: "oss", label: "存储 OSS" },- { id: "payment", label: "支付计费" },- { id: "site", label: "站点工具" },-];--// 系统设置:模型、运行参数、OSS、支付、站点-export function SettingsPage() {- const [tab, setTab] = useState<SettingsTab>("routing");-- return (- <div className="settings-page admin-page">- <div className="settings-head">- <p className="settings-head-desc">- 渠道路由、运行参数、OSS / 易支付 / 计费与站点配置;密钥加密存库,留空保存不修改。- </p>- <div className="settings-tabs" role="tablist" aria-label="系统设置分区">- {TABS.map(({ id, label }) => (- <button- key={id}- type="button"- role="tab"- aria-selected={tab === id}- className={cn("admin-tab settings-tab", tab === id && "is-active")}- onClick={() => setTab(id)}- >- {label}- </button>- ))}- </div>- </div>-- <div className="settings-main">- {tab === "routing" ? <RoutingSettingsPanel /> : null}- {tab === "runtime" ? <RuntimeSettingsPanel /> : null}- {tab === "oss" ? <OssSettingsPanel /> : null}- {tab === "payment" ? <PaymentSettingsPanel /> : null}- {tab === "site" ? <SiteSettingsPanel /> : null}- </div>- </div>- );-}-\ No newline at end of file+import { useState } from "react";+import { Loader2, Save } from "lucide-react";+import { OssSettingsPanel } from "@/components/settings/OssSettingsPanel";+import { PaymentSettingsPanel } from "@/components/settings/PaymentSettingsPanel";+import { RoutingSettingsPanel } from "@/components/settings/RoutingSettingsPanel";+import { RuntimeSettingsPanel } from "@/components/settings/RuntimeSettingsPanel";+import { SiteSettingsPanel } from "@/components/settings/SiteSettingsPanel";+import {+ SettingsSaveProvider,+ useSettingsSaveSlot,+} from "@/components/settings/SettingsSaveContext";+import { cn } from "@/lib/utils";++type SettingsTab = "routing" | "runtime" | "oss" | "payment" | "site";++const TABS: { id: SettingsTab; label: string }[] = [+ { id: "routing", label: "模型路由" },+ { id: "runtime", label: "运行参数" },+ { id: "oss", label: "存储 OSS" },+ { id: "payment", label: "支付计费" },+ { id: "site", label: "站点工具" },+];++// 页头:标题 + 统一保存按钮+function SettingsPageHeader() {+ const { action } = useSettingsSaveSlot();+ return (+ <header className="settings-page-hero">+ <div className="min-w-0">+ <h1 className="settings-page-title">系统设置</h1>+ <p className="settings-head-desc">+ 渠道路由、运行参数、OSS / 易支付 / 计费与站点配置;密钥加密存库,留空保存不修改。+ </p>+ </div>+ {action ? (+ <button+ type="button"+ className="admin-btn admin-btn-primary settings-save-btn"+ disabled={action.saving}+ onClick={() => void action.onSave()}+ >+ {action.saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}+ {action.label ?? "保存"}+ </button>+ ) : null}+ </header>+ );+}++// 系统设置内容区+function SettingsPageInner() {+ const [tab, setTab] = useState<SettingsTab>("routing");++ return (+ <div className="settings-page admin-page">+ <SettingsPageHeader />++ <div className="settings-tabs" role="tablist" aria-label="系统设置分区">+ {TABS.map(({ id, label }) => (+ <button+ key={id}+ type="button"+ role="tab"+ aria-selected={tab === id}+ className={cn("settings-tab", tab === id && "is-active")}+ onClick={() => setTab(id)}+ >+ {label}+ </button>+ ))}+ </div>++ <div className="settings-main">+ {tab === "routing" ? <RoutingSettingsPanel /> : null}+ {tab === "runtime" ? <RuntimeSettingsPanel /> : null}+ {tab === "oss" ? <OssSettingsPanel /> : null}+ {tab === "payment" ? <PaymentSettingsPanel /> : null}+ {tab === "site" ? <SiteSettingsPanel /> : null}+ </div>+ </div>+ );+}++export function SettingsPage() {+ return (+ <SettingsSaveProvider>+ <SettingsPageInner />+ </SettingsSaveProvider>+ );+}diff --git a/backend/.env.example b/backend/.env.exampleindex 69b6969..52bbd10 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -6,8 +6,9 @@ SECRET_KEY=dev-secret-change-meDATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilmDATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm# Postgres 生产建议:API uvicorn --workers 1;Celery 设 PRINTFILM_DB_ROLE=celery-# DB_POOL_SIZE=5-# DB_MAX_OVERFLOW=5+# 生产建议与任务并发对齐(杭州现网:100+20,PG max_connections≥250)+# DB_POOL_SIZE=100+# DB_MAX_OVERFLOW=20# DB_POOL_SIZE_CELERY=2# DB_MAX_OVERFLOW_CELERY=3REDIS_URL=redis://127.0.0.1:16379/0diff --git a/backend/app/api/admin/settings.py b/backend/app/api/admin/settings.pyindex 306e408..90b6641 100644--- a/backend/app/api/admin/settings.py+++ b/backend/app/api/admin/settings.py@@ -16,6 +16,7 @@ from app.services.model_settings import (patch_admin_model_settings,patch_admin_routing_settings,)+from app.services.upstream_model_catalog import list_upstream_modelsrouter = APIRouter()@@ -25,6 +26,16 @@ class AdminArkModelsRequest(BaseModel):api_key: str | None = Field(default=None, max_length=512)+class AdminUpstreamModelsRequest(BaseModel):+ """按渠道凭证拉取上游 /models 目录。"""++ channel_id: str | None = Field(default=None, max_length=64)+ protocol: str = Field(default="auto", max_length=32)+ base_url: str = Field(default="", max_length=512)+ api_key: str | None = Field(default=None, max_length=512)+ capability: str = Field(default="all", max_length=32)++@router.get("/settings/routing", response_model=AdminRoutingSettingsOut)async def admin_get_routing_settings(_admin: User = Depends(get_current_admin),@@ -101,3 +112,24 @@ async def admin_list_ark_models(except RuntimeError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excreturn {"models": models}++[email protected]("/settings/upstream/models")+async def admin_list_upstream_models(+ body: AdminUpstreamModelsRequest,+ _admin: User = Depends(get_current_admin),+ db: AsyncSession = Depends(get_db),+) -> dict:+ """按渠道协议拉取上游可用模型(OpenAI 兼容或方舟)。"""+ try:+ models = await list_upstream_models(+ db,+ channel_id=body.channel_id,+ protocol=body.protocol,+ base_url=body.base_url,+ api_key_override=body.api_key,+ capability=body.capability,+ )+ except RuntimeError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"models": models}diff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex e5fc092..e5dc86d 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -7,7 +7,16 @@ from app.config import get_settingsfrom app.database import get_dbfrom app.deps import get_current_userfrom app.models import User, WalletLedger-from app.schemas import LoginRequest, ProfileUpdateRequest, RegisterRequest, TokenResponse, UserOut, ChangePasswordRequest+from app.schemas import (+ ChangePasswordRequest,+ ForgotPasswordRequest,+ LoginRequest,+ ProfileUpdateRequest,+ RegisterRequest,+ ResetPasswordRequest,+ TokenResponse,+ UserOut,+)from app.services import storagefrom app.services.auth import (create_access_token,@@ -15,6 +24,12 @@ from app.services.auth import (hash_password,verify_password,)+from app.services.password_reset import (+ InvalidTokenError,+ RedisUnavailableError,+ apply_password_reset,+ request_password_reset,+)from app.services.profile import ProfileError, prepare_profile_updaterouter = APIRouter(prefix="/auth", tags=["auth"])@@ -83,6 +98,33 @@ async def change_password(return {"ok": True}[email protected]("/forgot-password")+async def forgot_password(+ body: ForgotPasswordRequest,+ db: AsyncSession = Depends(get_db),+) -> dict[str, object]:+ """发送密码重置邮件;统一成功文案,避免邮箱枚举。"""+ try:+ return await request_password_reset(db, str(body.email))+ except RedisUnavailableError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc++[email protected]("/reset-password")+async def reset_password(+ body: ResetPasswordRequest,+ db: AsyncSession = Depends(get_db),+) -> dict[str, bool]:+ """用邮件中的一次性 token 设置新密码。"""+ try:+ await apply_password_reset(db, token=body.token, new_password=body.new_password)+ except RedisUnavailableError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except InvalidTokenError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True}++@router.patch("/me", response_model=UserOut)async def update_me(body: ProfileUpdateRequest,diff --git a/backend/app/config.py b/backend/app/config.pyindex 8636e17..991c688 100644--- a/backend/app/config.py+++ b/backend/app/config.py@@ -102,7 +102,8 @@ class Settings(BaseSettings):billing_tts_per_m: float = 2.0# Fallback tokens when API omits usagebilling_est_llm_tokens: int = 80_000- billing_est_seedream_tokens: int = 20_000+ # Seedream 单张实测约 3–3.5 万 tokens;预估略留余量,避免预扣远高于实扣+ billing_est_seedream_tokens: int = 45_000billing_est_tts_tokens: int = 5_000billing_est_seedance_tokens_per_sec: int = 20_000# Signup grant (fen)diff --git a/backend/app/schemas.py b/backend/app/schemas.pyindex 5d5ae5f..a89cea5 100644--- a/backend/app/schemas.py+++ b/backend/app/schemas.py@@ -55,6 +55,15 @@ class ChangePasswordRequest(BaseModel):new_password: str = Field(min_length=6, max_length=64)+class ForgotPasswordRequest(BaseModel):+ email: EmailStr+++class ResetPasswordRequest(BaseModel):+ token: str = Field(min_length=1, max_length=256)+ new_password: str = Field(min_length=6, max_length=64)++# ---- Templates ----class TemplateOut(BaseModel):id: strdiff --git a/backend/app/schemas_settings.py b/backend/app/schemas_settings.pyindex 1bdb95b..7e9969a 100644--- a/backend/app/schemas_settings.py+++ b/backend/app/schemas_settings.py@@ -105,7 +105,7 @@ class AdminModelSettingsOut(BaseModel):billing_seedream_per_m: float = 8.0billing_tts_per_m: float = 2.0billing_est_llm_tokens: int = 80_000- billing_est_seedream_tokens: int = 20_000+ billing_est_seedream_tokens: int = 45_000billing_est_tts_tokens: int = 5_000billing_est_seedance_tokens_per_sec: int = 20_000billing_signup_grant_fen: int = 500diff --git a/backend/app/services/password_reset.py b/backend/app/services/password_reset.pynew file mode 100644index 0000000..a792a1f--- /dev/null+++ b/backend/app/services/password_reset.py@@ -0,0 +1,166 @@+# -*- coding: utf-8 -*-+"""邮箱找回密码:Redis 一次性 token + SMTP 重置链接。"""+from __future__ import annotations++import hashlib+import logging+import secrets+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.config import get_settings+from app.services.auth import get_user_by_email, get_user_by_id, hash_password+from app.services.email import send_email++logger = logging.getLogger(__name__)++# token TTL / 同邮箱冷却+TOKEN_TTL_SECONDS = 30 * 60+COOLDOWN_SECONDS = 60++GENERIC_OK_MESSAGE = "若该邮箱已注册,将收到重置邮件"+++class PasswordResetError(Exception):+ """找回/重置密码业务错误。"""+++class RedisUnavailableError(PasswordResetError):+ """Redis 不可用,无法签发或校验重置 token。"""+++class InvalidTokenError(PasswordResetError):+ """重置 token 无效或已过期。"""+++def _token_hash(token: str) -> str:+ # 只存 sha256,明文 token 仅出现在邮件链接里+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++def _token_key(token_hash: str) -> str:+ return f"pwdreset:{token_hash}"+++def _user_key(user_id: int) -> str:+ return f"pwdreset:user:{user_id}"+++def _cooldown_key(email: str) -> str:+ return f"pwdreset:cd:{email}"+++def get_redis_client() -> Any:+ """连接 Redis;失败则抛 RedisUnavailableError(不做内存回退)。"""+ try:+ import redis++ client = redis.Redis.from_url(+ get_settings().redis_url,+ decode_responses=True,+ socket_connect_timeout=2,+ socket_timeout=2,+ )+ client.ping()+ return client+ except Exception as exc: # noqa: BLE001+ logger.warning("password reset redis unavailable: %s", exc)+ raise RedisUnavailableError("服务暂时不可用,请稍后再试") from exc+++def create_reset_token(redis_client: Any, user_id: int) -> str:+ """签发一次性 token,并使该用户旧 token 失效。"""+ old_hash = redis_client.get(_user_key(user_id))+ if old_hash:+ redis_client.delete(_token_key(str(old_hash)))++ token = secrets.token_urlsafe(32)+ th = _token_hash(token)+ pipe = redis_client.pipeline()+ pipe.setex(_token_key(th), TOKEN_TTL_SECONDS, str(user_id))+ pipe.setex(_user_key(user_id), TOKEN_TTL_SECONDS, th)+ pipe.execute()+ return token+++def consume_reset_token(redis_client: Any, token: str) -> int:+ """校验并删除 token,返回 user_id;无效则抛 InvalidTokenError。"""+ raw = (token or "").strip()+ if not raw:+ raise InvalidTokenError("重置链接无效或已过期")+ th = _token_hash(raw)+ key = _token_key(th)+ user_id_raw = redis_client.get(key)+ if not user_id_raw:+ raise InvalidTokenError("重置链接无效或已过期")+ try:+ user_id = int(user_id_raw)+ except (TypeError, ValueError) as exc:+ redis_client.delete(key)+ raise InvalidTokenError("重置链接无效或已过期") from exc++ redis_client.delete(key, _user_key(user_id))+ return user_id+++def build_reset_link(token: str) -> str:+ # 用户端 Auth 页:?mode=reset&token=...+ base = str(get_settings().public_base_url or "").rstrip("/")+ return f"{base}/auth?mode=reset&token={token}"+++async def request_password_reset(db: AsyncSession, email: str) -> dict[str, Any]:+ """+ 发起找回:写 Redis token 并尝试发信。+ 始终返回统一成功文案(防枚举);Redis 不可用时抛错。+ """+ redis_client = get_redis_client()+ email_norm = str(email or "").strip().lower()+ cd_key = _cooldown_key(email_norm)++ # 60 秒冷却:重复请求直接成功、不重发+ if redis_client.get(cd_key):+ return {"ok": True, "message": GENERIC_OK_MESSAGE}++ redis_client.setex(cd_key, COOLDOWN_SECONDS, "1")++ user = await get_user_by_email(db, email_norm)+ if not user:+ return {"ok": True, "message": GENERIC_OK_MESSAGE}++ token = create_reset_token(redis_client, int(user.id))+ link = build_reset_link(token)+ body = (+ "您正在重置 PRINTFILM 账号密码。\n\n"+ f"请在 30 分钟内打开以下链接设置新密码:\n{link}\n\n"+ "如非本人操作,请忽略本邮件。"+ )+ sent = await send_email(+ to_addrs=[email_norm],+ subject="PRINTFILM 密码重置",+ body=body,+ )+ if not sent:+ logger.warning(+ "password reset email not sent (smtp off or failed) user_id=%s email=%s",+ user.id,+ email_norm,+ )+ return {"ok": True, "message": GENERIC_OK_MESSAGE}+++async def apply_password_reset(+ db: AsyncSession,+ *,+ token: str,+ new_password: str,+) -> None:+ """校验 token 后更新密码;token 一次性消费。"""+ redis_client = get_redis_client()+ user_id = consume_reset_token(redis_client, token)+ user = await get_user_by_id(db, user_id)+ if not user:+ raise InvalidTokenError("重置链接无效或已过期")+ user.hashed_password = hash_password(new_password)+ await db.commit()diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.pyindex ea70f46..5d959a8 100644--- a/backend/app/services/tasks/executor.py+++ b/backend/app/services/tasks/executor.py@@ -43,6 +43,10 @@ async def execute_task_run(task_id: int) -> None:await db.commit()return+ # 在 freeze_for_task 之前读取 steps:_lock_task(populate_existing=True)+ # 会卸掉已预加载的关系,之后访问 task.steps 会触发异步懒加载抛 MissingGreenlet。+ step = task.steps[0] if task.steps else None+try:await freeze_for_task(db, task)except ValueError as exc:@@ -64,7 +68,6 @@ async def execute_task_run(task_id: int) -> None:await db.commit()return- step = task.steps[0] if task.steps else Nonenow = datetime.now(UTC)task.status = "running"task.started_at = task.started_at or now@@ -89,10 +92,10 @@ async def execute_task_run(task_id: int) -> None:returnhandler = get_task_handler(task.domain, task.task_type)result = await handler.executor(task) if handler else {"ok": False, "error": "missing_handler"}+ # 重新加载(含 selectinload steps);勿 refresh,会卸掉关系再触发懒加载。task = await get_task_for_runtime(db, task_id)if not task:return- await db.refresh(task)if isinstance(result, dict) and (result.get("deferred") or result.get("awaiting_poll")):await db.commit()returndiff --git a/backend/app/services/upstream_model_catalog.py b/backend/app/services/upstream_model_catalog.pynew file mode 100644index 0000000..70dc913--- /dev/null+++ b/backend/app/services/upstream_model_catalog.py@@ -0,0 +1,134 @@+# -*- coding: utf-8 -*-+"""从上游渠道拉取可用模型目录(OpenAI 兼容 / 方舟)。"""+from __future__ import annotations++import logging+from typing import Any++import httpx+from sqlalchemy.ext.asyncio import AsyncSession++from app.services.ark_model_catalog import ARK_DEFAULT_BASE, list_ark_models+from app.services.model_routing_config import infer_model_capability, normalize_model_name++logger = logging.getLogger(__name__)+++def _model_id(item: dict[str, Any]) -> str:+ for key in ("id", "name", "model"):+ raw = item.get(key)+ if isinstance(raw, str) and raw.strip():+ return raw.strip()+ return ""+++async def _resolve_channel_credentials(+ db: AsyncSession | None,+ *,+ channel_id: str | None,+ protocol: str,+ base_url: str,+ api_key_override: str | None,+) -> tuple[str, str, str]:+ """返回 (protocol, base_url, api_key)。"""+ proto = (protocol or "auto").strip().lower() or "auto"+ base = (base_url or "").strip().rstrip("/")+ key = (api_key_override or "").strip()++ if db is not None and channel_id:+ from app.services.model_settings import _load_channels++ channels = await _load_channels(db, runtime=True)+ channel = next((item for item in channels if item.id == channel_id), None)+ if channel is not None:+ if not key:+ key = (channel.api_key or "").strip()+ if not base:+ base = (channel.base_url or "").strip().rstrip("/")+ if proto in {"", "auto"}:+ proto = (channel.protocol or "auto").strip().lower() or "auto"++ if proto == "ark" and not base:+ base = ARK_DEFAULT_BASE.rstrip("/")+ return proto, base, key+++async def _list_openai_compatible_models(+ *,+ base_url: str,+ api_key: str,+ capability: str = "all",+) -> list[dict[str, str]]:+ """GET {base}/models,按 OpenAI 兼容响应解析。"""+ if not base_url:+ raise RuntimeError("请先填写 Base URL")+ if not api_key:+ raise RuntimeError("请先填写 API Key,或使用已保存密钥的渠道")++ headers = {"Authorization": f"Bearer {api_key}"}+ url = f"{base_url.rstrip('/')}/models"+ async with httpx.AsyncClient(timeout=60.0) as client:+ resp = await client.get(url, headers=headers)+ if resp.status_code >= 400:+ raise RuntimeError(f"拉取模型目录失败 HTTP {resp.status_code}: {resp.text[:300]}")+ payload = resp.json()++ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, list):+ raise RuntimeError("上游返回格式异常:缺少 data 列表")++ cap_filter = (capability or "all").strip().lower()+ out: list[dict[str, str]] = []+ seen: set[str] = set()+ for item in data:+ if not isinstance(item, dict):+ continue+ model_id = _model_id(item)+ if not model_id:+ continue+ cap = infer_model_capability(model_id)+ if cap_filter not in {"", "all"} and cap != cap_filter:+ continue+ key = normalize_model_name(model_id)+ if key in seen:+ continue+ seen.add(key)+ label = str(item.get("display_name") or model_id)+ out.append({"id": model_id, "label": label if label else model_id, "capability": cap})+ out.sort(key=lambda row: row["id"])+ return out+++async def list_upstream_models(+ db: AsyncSession | None = None,+ *,+ channel_id: str | None = None,+ protocol: str = "auto",+ base_url: str = "",+ api_key_override: str | None = None,+ capability: str = "all",+) -> list[dict[str, str]]:+ """按渠道协议拉取可用模型。"""+ proto, base, key = await _resolve_channel_credentials(+ db,+ channel_id=channel_id,+ protocol=protocol,+ base_url=base_url,+ api_key_override=api_key_override,+ )++ if proto == "volc_tts":+ raise RuntimeError("豆包 TTS 暂不支持从上游拉取模型目录,请手动填写 speaker / 音色 ID")++ if proto == "ark" or "volces.com" in base.lower():+ return await list_ark_models(+ db,+ capability=capability if capability not in {"", "all"} else "all",+ api_key_override=key or api_key_override,+ )++ return await _list_openai_compatible_models(+ base_url=base,+ api_key=key,+ capability=capability,+ )diff --git a/backend/tests/test_password_reset.py b/backend/tests/test_password_reset.pynew file mode 100644index 0000000..dea8701--- /dev/null+++ b/backend/tests/test_password_reset.py@@ -0,0 +1,153 @@+"""密码重置:token 存取、冷却与一次性消费(mock Redis)。"""++from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from app.services import password_reset as pr+++class FakeRedis:+ """最小 Redis 替身:支持 get/setex/delete/pipeline/ping。"""++ def __init__(self) -> None:+ self.store: dict[str, str] = {}+ self.ttls: dict[str, int] = {}++ def ping(self) -> bool:+ return True++ def get(self, key: str) -> str | None:+ return self.store.get(key)++ def setex(self, key: str, ttl: int, value: str) -> bool:+ self.store[key] = str(value)+ self.ttls[key] = int(ttl)+ return True++ def delete(self, *keys: str) -> int:+ n = 0+ for key in keys:+ if key in self.store:+ del self.store[key]+ self.ttls.pop(key, None)+ n += 1+ return n++ def pipeline(self) -> "FakePipeline":+ return FakePipeline(self)+++class FakePipeline:+ def __init__(self, redis: FakeRedis) -> None:+ self.redis = redis+ self.ops: list[tuple[str, tuple[Any, ...]]] = []++ def setex(self, key: str, ttl: int, value: str) -> "FakePipeline":+ self.ops.append(("setex", (key, ttl, value)))+ return self++ def execute(self) -> list[bool]:+ out: list[bool] = []+ for name, args in self.ops:+ if name == "setex":+ out.append(self.redis.setex(*args))+ return out+++def test_create_and_consume_reset_token_roundtrip():+ # 签发后可消费一次,第二次失败+ r = FakeRedis()+ token = pr.create_reset_token(r, user_id=42)+ assert token+ assert r.get(pr._user_key(42))+ user_id = pr.consume_reset_token(r, token)+ assert user_id == 42+ assert r.get(pr._token_key(pr._token_hash(token))) is None+ with pytest.raises(pr.InvalidTokenError):+ pr.consume_reset_token(r, token)+++def test_new_token_invalidates_old():+ # 同用户新 token 会使旧 token 失效+ r = FakeRedis()+ old = pr.create_reset_token(r, user_id=7)+ new = pr.create_reset_token(r, user_id=7)+ assert old != new+ with pytest.raises(pr.InvalidTokenError):+ pr.consume_reset_token(r, old)+ assert pr.consume_reset_token(r, new) == 7+++def test_consume_empty_or_unknown_token():+ r = FakeRedis()+ with pytest.raises(pr.InvalidTokenError):+ pr.consume_reset_token(r, "")+ with pytest.raises(pr.InvalidTokenError):+ pr.consume_reset_token(r, "not-a-real-token")+++async def test_request_password_reset_cooldown_skips_resend():+ # 冷却期内第二次请求不重发、不重写 token+ fake = FakeRedis()+ user = MagicMock(id=9, email="[email protected]")+ db = AsyncMock()++ with (+ patch.object(pr, "get_redis_client", return_value=fake),+ patch.object(pr, "get_user_by_email", AsyncMock(return_value=user)) as get_user,+ patch.object(pr, "send_email", AsyncMock(return_value=True)) as send,+ patch.object(pr, "get_settings") as settings,+ ):+ settings.return_value.public_base_url = "https://www.printfilm.com"+ first = await pr.request_password_reset(db, "[email protected]")+ assert first["ok"] is True+ assert send.await_count == 1+ assert get_user.await_count == 1+ token_keys = [k for k in fake.store if k.startswith("pwdreset:") and not k.startswith("pwdreset:cd:") and not k.startswith("pwdreset:user:")]+ assert len(token_keys) == 1++ second = await pr.request_password_reset(db, "[email protected]")+ assert second["ok"] is True+ assert send.await_count == 1+ assert get_user.await_count == 1+++async def test_request_password_reset_unknown_email_still_ok():+ # 未注册邮箱仍返回统一成功文案+ fake = FakeRedis()+ db = AsyncMock()+ with (+ patch.object(pr, "get_redis_client", return_value=fake),+ patch.object(pr, "get_user_by_email", AsyncMock(return_value=None)),+ patch.object(pr, "send_email", AsyncMock(return_value=True)) as send,+ ):+ res = await pr.request_password_reset(db, "[email protected]")+ assert res["ok"] is True+ assert res["message"] == pr.GENERIC_OK_MESSAGE+ send.assert_not_awaited()+++async def test_apply_password_reset_updates_hash():+ fake = FakeRedis()+ token = pr.create_reset_token(fake, user_id=3)+ user = MagicMock(id=3, hashed_password="old")+ db = AsyncMock()++ with (+ patch.object(pr, "get_redis_client", return_value=fake),+ patch.object(pr, "get_user_by_id", AsyncMock(return_value=user)),+ patch.object(pr, "hash_password", return_value="new-hash") as hp,+ ):+ await pr.apply_password_reset(db, token=token, new_password="secret1")+ hp.assert_called_once_with("secret1")+ assert user.hashed_password == "new-hash"+ db.commit.assert_awaited()+ with pytest.raises(pr.InvalidTokenError):+ await pr.apply_password_reset(db, token=token, new_password="again12")diff --git a/backend/tests/test_task_executor_freeze_steps.py b/backend/tests/test_task_executor_freeze_steps.pynew file mode 100644index 0000000..871f24f--- /dev/null+++ b/backend/tests/test_task_executor_freeze_steps.py@@ -0,0 +1,109 @@+"""Task executor regression: freeze 不得卸掉尚未读取的 steps。"""+from __future__ import annotations++import inspect+from contextlib import asynccontextmanager+from datetime import UTC, datetime+from unittest.mock import patch++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models_tasks import TaskStep+from app.services.billing.settlement import freeze_for_task+from app.services.tasks.executor import execute_task_run+from app.services.tasks.service import get_task_for_runtime, set_task_step_state++from tests.conftest import make_task, make_user+++def test_execute_task_run_source_reads_steps_before_freeze() -> None:+ """源码顺序守卫:steps 必须在 freeze_for_task 之前读取,避免 MissingGreenlet。"""+ src = inspect.getsource(execute_task_run)+ i_steps = src.find("step = task.steps[0]")+ i_freeze = src.find("await freeze_for_task")+ assert i_steps != -1 and i_freeze != -1+ assert i_steps < i_freeze, "必须先读取 task.steps,再调用 freeze_for_task"+++async def test_freeze_expires_preloaded_steps_relationship(db_session: AsyncSession) -> None:+ """根因:_lock_task(populate_existing) 会使已 selectinload 的 steps 失效。"""+ user = await make_user(db_session, balance_fen=50_000)+ task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))+ await db_session.commit()++ loaded = await get_task_for_runtime(db_session, int(task.id))+ assert loaded is not None+ assert len(loaded.steps) == 1+ await freeze_for_task(db_session, loaded)+ with pytest.raises(Exception) as ei:+ _ = list(loaded.steps)+ assert "MissingGreenlet" in type(ei.value).__name__ or "greenlet" in str(ei.value).lower()+++async def test_held_step_survives_freeze_populate_existing(db_session: AsyncSession) -> None:+ """修复路径:先持有 step 再 freeze,仍可写步骤状态(不必再碰 task.steps)。"""+ user = await make_user(db_session, balance_fen=50_000)+ task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))+ await db_session.commit()++ loaded = await get_task_for_runtime(db_session, int(task.id))+ assert loaded is not None+ step = loaded.steps[0] if loaded.steps else None+ assert step is not None++ await freeze_for_task(db_session, loaded)+ now = datetime.now(UTC)+ set_task_step_state(loaded, step, status="submitting", now=now)+ loaded.status = "running"+ await db_session.commit()++ assert step.status == "submitting"+ assert loaded.status == "running"+ assert loaded.current_step_key == "main"+++async def test_execute_task_run_survives_freeze_populate_existing(+ db_session: AsyncSession,+) -> None:+ """执行器在 freeze(会卸掉关系)后仍能把 leased 任务跑到 succeeded。++ execute_task_run 自开 AsyncSessionLocal;测试用外层事务对别的连接不可见,+ 因此把 SessionLocal 钉到本用例 session。+ """+ user = await make_user(db_session, balance_fen=50_000)+ task = await make_task(+ db_session,+ user,+ domain="api",+ task_type="v1_image",+ status="leased",+ )+ db_session.add(+ TaskStep(+ task_id=task.id,+ step_key="main",+ step_type="run",+ status="pending",+ )+ )+ await db_session.commit()+ task_id = int(task.id)++ @asynccontextmanager+ async def same_session():+ yield db_session++ with patch("app.services.tasks.executor.AsyncSessionLocal", same_session):+ await execute_task_run(task_id)++ db_session.expire_all()+ done = await get_task_for_runtime(db_session, task_id)+ assert done is not None+ assert done.status == "succeeded"+ assert done.steps and done.steps[0].status == "done"diff --git a/docs/releases/2026-09-04.md b/docs/releases/2026-09-04.mdnew file mode 100644index 0000000..bff8d4b--- /dev/null+++ b/docs/releases/2026-09-04.md@@ -0,0 +1,44 @@+# 发布记录 · 2026-09-04++## 2026-09-04 16:27 · 任务卡在已租约 MissingGreenlet;杭州热修++- **操作者**:Agent+- **方式**:SSH 热修(上传 `executor.py` + `systemctl restart ai-movie-api`)+- **范围**:api+- **变更摘要**:+ - 根因:执行器先 `freeze_for_task`(`_lock_task` + `populate_existing`)再读 `task.steps`,触发异步懒加载 `MissingGreenlet`,协程死后状态停在 `leased`+ - 修复:在预扣前先取出 `steps[0]`;重启时 `_recover_orphaned_tasks` 回收 9 条孤儿租约+ - 备份:`/opt/ai_movie/backend/app/services/tasks/executor.py.bak_20260904_162736`+- **验证**:+ - [x] `ai-movie-api` active;journal `recovered orphaned task runs count=9`+ - [x] 原 #3100–#3117 九条由 `leased` → `running`,且出现 `task.started`+ - [x] `/api/health`:`scheduler_running_jobs=9`,`poller=running`;重启后无新的 `MissingGreenlet`+ - [x] `https://www.printfilm.com/api/health` 200+- **备注 / 回滚**:回滚可 `cp` 上述 `.bak_*` 后重启 API++## 2026-09-04 16:33 · DB 池调到 100 + 重试 QueuePool 失败任务;杭州热修++- **操作者**:Agent+- **方式**:SSH 热修(改 `.env` / PG `max_connections` + 应用内 `retry_task_for_user`)+- **范围**:api / postgres+- **变更摘要**:+ - `DB_POOL_SIZE=100`、`DB_MAX_OVERFLOW=20`(健康检查 `max=120`);PG `max_connections=250`+ - 对 #3100/#3109/#3113/#3116/#3117(QueuePool 超时失败)自动重试为 #3118–#3122+ - 漫剧 #353/#354 刷新 `summary_status=generating`,前端轮询可继续等到结果+ - 发布脚本模板同步池配置,避免下次全量覆盖回 5+5+- **验证**:+ - [x] `/api/health` `db_pool.size=100` `max=120`;`ai-movie-api` active+ - [x] 重试任务已入队并进入 `running`+- **备注 / 回滚**:`.env.bak_pool_*`;PG 可用 `ALTER SYSTEM SET max_connections = 100` 后重启容器++## 2026-09-04 16:45 · 任务详情补齐提交参数/结果/资产关联;杭州 admin 热修++- **操作者**:Agent+- **方式**:SSH 热修(上传 `admin/dist`)+- **范围**:admin+- **变更摘要**:+ - 详情概览:有值才展示关联字段;补资产/剧本链接;提交参数可读摘要 + JSON;结果区块固定展示+ - 任务列表增加「提交参数」「结果」摘要列+- **验证**:+ - [x] 本地 `npm run build` 通过;远端 `admin/dist` 已替换+- **备注 / 回滚**:`/opt/ai_movie/admin/dist.bak_*`diff --git a/docs/releases/README.md b/docs/releases/README.mdindex 4a4a332..3ebaaac 100644--- a/docs/releases/README.md+++ b/docs/releases/README.md@@ -33,6 +33,9 @@| 日期 | 摘要 | 文件 ||------|------|------|+| 2026-09-04 | 任务详情补齐提交参数/结果/资产关联;杭州 admin 热修 | [2026-09-04.md](./2026-09-04.md) |+| 2026-09-04 | DB 池调到 100 + 重试 QueuePool 失败任务;杭州热修 | [2026-09-04.md](./2026-09-04.md) |+| 2026-09-04 | 任务卡在已租约 MissingGreenlet;杭州热修 | [2026-09-04.md](./2026-09-04.md) || 2026-09-03 | 分镜收尾幂等 + 去掉无限额度;杭州全量 | [2026-09-03.md](./2026-09-03.md) || 2026-09-03 | 主站切 www;双结算防护全量 | [2026-09-03.md](./2026-09-03.md) || 2026-08-31 | 资产生图 TaskRun 未 commit 热修 | [2026-08-31.md](./2026-08-31.md) |diff --git a/frontend/src/App.css b/frontend/src/App.cssindex f50a0c1..491f679 100644--- a/frontend/src/App.css+++ b/frontend/src/App.css@@ -96,6 +96,12 @@color: var(--crimson);}+.auth-notice {+ color: #027a48;+ margin: 0;+ font-size: 0.95rem;+}+@media (max-width: 900px) {.auth-shell {grid-template-columns: 1fr;diff --git a/frontend/src/api.ts b/frontend/src/api.tsindex 468b7e7..9f74a76 100644--- a/frontend/src/api.ts+++ b/frontend/src/api.ts@@ -284,6 +284,18 @@ export const api = {body: JSON.stringify({ email, password }),})},+ forgotPassword(email: string) {+ return request<{ ok: boolean; message: string }>('/api/auth/forgot-password', {+ method: 'POST',+ body: JSON.stringify({ email }),+ })+ },+ resetPassword(token: string, new_password: string) {+ return request<{ ok: boolean }>('/api/auth/reset-password', {+ method: 'POST',+ body: JSON.stringify({ token, new_password }),+ })+ },me() {return request<User>('/api/auth/me')},diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.tsindex ce8633c..22adafe 100644--- a/frontend/src/i18n/locales/en/shell.ts+++ b/frontend/src/i18n/locales/en/shell.ts@@ -75,19 +75,31 @@ export const enShell = {auth: {loginTitle: 'Back to the studio',registerTitle: 'Create a creator account',+ forgotTitle: 'Reset your password',+ resetTitle: 'Choose a new password',lede: 'PRINTFILM · AI drama and explainer videos',nickname: 'Display name',email: 'Email',password: 'Password',+ newPassword: 'New password',+ confirmPassword: 'Confirm password',emailInvalid: 'Enter a valid email address with @',passwordTooShort: 'Password must be at least 6 characters',passwordTooLong: 'Password must be at most 64 characters',+ passwordMismatch: 'Passwords do not match',nicknameRequired: 'Display name is required',login: 'Sign in',register: 'Sign up',+ sendReset: 'Send reset email',+ savePassword: 'Save new password',processing: 'Working…',toRegister: 'No account? Sign up',toLogin: 'Already have an account? Sign in',+ forgotLink: 'Forgot password?',+ backToLogin: 'Back to sign in',+ forgotSent: 'If that email is registered, a reset link will be sent',+ resetSuccess: 'Password updated. Sign in with your new password',+ resetTokenMissing: 'Invalid reset link. Please request a new one',},create: {title: 'Start creating',diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.tsindex 4e138d6..9bf4f20 100644--- a/frontend/src/i18n/locales/zh/shell.ts+++ b/frontend/src/i18n/locales/zh/shell.ts@@ -74,19 +74,31 @@ export const zhShell = {auth: {loginTitle: '回到工作台',registerTitle: '创建创作者账号',+ forgotTitle: '找回密码',+ resetTitle: '设置新密码',lede: 'PRINTFILM · AI 漫剧与 AI短视频创作平台',nickname: '昵称',email: '邮箱',password: '密码',+ newPassword: '新密码',+ confirmPassword: '确认密码',emailInvalid: '请输入有效的邮箱地址,需包含 @ 符号',passwordTooShort: '密码至少 6 位',passwordTooLong: '密码最多 64 位',+ passwordMismatch: '两次输入的密码不一致',nicknameRequired: '请填写昵称',login: '登录',register: '注册',+ sendReset: '发送重置邮件',+ savePassword: '保存新密码',processing: '处理中…',toRegister: '没有账号?注册',toLogin: '已有账号?登录',+ forgotLink: '忘记密码?',+ backToLogin: '返回登录',+ forgotSent: '若该邮箱已注册,将收到重置邮件',+ resetSuccess: '密码已更新,请使用新密码登录',+ resetTokenMissing: '重置链接无效,请重新申请找回密码',},create: {title: '开始创作',diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsxindex d0de13d..95c2f2e 100644--- a/frontend/src/pages/AuthPage.tsx+++ b/frontend/src/pages/AuthPage.tsx@@ -7,6 +7,8 @@ import LanguageSwitch from '../components/layout/LanguageSwitch'import { useI18n } from '../i18n'import { isValidAuthPassword, isValidEmailInput } from '../lib/validateAuthForm'+type AuthMode = 'login' | 'register' | 'forgot' | 'reset'+// 仅允许站内相对路径回跳,防止开放重定向function safeNextPath(raw: string | null, fallback = '/') {if (!raw) return fallback@@ -14,21 +16,104 @@ function safeNextPath(raw: string | null, fallback = '/') {return raw}+// 由 URL ?mode= / ?token= 决定初始 Auth 模式+function modeFromParams(params: URLSearchParams): AuthMode {+ const mode = (params.get('mode') || '').toLowerCase()+ if (mode === 'reset' || params.get('token')) return 'reset'+ if (mode === 'forgot') return 'forgot'+ if (mode === 'register') return 'register'+ return 'login'+}+export default function AuthPage() {const nav = useNavigate()const { t } = useI18n()- const [params] = useSearchParams()+ const [params, setSearchParams] = useSearchParams()const nextPath = safeNextPath(params.get('next'), '/')- const [mode, setMode] = useState<'login' | 'register'>('login')+ /*+ * mode 当前表单模式+ * email / password / confirmPassword / nickname 表单字段+ * notice 成功提示(找回已发送、重置成功)+ * error / loading 提交态+ */+ const [mode, setMode] = useState<AuthMode>(() => modeFromParams(params))const [email, setEmail] = useState('')const [password, setPassword] = useState('')+ const [confirmPassword, setConfirmPassword] = useState('')const [nickname, setNickname] = useState('')const [error, setError] = useState('')+ const [notice, setNotice] = useState('')const [loading, setLoading] = useState(false)+ const resetToken = (params.get('token') || '').trim()++ // 切换模式并同步 URL(保留 next)+ function switchMode(next: AuthMode) {+ setMode(next)+ setError('')+ setNotice('')+ setPassword('')+ setConfirmPassword('')+ if (next === 'register') setNickname('')+ const nextParams = new URLSearchParams()+ if (nextPath && nextPath !== '/') nextParams.set('next', nextPath)+ if (next === 'forgot') nextParams.set('mode', 'forgot')+ else if (next === 'reset' && resetToken) {+ nextParams.set('mode', 'reset')+ nextParams.set('token', resetToken)+ } else if (next === 'register') nextParams.set('mode', 'register')+ setSearchParams(nextParams, { replace: true })+ }async function onSubmit(e: FormEvent) {e.preventDefault()setError('')+ setNotice('')++ if (mode === 'forgot') {+ const trimmedEmail = email.trim()+ if (!isValidEmailInput(trimmedEmail)) {+ setError(t('auth.emailInvalid'))+ return+ }+ setLoading(true)+ try {+ const res = await api.forgotPassword(trimmedEmail)+ setNotice(res.message || t('auth.forgotSent'))+ } catch (err) {+ setError(err instanceof Error ? err.message : t('common.fail'))+ } finally {+ setLoading(false)+ }+ return+ }++ if (mode === 'reset') {+ if (!resetToken) {+ setError(t('auth.resetTokenMissing'))+ return+ }+ if (!isValidAuthPassword(password)) {+ setError(password.length > 64 ? t('auth.passwordTooLong') : t('auth.passwordTooShort'))+ return+ }+ if (password !== confirmPassword) {+ setError(t('auth.passwordMismatch'))+ return+ }+ setLoading(true)+ try {+ await api.resetPassword(resetToken, password)+ setPassword('')+ setConfirmPassword('')+ switchMode('login')+ setNotice(t('auth.resetSuccess'))+ } catch (err) {+ setError(err instanceof Error ? err.message : t('common.fail'))+ } finally {+ setLoading(false)+ }+ return+ }const trimmedEmail = email.trim()if (mode === 'register' && !nickname.trim()) {@@ -59,6 +144,24 @@ export default function AuthPage() {}}+ const title =+ mode === 'login'+ ? t('auth.loginTitle')+ : mode === 'register'+ ? t('auth.registerTitle')+ : mode === 'forgot'+ ? t('auth.forgotTitle')+ : t('auth.resetTitle')++ const submitLabel =+ mode === 'login'+ ? t('auth.login')+ : mode === 'register'+ ? t('auth.register')+ : mode === 'forgot'+ ? t('auth.sendReset')+ : t('auth.savePassword')+return (<div className="auth-shell"><div className="auth-panel">@@ -66,7 +169,7 @@ export default function AuthPage() {<BrandMark /><LanguageSwitch /></div>- <h1>{mode === 'login' ? t('auth.loginTitle') : t('auth.registerTitle')}</h1>+ <h1>{title}</h1><form onSubmit={onSubmit} className="stack" noValidate>{mode === 'register' && (<label>@@ -74,47 +177,74 @@ export default function AuthPage() {<input value={nickname} onChange={(e) => setNickname(e.target.value)} /></label>)}- <label>- {t('auth.email')}- <input- type="email"- inputMode="email"- autoComplete="username"- value={email}- onChange={(e) => {- setEmail(e.target.value)- if (error) setError('')- }}- />- </label>- <label>- {t('auth.password')}- <input- type="password"- autoComplete={mode === 'login' ? 'current-password' : 'new-password'}- value={password}- onChange={(e) => {- setPassword(e.target.value)- if (error) setError('')- }}- />- </label>+ {(mode === 'login' || mode === 'register' || mode === 'forgot') && (+ <label>+ {t('auth.email')}+ <input+ type="email"+ inputMode="email"+ autoComplete="username"+ value={email}+ onChange={(e) => {+ setEmail(e.target.value)+ if (error) setError('')+ }}+ />+ </label>+ )}+ {(mode === 'login' || mode === 'register' || mode === 'reset') && (+ <label>+ {mode === 'reset' ? t('auth.newPassword') : t('auth.password')}+ <input+ type="password"+ autoComplete={mode === 'login' ? 'current-password' : 'new-password'}+ value={password}+ onChange={(e) => {+ setPassword(e.target.value)+ if (error) setError('')+ }}+ />+ </label>+ )}+ {mode === 'reset' && (+ <label>+ {t('auth.confirmPassword')}+ <input+ type="password"+ autoComplete="new-password"+ value={confirmPassword}+ onChange={(e) => {+ setConfirmPassword(e.target.value)+ if (error) setError('')+ }}+ />+ </label>+ )}+ {notice ? <p className="auth-notice" role="status">{notice}</p> : null}{error ? <p className="error" role="alert">{error}</p> : null}<button className="btn primary" disabled={loading}>- {loading ? t('auth.processing') : mode === 'login' ? t('auth.login') : t('auth.register')}+ {loading ? t('auth.processing') : submitLabel}</button></form>- <button- type="button"- className="linkish"- onClick={() => {- setMode(mode === 'login' ? 'register' : 'login')- setError('')- setNickname('')- }}- >- {mode === 'login' ? t('auth.toRegister') : t('auth.toLogin')}- </button>+ {mode === 'login' && (+ <button type="button" className="linkish" onClick={() => switchMode('forgot')}>+ {t('auth.forgotLink')}+ </button>+ )}+ {(mode === 'login' || mode === 'register') && (+ <button+ type="button"+ className="linkish"+ onClick={() => switchMode(mode === 'login' ? 'register' : 'login')}+ >+ {mode === 'login' ? t('auth.toRegister') : t('auth.toLogin')}+ </button>+ )}+ {(mode === 'forgot' || mode === 'reset') && (+ <button type="button" className="linkish" onClick={() => switchMode('login')}>+ {t('auth.backToLogin')}+ </button>+ )}</div><div className="auth-visual" aria-hidden><div className="ink-wash" />@@ -122,4 +252,3 @@ export default function AuthPage() {</div>)}-