/** * 调度中心(图2 节点 ④ plan_tasks → ⑪ 派发执行) * 清单怎么算、队列怎么排、心跳谁断了:后端是权威,这一页只负责说人话 + 给按钮。 */ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Link, useSearchParams } from 'react-router-dom' import * as api from '../../api/client' import { fmtAgo, fmtMoney, statusLabel } from '../../lib/format' import { useAutoRefresh } from '../../hooks' import { Select } from '../../components/forms' import { Actions, Between, Button, buttonCls, Check, Ctlbar, Divider, ErrorText, Field, Layout, MONO, MUTED, MUTED_MONO, Panel, PanelHead, ProgressBar, Row, Spinner, Status, TabStack, Table, TableBox, Tag, TagGroup, cellCenter, cellRight, cellWrap } from '../../components/ui' import { refresh, useProjectStore } from '../../stores/project' import { useSystemStore } from '../../stores/system' import { notify } from '../../stores/notice' const QUEUE_STATUSES = ['planned', 'queued', 'running', 'retrying', 'succeeded', 'failed', 'cancelled', 'skipped'] const QUEUE_KINDS = ['generate_shot', 'voiceover', 'qc_shot', 'compose', 'import', 'asset'] /** 后端 /api/meta 挂了也要能筛:这份兜底只在 meta 缺席时出现 */ const FALLBACK_TASK_STATUSES = ['planned', 'queued', 'running', 'retrying', 'waiting_review', 'succeeded', 'failed', 'cancelled', 'skipped'] const ACTIVE_STATUSES = ['queued', 'running', 'retrying', 'planned'] /** 执行方式是平台内部实现细节,界面只说人话:任务现在怎么跑、什么时候能看到结果 */ const EXEC_LABEL: Record = { inline: '平台内即时执行', celery: '后台任务队列' } /** 清单动作:后端是三态 enqueue / skip / needs_attention,别把「阻塞」显示成「跳过」 */ const ACTION_LABELS: Record = { enqueue: '待入队', skip: '跳过', needs_attention: '预检阻塞' } const actionLabel = (a: string) => ACTION_LABELS[a] || a || '—' const EMPTY_CELL = 'text-center py-[22px] leading-[1.7]' /** 心跳年龄说成人话:「12 分钟」比「742 秒」更能判断该不该干预。 */ function fmtAge(sec?: number | null) { if (sec === null || sec === undefined) return '从未心跳' if (sec < 60) return `${sec} 秒` const m = Math.round(sec / 60) return m < 60 ? `${m} 分钟` : `${Math.floor(m / 60)} 小时 ${m % 60} 分` } type Switches = { force: boolean; allow_unready: boolean } export default function Dispatch() { const projectId = useProjectStore((s) => s.id) const meta = useSystemStore((s) => s.meta) const [params] = useSearchParams() const [error, setError] = useState('') const [busy, setBusy] = useState('') const [plan, setPlan] = useState(null) const [queue, setQueue] = useState(null) const [tasks, setTasks] = useState([]) /** 任务状态枚举只认后端 /api/meta(TaskStatus.ALL):状态机加一档,筛选就该跟着长, * 不能再靠这里抄一遍 —— 抄漏的那档会在列表里出现却筛不出来。 */ const taskStatusOptions: string[] = (meta?.task_statuses as string[]) || FALLBACK_TASK_STATUSES const [statusFilter, setStatusFilter] = useState('') const [drain, setDrain] = useState(true) const [shotIds, setShotIds] = useState([]) const [withVoiceover, setWithVoiceover] = useState(true) const [switches, setSwitches] = useState({ force: false, allow_unready: false }) const [priority, setPriority] = useState(5) const [limit, setLimit] = useState(32) const [timeout_, setTimeout_] = useState(900) const counts = queue?.counts || {} const executorLabel = queue?.executor ? (EXEC_LABEL[queue.executor] || queue.executor) : '未知' const activeCount = ACTIVE_STATUSES.reduce((sum, k) => sum + (counts[k] || 0), 0) /** 心跳停更的「进行中」:执行体可能已经没了(服务被杀 / 平台热重载),界面必须说破。 */ const staleTasks = tasks.filter((t) => t.stale) const livenessLabel = (() => { const sec = Number(tasks.find((t) => t.stale)?.stale_after_seconds || 0) return sec >= 60 ? `${Math.round(sec / 60)} 分钟` : `${sec} 秒` })() const enqueueable = (plan?.shots || []).filter((s: any) => s.action !== 'skip') const voiceoverable = (plan?.voiceovers || []).filter((v: any) => v.action !== 'skip') /** 队列矩阵按 kind×status 反查,表格里三列循环不必每次都扫一遍数组 */ const matrix = useMemo(() => { const map = new Map() for (const row of queue?.matrix || []) map.set(`${row.kind}|${row.status}`, row) return map }, [queue]) /** load 里要按「当前」的强制/放行开关问后端,但它们又不该进依赖数组 * (否则每勾一次就把整页三张表重新拉一遍),所以留一份 ref 给闭包用。 */ const switchesRef = useRef(switches) switchesRef.current = switches // 清单必须按当前这几个开关去问后端:后端算 skip/enqueue 看的正是 force/allow_unready。 // 以前固定不带 force 去读,已生成或已审核合格的镜头永远显示「跳过」, // 加上下面 skip 行不许勾选,用户从分镜点「重新生成」过来就一个都选不动。 const load = useCallback(async (silent = true, sw?: Switches) => { if (!projectId) return null const gates = sw ?? switchesRef.current if (!silent) setBusy('读取队列') try { const [pl, qu, tk] = await Promise.all([ api.get(`/api/projects/${projectId}/tasklist`, { force: gates.force, allow_unready: gates.allow_unready }), api.get(`/api/projects/${projectId}/queue`), api.get('/api/tasks', { project_id: projectId, status: statusFilter }) ]) setPlan(pl.plan) setQueue(qu) setTasks(tk.tasks || []) setError('') return pl.plan } catch (exc: any) { setError(exc?.message || String(exc)); return null } finally { setBusy('') } }, [projectId, statusFilter]) async function run(label: string, fn: () => Promise, message?: (res: any) => string) { setBusy(label); setError('') try { const res = await fn() const text = message ? message(res) : '' if (text) notify(text) await Promise.all([load(), refresh()]) return res } catch (exc: any) { setError(exc?.message || String(exc)); return null } finally { setBusy('') } } /** 勾选「强制重建 / 放行未就绪」后清单要重算,否则「动作」列还是按旧开关显示跳过。 * 只监听这两个开关:load 的函数身份也随状态筛选变化,写进依赖会多发一次请求。 */ const booted = useRef(false) useEffect(() => { if (!booted.current) { booted.current = true; return } void load() // eslint-disable-next-line react-hooks/exhaustive-deps }, [switches.force, switches.allow_unready]) useEffect(() => { let alive = true ;(async () => { // 分镜工作台卡片上的「▷ 生成 / ↻ 重生成」带 ?shot= 过来时,预勾选该镜头,避免误伤整批。 // 带 force=1 说明来意就是**重做这一镜**:它的产物已经存在,后端默认判 skip, // 不先把强制打开,这一镜在清单里根本选不动。 const want = Number(params.get('shot') || 0) const wantForce = !!want && Number(params.get('force') || 0) === 1 if (wantForce) setSwitches((s) => ({ ...s, force: true })) const pl = await load(false, { force: wantForce, allow_unready: false }) if (!alive) return const row = (pl?.shots || []).find((s: any) => s.shot_id === want) if (!row) return setShotIds([want]) if (row.action === 'skip') { notify(`镜头 #${row.order_index} 暂不需要生成:${row.reason}。勾上「强制重建任务」就能只重做它`) } else { notify(`已勾选镜头 #${row.order_index},点「入队所选」即可只生成这一镜`) } })() return () => { alive = false } // eslint-disable-next-line react-hooks/exhaustive-deps }, [projectId]) /* 队列里有活就 4 秒看一次;空闲时不必反复敲后端 */ useAutoRefresh(() => void load(), 4000, !!busy, false) /** 派发/入队返回的 blocked[]:模型停用或并发·RPM 额度用尽时说明「为什么没动」 */ function blockedNote(r: any) { const blocked = r?.dispatched?.blocked || [] return blocked.length ? `;${blocked.length} 个模型暂不可派发:` + blocked.map((b: any) => `${b.provider_model}(${b.reason})`).join(';') : '' } const enqueue = () => run('生成任务并入队', () => api.post(`/api/projects/${projectId}/tasks`, { shot_ids: shotIds.length ? shotIds : null, force: switches.force, allow_unready: switches.allow_unready, priority, with_voiceover: withVoiceover, actor: 'studio' }), (r) => `已入队 ${r?.created?.count ?? 0} 个任务(其中配音 ${(r?.created?.voiceovers || []).length},` + `跳过 ${(r?.created?.skipped || []).length} —— 跳过原因见清单「动作」列` + blockedNote(r)) const buildVoiceover = () => run('生成配音任务', () => api.post(`/api/projects/${projectId}/voiceover`, { shot_ids: null, only_missing: true, priority: 4 }), (r) => `已创建 ${r?.count ?? 0} 条配音任务`) const doDispatch = () => run(drain ? '派发并排空队列' : '派发任务', () => api.post(`/api/projects/${projectId}/dispatch`, { limit, drain, timeout: timeout_ }), (r) => drain ? `本轮派发 ${r?.dispatched?.count ?? 0} 个,排空期间跑完 ` + `${r?.drained?.completed_during_drain ?? 0} 个(终态累计 ${r?.drained?.completed ?? 0})` + (r?.drained?.remaining ? `,仍在队列 ${r.drained.remaining} 个` : ',队列已清空') + (r?.drained?.timed_out ? '(等待超时,可加大「排空等待」或再点一次)' : '') + (r?.drained?.stalled ? `;已停滞:${(r.drained.stalled_detail?.blocked || []).map((b: any) => `${b.provider_model} ${b.reason}`).join(';')}` : '') + blockedNote(r) : `已派发 ${r?.dispatched?.count ?? 0} 个任务${blockedNote(r)}`) const retryFailed = () => run('重排失败任务', () => api.post(`/api/projects/${projectId}/tasks/retry-failed`, { reset_attempts: true }), (r) => `重新入队 ${r?.count ?? 0} 个失败任务`) const cancelActive = () => run('取消进行中的任务', () => api.post(`/api/projects/${projectId}/tasks/cancel-active`, { reason: '人工在调度中心取消' }), (r) => `已取消 ${r?.count ?? 0} 个任务`) const resume = () => run('断点续跑', () => api.post(`/api/projects/${projectId}/resume`, {}), (r) => `恢复中断任务 ${r?.resume?.count ?? 0} 个,本进程已接手 ${(r?.recovered_here || []).length} 个`) const retryTask = (t: any) => run('重试任务', () => api.post(`/api/tasks/${t.id}/retry`, {}), () => `任务 #${t.id} 已重新入队`) const cancelTask = (t: any) => run('取消任务', () => api.post(`/api/tasks/${t.id}/cancel`, { reason: '人工取消' }), () => `任务 #${t.id} 已取消`) function toggleShot(id: number) { setShotIds((list) => (list.includes(id) ? list.filter((x) => x !== id) : [...list, id])) } return ( {/* 只读计数:跟旁边的 Tag 同档,不借 Chip 的 31px 胶囊皮肤(规范 §2.0) */} 任务执行:{executorLabel} {Object.entries(counts).map(([k, v]) => {statusLabel(k)} {String(v)})} {!activeCount && 队列空闲} {busy ? {busy}… : null} {error} {/* ===== 任务清单(图2 节点④ plan_tasks) ===== */} 预计成本 {fmtMoney(plan?.estimated_cost, plan?.currency)} } /> 待入队 {enqueueable.length} 配音待生成 {voiceoverable.length} 已排队 {plan?.queued_count || 0} 阻塞 {plan?.blocked_count || 0} 跳过 {plan?.skipped_count || 0} 预检就绪 {plan?.preflight?.ready || 0} 预检告警 {plan?.preflight?.warnings || 0} 预计 {plan?.voiceover_count || 0} 条配音 {(plan?.shots || []).map((s: any) => ( ))} {(plan?.voiceovers || []).map((v: any) => ( ))} {!(plan?.shots || []).length && !(plan?.voiceovers || []).length ? : null}
#镜头动作Provider / 模型 时长预估成本说明
toggleShot(s.shot_id)} /> #{s.order_index} {s.title}
shot#{s.shot_id}
{actionLabel(s.action)} {s.provider || '—'} / {s.model || '默认'} {s.duration}s {fmtMoney(s.estimated_cost)} {s.reason} {s.blocking?.length ? 阻塞:{s.blocking.join(';')} : null}
🔊 #{v.order_index} 配音
shot#{v.shot_id}
{v.action !== 'skip' ? '待配音' : '跳过'} TTS {v.chars} 字 — {v.reason}
还没有分镜清单,先去「分镜工作台」拆镜头。

调度控制

入队时一并排配音任务 setSwitches((s) => ({ ...s, allow_unready: v }))}>放行预检未通过的镜头(默认只跳过它们) setSwitches((s) => ({ ...s, force: v }))}>强制重建任务(忽略幂等,可重做已生成的镜头) setPriority(Number(e.target.value))} /> 派发后同步排空(等任务跑完再返回) setLimit(Number(e.target.value))} /> setTimeout_(Number(e.target.value))} />

异常处理

{/* ===== 队列与容量 ===== */} {QUEUE_STATUSES.map((st) => )} {QUEUE_KINDS.map((kind) => ( {QUEUE_STATUSES.map((st) => { const hit = matrix.get(`${kind}|${st}`) return })} ))}
任务类型{statusLabel(st)}
{statusLabel(kind)}{hit ? {hit.count || ''} : null}
{(queue?.capacity || []).map((c: any) => ( ))} {!(queue?.capacity || []).length ? : null}
Provider / 模型运行排队 槽位RPM 余量状态
{c.provider} / {c.model || '默认'}
{c.media_type}
{c.running} {c.queued} {c.slots}/{c.concurrency_limit} {c.rpm_headroom} {!c.enabled ? '已停用' : c.saturated ? '已满负荷' : '可用'}
没有登记并发的模型:所有任务按默认额度执行。
{/* ===== 任务列表 ===== */} 任务执行明细({tasks.length}) {staleTasks.length ? {staleTasks.length} 条心跳已停止 : null} } sub={staleTasks.length ? <>这些任务的执行体超过 {livenessLabel}没有报活:多半是那台机器上的模型服务或平台进程中断过。 产物与断点都留着,平台回收后会自动续跑;着急就点上方「断点续跑」立即处理。 : undefined} right={