nex_animation/frontend/src/pages/project/Overview.tsx

536 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 流程概览(项目工作台第一个页签)。
*
* 一屏回答四个问题:流程走到哪了(节点明细)、能不能开跑(素材预检)、
* 项目是怎么配的(设置)、下一步点哪里(建议 + 事件流)。
* 顶上那块「项目总控台」是本页唯一的写入口之一(拆在 AgentConsole.tsx),
* 其余面板全部只读,只有「项目设置」展开编辑时才会 PATCH。
*
* 数据分两层是有意的:12 节点流程、指标卡由项目 store 每 6 秒轮询,
* 本页只按 15 秒补拉「预检 + 事件流」这两样项目接口里没有的东西。
*/
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import * as api from '../../api/client'
import { EVENT_LEVELS, eventLabel, eventLevelKey, fmtAgo, fmtTime, opt, statusLabel } from '../../lib/format'
import { allNodesDone, stageNote } from '../../lib/pipeline'
import { cn } from '../../lib/cn'
import {
capabilityHint, capsOf, defaultFor, deliveryResolutions, fpsChoices, isMock,
modelsOf, parseRef, refOf, resolutionChoices, useModelsStore
} from '../../stores/models'
import { options } from '../../stores/system'
import { refresh, useProjectStore } from '../../stores/project'
import { notify } from '../../stores/notice'
import { useAutoRefresh } from '../../hooks'
import { Select } from '../../components/forms'
import {
Actions, Button, CardRow, Chip, Ctlbar, Divider, ErrorText, Field, FieldBlock, FormRow, Grid,
Layout, LINK_CLS, LogBox, LogRow, MONO, MUTED, MUTED_MONO, Panel, PanelHead, Row, Stack, Stat,
TabStack, Table, TableBox, Tag, TagGroup, Value, buttonCls, cellCenter, cellWrap
} from '../../components/ui'
import type { GridStep } from '../../components/ui'
import AgentConsole from './AgentConsole'
/**
* 只放后端 ProjectUpdate 真实接受的字段。
* status 不在这里:项目状态由后端 status.refresh() 按镜头与任务真实进度回写,
* 用户唯一能决定的只有「归档 / 取消归档」,把它做成一个可随便选的下拉是误导。
*/
type ProjectForm = {
name: string
description: string
genre: string
target_duration: number
aspect_ratio: string
resolution: string
fps: number
style_guide: string
global_negative_prompt: string
default_provider: string
default_model: string
default_transition: string
}
const EMPTY_FORM: ProjectForm = {
name: '', description: '', genre: '', target_duration: 60, aspect_ratio: '16:9',
resolution: '720p', fps: 24, style_guide: '', global_negative_prompt: '',
default_provider: '', default_model: '', default_transition: 'cut'
}
/** 流程节点状态的中文口径(与右侧流程控制台一致,但本页沿用旧页措辞) */
const STATE_LABEL: Record<string, string> = { done: '已完成', active: '进行中', pending: '待处理', failed: '异常' }
const STATE_TONE: Record<string, 'ok' | 'bad' | 'warn' | 'info'> = {
done: 'ok', failed: 'bad', active: 'warn', pending: 'info'
}
/** 根据当前节点给出下一步动作建议(对应业务流程图 12 节点) */
type Suggestion = { to: string; label: string; hint: string }
const NEXT_ACTIONS: Record<string, Suggestion[]> = {
create_project: [{ to: 'library', label: '建立人物 / 场景 / 声线', hint: '先建母版,后面每个镜头都能复用' }],
import_storyboard: [
{ to: 'library', label: '先补齐人物与场景', hint: '便于自动绑定' },
{ to: 'storyboard', label: '导入分镜脚本与关键帧', hint: '支持表格 / 文本粘贴' }
],
bind_assets: [{ to: 'storyboard', label: '检查镜头绑定', hint: '人物/场景/说话人/声线' }],
plan_tasks: [{ to: 'dispatch', label: '生成任务清单并入队', hint: '按依赖自动排队' }],
preflight: [
{ to: 'storyboard', label: '修复预检问题', hint: '缺关键帧/提示词' },
{ to: 'dispatch', label: '进入调度中心派发', hint: '预检通过后才能派发' }
],
dispatch: [{ to: 'dispatch', label: '派发 / 排空任务队列', hint: '可暂停、可重试' }],
generate: [{ to: 'dispatch', label: '查看生成任务进度', hint: '关键帧 → 视频' }],
save_output: [{ to: 'dispatch', label: '查看生成任务进度', hint: '产物自动入库' }],
quality_check: [{ to: 'review', label: '查看自动质检结果', hint: '不合格自动重做' }],
review: [{ to: 'review', label: '逐镜审核并放行', hint: '驳回自动回流重生成' }],
revise: [{ to: 'storyboard', label: '修改提示词后重新生成', hint: '驳回回流' }],
compose: [{ to: 'timeline', label: '搭建时间线并合成', hint: '字幕 / 配音一次编排' }],
export: [{ to: 'delivery', label: '导出完整成片', hint: '多平台一键出片' }]
}
/** 统计卡栅格:照旧站 .grid4——≤1180 先并两列,≤560 才塌成一列 */
const STAT_STEPS: GridStep[] = [{ at: 'mid', cols: 2 }, { at: 'narrow', cols: 1 }]
export default function Overview() {
const id = useProjectStore((s) => s.id)
const project = useProjectStore((s) => s.project)
const workflow = useProjectStore((s) => s.workflow)
const stats = useProjectStore((s) => s.stats)
const lastLoad = useProjectStore((s) => s.lastLoad)
const modelRows = useModelsStore((s) => s.rows)
const [form, setForm] = useState<ProjectForm>(EMPTY_FORM)
const [events, setEvents] = useState<any[]>([])
const [level, setLevel] = useState('')
const [eventKeyword, setEventKeyword] = useState('')
const [preflight, setPreflight] = useState<any>(null)
const [error, setError] = useState('')
const [saving, setSaving] = useState(false)
const [editing, setEditing] = useState(false)
const patch = (part: Partial<ProjectForm>) => setForm((prev) => ({ ...prev, ...part }))
/* ───────────────────────── 默认视频模型(能力联动) ───────────────────────── */
/** provider + model 合成一个下拉,取值全部来自模型注册表 */
const videoRef = form.default_provider ? `${form.default_provider}|${form.default_model}` : ''
const setVideoRef = (v: string) => {
const [provider, model] = parseRef(v)
const caps = capsOf(provider, model)
const next: Partial<ProjectForm> = { default_provider: provider, default_model: model }
if (caps.fps > 0) next.fps = caps.fps
// 档位不在模型能力里才回落,且只回落到「原生能出」的最高档:
// 放大交付档(1080p)是合法选项,不能一换模型就被静默踢回 720p。
const deliverable = deliveryResolutions(provider, model)
if (deliverable.length && !deliverable.includes(form.resolution)) {
const native = caps.resolutions.length ? caps.resolutions : deliverable
next.resolution = native[native.length - 1]
}
patch(next)
}
const videoModels = useMemo(() => modelsOf('video'), [modelRows])
const videoCaps = useMemo(
() => capsOf(form.default_provider, form.default_model || null),
[form.default_provider, form.default_model, modelRows]
)
const defaultVideoLabel = defaultFor('video')?.display_name || '后端默认'
const resOptions = useMemo(
() => resolutionChoices(form.default_provider, form.default_model || null),
[form.default_provider, form.default_model, modelRows]
)
const fpsOptions = useMemo(
() => fpsChoices(form.default_provider, form.default_model || null),
[form.default_provider, form.default_model, modelRows]
)
const modelWarnings = capabilityHint(
form.default_provider, form.default_model || null, form.resolution, form.fps, form.aspect_ratio
)
const modeLabels = videoCaps.modes.map((m) => opt('mode', m)).join(' / ') || '—'
/** 项目总时长与「单镜时长区间」是两件事,这里给出模型区间避免排出跑不动的镜头 */
const durationRule = !videoCaps.minDuration && !videoCaps.maxDuration
? '模型未声明时长区间'
: `单镜时长需在 ${videoCaps.minDuration || 0}–${videoCaps.maxDuration || '∞'} 秒内,总时长按镜头数自由累加`
/* ───────────────────────────── 预检 / 事件流 ───────────────────────────── */
const loadExtra = useCallback(async () => {
if (!id) return
setError('')
try {
const [evs, pf] = await Promise.all([
api.get(`/api/projects/${id}/events`, { limit: 80 }),
api.get(`/api/projects/${id}/preflight`)
])
setEvents(evs.events || [])
setPreflight(pf.preflight)
} catch (exc: any) {
setError(exc.message)
}
}, [id])
useAutoRefresh(loadExtra, 15000, false, editing || saving)
useEffect(() => {
loadExtra()
}, [project?.current_stage, loadExtra])
const needle = eventKeyword.trim().toLowerCase()
const shownEvents = useMemo(() => events.filter((e: any) => {
if (level && eventLevelKey(e.level) !== level) return false
if (!needle) return true
return `${e.message || ''} ${e.action || ''} ${eventLabel(e.action)}`.toLowerCase().includes(needle)
}), [events, level, needle])
const badPreflight = useMemo(
() => (preflight?.checks || []).filter((c: any) => !c.ok || (c.issues || []).length),
[preflight]
)
/* ───────────────────────────── 表单回填 / 保存 ───────────────────────────── */
const fill = useCallback(() => {
const p: any = useProjectStore.getState().project || {}
setForm((prev) => {
const next = { ...prev } as Record<string, any>
Object.keys(prev).forEach((k) => {
const v = p[k]
if (v !== undefined && v !== null) next[k] = v
})
// 老项目里残留的 mock 演练通道:注册表已停用 mock 时改跟平台默认视频模型
if (p.default_provider === 'mock' && !modelsOf('video').some((row) => row.provider === 'mock')) {
next.default_provider = ''
next.default_model = ''
}
return next as ProjectForm
})
}, [])
// 项目每 6 秒刷一次、注册表也可能晚于首屏到达,两者都要回填;
// 但编辑态必须跳过:旧站这里没有守卫,正在敲的「名称」会被下一轮轮询原样覆盖回去。
useEffect(() => {
if (editing || saving) return
fill()
}, [lastLoad, modelRows, editing, saving, fill])
const isArchived = project?.status === 'archived'
const finished = allNodesDone(workflow)
/* 「流程推进中」不能挂在已经全部走完 / 已归档的项目上,否则和同一块面板里的
「全部 12 个节点已完成」打嘴架。 */
const flowTagText = isArchived ? '已归档' : finished ? '流程已完成' : '流程推进中'
const flowTagTone = isArchived ? 'warn' : finished ? 'ok' : 'info'
/** 流程走完后不再喊「当前节点」,否则和「已交付」自相矛盾 */
const flowNote = (() => {
const note = stageNote(project, workflow)
return finished || !note ? note : `当前节点:${note}`
})()
const suggestions = NEXT_ACTIONS[project?.current_stage] || NEXT_ACTIONS.create_project
/** 归档是项目状态里唯一由人决定的开关,取消归档后由后端重新推算真实节点 */
const setArchived = async (on: boolean) => {
if (!id) return
setSaving(true)
setError('')
try {
await api.patch(`/api/projects/${id}`, { status: on ? 'archived' : 'draft' })
notify(on ? '项目已归档,不再自动推进流程' : '已取消归档,流程状态按镜头真实进度重算')
await refresh()
} catch (exc: any) {
setError(exc.message)
} finally {
setSaving(false)
}
}
const save = async () => {
if (!id) return
setSaving(true)
setError('')
try {
await api.patch(`/api/projects/${id}`, { ...form })
notify('项目设置已保存')
setEditing(false)
await refresh()
} catch (exc: any) {
setError(exc.message)
} finally {
setSaving(false)
}
}
return (
<TabStack>
<AgentConsole />
<Layout>
<Stack>
{/* 流程节点与指标卡由项目 store 每 6 秒轮询,本页只负责预检与事件流 */}
<Panel>
<PanelHead title="流程节点明细" />
<TableBox maxHeight={false}>
<Table minWidth={720}>
<thead>
<tr>
<th className="w-[64px]">状态</th>
<th>节点</th>
<th>说明</th>
<th className={`${cellCenter} w-[74px]`}>完成度</th>
</tr>
</thead>
<tbody>
{workflow.map((s: any) => (
<tr key={s.key}>
<td><Tag tone={STATE_TONE[s.state] || 'default'}>{STATE_LABEL[s.state] || s.state}</Tag></td>
<td>
<b>{s.label}</b>
<div className={MUTED_MONO}>{s.key}</div>
</td>
<td className={cellWrap}>{s.detail}</td>
<td className={cn(MONO, cellCenter)}>{s.done == null ? '—' : `${s.done}/${s.total}`}</td>
</tr>
))}
</tbody>
</Table>
</TableBox>
</Panel>
<Panel>
<PanelHead
title="素材与参数预检"
right={(
<Tag tone={preflight?.can_generate ? 'ok' : 'bad'}>
{preflight ? (preflight.can_generate ? '可以生成' : '存在阻塞') : '读取中'}
</Tag>
)}
/>
{preflight && (
<Value>
共 {preflight.total} 个镜头:{preflight.ready} 个就绪、{preflight.blocked} 个被阻塞;
错误 {preflight.errors} 项、提醒 {preflight.warnings} 项。
</Value>
)}
{badPreflight.map((c: any) => (
<CardRow
key={c.shot_id}
title={`#${c.order_index} ${c.title}`}
right={<Link className={LINK_CLS} to={`/projects/${id}/storyboard`}>去修复 →</Link>}
>
{(c.issues || []).map((i: any, k: number) => (
<p key={k}>
<Tag tone={i.severity === 'error' ? 'bad' : 'warn'}>{i.severity === 'error' ? '阻塞' : '提醒'}</Tag>
{' '}{i.message}
</p>
))}
</CardRow>
))}
{/* project_issues 是纯文本清单(项目级前置条件),不要按 issue 对象去取 severity */}
{!!preflight?.project_issues?.length && (
<>
<Divider />
{preflight.project_issues.map((i: any, k: number) => (
<p key={`pi${k}`} className="m-[3px]_0 text-caption text-muted leading-[1.55]">
<Tag tone="warn">建议</Tag>{' '}{i}
</p>
))}
</>
)}
{preflight && !badPreflight.length && !preflight.project_issues?.length && (
<Value>✔ 所有镜头的素材与参数均已就绪。</Value>
)}
</Panel>
<Panel>
<PanelHead
title="项目设置"
right={(
<Row tight>
<Tag tone={flowTagTone}>{flowTagText}</Tag>
<Button variant="outline" size="sm" disabled={saving} onClick={() => setArchived(!isArchived)}
title="项目状态由后端按镜头与任务真实进度回写,这里只提供归档开关;归档后不再自动推进流程节点。">
{isArchived ? '取消归档' : '归档项目'}
</Button>
<Button variant="outline" size="sm" onClick={() => setEditing(!editing)}>
{editing ? '收起' : '编辑'}
</Button>
</Row>
)}
/>
{editing ? (
<>
<FormRow>
<Field label="名称">
<input value={form.name} onChange={(e) => patch({ name: e.target.value })} />
</Field>
<Field label="题材">
<input value={form.genre} placeholder="科幻 / 悬疑 / 公路"
onChange={(e) => patch({ genre: e.target.value })} />
</Field>
<Field label="目标总时长(秒)" title={durationRule}>
<input type="number" min={1} value={form.target_duration}
onChange={(e) => patch({ target_duration: Number(e.target.value) })} />
</Field>
<Field label="默认转场">
<Select value={form.default_transition} options={options('transition')}
onChange={(v) => patch({ default_transition: v })} />
</Field>
{/* 旧站是 .span2:模型名带 provider,短栅格里挤成两行看不出选的是谁 */}
<Field label="默认视频模型" className="col-span-2"
title="镜头未单独指定模型时使用;决定可用的分辨率与帧率档位。">
<Select value={videoRef} onChange={setVideoRef}
options={[
{ value: '', label: `跟随平台默认(${defaultVideoLabel})` },
...videoModels.map((r) => ({
value: refOf(r),
label: `${r.display_name || `${r.provider} · ${r.model}`}`
+ `${r.available ? '' : '(未就绪)'}${isMock(r) ? '(演练通道)' : ''}`
}))
]} />
</Field>
<Field label="画幅">
<Select value={form.aspect_ratio} options={options('aspect_ratio')}
onChange={(v) => patch({ aspect_ratio: v })} />
</Field>
<Field label="分辨率">
<Select value={form.resolution} options={resOptions}
onChange={(v) => patch({ resolution: v })} />
</Field>
<Field label="帧率">
<Select value={form.fps} onChange={(v) => patch({ fps: Number(v) })}
options={fpsOptions.map((f) => ({ value: String(f), label: `${f} fps` }))} />
</Field>
</FormRow>
<TagGroup>
<Tag>生成模式 {modeLabels}</Tag>
<Tag>可用档位 {videoCaps.resolutions.join(' / ') || '未声明'}</Tag>
<Tag>帧率 {videoCaps.fps || '未声明'}fps</Tag>
<Tag>单镜 {videoCaps.minDuration || '?'}–{videoCaps.maxDuration || '?'} 秒</Tag>
<Tag>参考图上限 {videoCaps.maxReferenceImages || '未声明'}</Tag>
</TagGroup>
{modelWarnings.map((w, i) => <ErrorText key={`mw${i}`}>{w}</ErrorText>)}
<FieldBlock label="简介">
<textarea rows={2} value={form.description} onChange={(e) => patch({ description: e.target.value })} />
</FieldBlock>
<FieldBlock label="全局风格指南"
title="只写画面感风格;音画一体模型会自动过滤画幅、水印、一致性这类元指令。">
<textarea rows={2} value={form.style_guide} placeholder="只写画面风格:写实电影质感,35mm 浅景深……(音画一体模型会自动过滤画幅/水印/一致性等元指令)"
onChange={(e) => patch({ style_guide: e.target.value })} />
</FieldBlock>
<FormRow>
<Field label="全局负面提示词(音画一体模型不下发)">
<input value={form.global_negative_prompt} placeholder="字幕,水印,角色变形,多手多指"
onChange={(e) => patch({ global_negative_prompt: e.target.value })} />
</Field>
</FormRow>
<Actions>
<Button variant="primary" disabled={saving} onClick={save}>{saving ? '保存中…' : '保存设置'}</Button>
</Actions>
</>
) : (
<Grid cols={3} steps={STAT_STEPS}>
<div>
<small className={MUTED}>风格指南</small>
<Value>{project?.style_guide || '未设置'}</Value>
</div>
<div>
<small className={MUTED}>负面提示词</small>
<Value>{project?.global_negative_prompt || '未设置'}</Value>
</div>
<div>
<small className={MUTED}>默认生成参数</small>
<Value>
{project?.default_model
? `${project?.default_provider} / ${project?.default_model}`
: `跟随平台默认(${defaultVideoLabel})`}
{' · '}{project?.aspect_ratio} · {project?.resolution} @{project?.fps}fps
{' · '}单镜时长区间 {videoCaps.minDuration || '?'}–{videoCaps.maxDuration || '?'} 秒
</Value>
</div>
</Grid>
)}
<ErrorText>{error}</ErrorText>
</Panel>
</Stack>
<Stack>
<Panel>
<PanelHead title="下一步建议" right={<span className={MUTED}>{flowNote}</span>} />
<Actions>
{suggestions.map((a) => (
<Link key={a.to} className={cn(buttonCls({ variant: 'secondary' }), 'no-underline')}
to={`/projects/${id}/${a.to}`}>
{a.label} <span className={MUTED}>· {a.hint}</span>
</Link>
))}
</Actions>
</Panel>
<Panel>
<PanelHead title="资产与镜头统计"
right={<Link className={LINK_CLS} to={`/projects/${id}/library`}>资产库 →</Link>} />
<Grid cols={4} steps={STAT_STEPS}>
<Stat label="人物" value={stats?.characters || 0} />
<Stat label="场景" value={stats?.scenes || 0} />
<Stat label="声线" value={stats?.voices || 0} />
<Stat label="素材文件" value={stats?.assets || 0} />
</Grid>
<Divider />
<Grid cols={4} steps={STAT_STEPS}>
<Stat label="镜头总数" value={stats?.shots || 0} />
<Stat label="待生成" value={stats?.shots_ready || 0} />
<Stat label="已生成" value={stats?.shots_generated || 0} />
<Stat label="审核合格" value={stats?.shots_approved || 0} />
</Grid>
<Divider />
<TagGroup>
{Object.entries(stats?.shot_status || {}).map(([k, v]) => (
<Tag key={k}>{statusLabel(k)} {String(v)}</Tag>
))}
{!Object.keys(stats?.shot_status || {}).length && <span className={MUTED}>尚无镜头状态数据</span>}
</TagGroup>
</Panel>
<Panel>
<PanelHead
title="项目事件流"
right={(
<Ctlbar className="mb-0">
{EVENT_LEVELS.map((lv) => (
<Chip key={lv.value || 'all'} active={level === lv.value} onClick={() => setLevel(lv.value)}>
{lv.label}
</Chip>
))}
<Field label="搜索" width="narrow">
<input value={eventKeyword} aria-label="搜索项目事件" placeholder="事件内容 / 动作"
onChange={(e) => setEventKeyword(e.target.value)} />
</Field>
</Ctlbar>
)}
/>
<LogBox>
{shownEvents.map((e: any) => (
<LogRow key={e.id} level={eventLevelKey(e.level)}
time={<span title={fmtTime(e.created_at)}>{fmtAgo(e.created_at)}</span>}
who={<span className={MONO} title={e.action}>{eventLabel(e.action)}</span>}>
{e.message}
{e.shot_id ? <span className={MUTED}> · 镜头#{e.shot_id}</span> : null}
{e.task_id ? <span className={MUTED}> · 任务#{e.task_id}</span> : null}
</LogRow>
))}
{!!events.length && !shownEvents.length && (
<div className={cn(MUTED, 'flex flex-wrap items-center gap-[9px] p-[8px_2px]')}>
当前筛选条件下没有事件。
<Button variant="outline" size="sm"
onClick={() => { setLevel(''); setEventKeyword('') }}>清除筛选</Button>
</div>
)}
{!events.length && <div className={cn(MUTED, 'p-[8px_2px]')}>暂无事件</div>}
</LogBox>
</Panel>
</Stack>
</Layout>
</TabStack>
)
}