迁移项目总控台与流程概览:LLM 指令台(折叠执行过程/规划计时/阻塞解释)+ 节点明细/预检/项目设置/统计/事件流;Grid 支持两段式降列 steps

main
mula.liu 2026-11-01 18:19:43 +08:00
parent 5e641ffe46
commit 569f4c2f1d
4 changed files with 1422 additions and 6 deletions

View File

@ -73,9 +73,12 @@ export function Stat({ label, value, hint, className }: { label: ReactNode; valu
const STEP_CLS: Record<string, string> = {
'huge:3': 'max-huge:grid-cols-3', 'mid:3': 'max-mid:grid-cols-3', 'mid2:3': 'max-mid2:grid-cols-3',
'nav:2': 'max-nav:grid-cols-2', 'short:2': 'max-short:grid-cols-2', 'mid2:2': 'max-mid2:grid-cols-2',
'mid:2': 'max-mid:grid-cols-2', 'nav:1': 'max-nav:grid-cols-1', 'mid2:1': 'max-mid2:grid-cols-1',
'tiny:1': 'max-tiny:grid-cols-1', 'narrow:1': 'max-narrow:grid-cols-1', 'short:1': 'max-short:grid-cols-1'
}
export type StatStep = { at: 'huge' | 'mid' | 'mid2' | 'nav' | 'short' | 'tiny' | 'narrow'; cols: 1 | 2 | 3 }
/** 通用栅格的降列节奏与指标卡共用一套档位(旧站 .grid3/.grid4 是「≤1180 两列、≤560 一列」两段式) */
export type GridStep = StatStep
/**
* 指标卡栅格:列数与降列节奏都由容器声明,页面不写 @media。
@ -206,16 +209,21 @@ export type GridCollapse = 'mid' | 'mid2' | 'nav' | 'short' | 'tiny' | 'narrow'
/**
* 通用栅格(.grid / .grid2 / .grid3 / .grid4)。
*
* oneAt 只管「到某个断点塌成一列」这一种最省事的收法;旧站 .grid3/.grid4 是两段式
* (≤1180 先并到两列、≤560 才塌成一列),硬用 oneAt="mid" 会让三列在 1100px 就变成
* 一条竖列,所以把 StatGrid 那套 steps 档位挪过来共用:例外写在参数里,不写回 @media。
*
* 列数走 --cols/--min 两个 CSS 变量 + 字面量工具类,而不是内联 grid-template-columns:
* 内联样式会盖掉所有断点类,「窄屏折成一列」就再也写不上去
* (旧站 .grid2 在 ≤560 就是单列,用内联 style 之后这一档静默失效)。
*/
export function Grid({ children, cols = 4, gap = 12, min = 0, oneAt, className }: {
children?: ReactNode; cols?: number; gap?: number; min?: number; oneAt?: GridCollapse; className?: string
export function Grid({ children, cols = 4, gap = 12, min = 0, oneAt, steps, className }: {
children?: ReactNode; cols?: number; gap?: number; min?: number; oneAt?: GridCollapse
steps?: GridStep[]; className?: string
}) {
return (
<div className={cn('grid min-w-0 [&>*]:min-w-0 gap-[var(--gap)] grid-cols-[repeat(var(--cols),minmax(var(--min),1fr))]',
oneAt && ONE_CLS[oneAt], className)}
oneAt && ONE_CLS[oneAt], ...(steps || []).map((st) => STEP_CLS[`${st.at}:${st.cols}`]), className)}
style={{ ['--cols' as string]: cols, ['--min' as string]: `${min}px`, ['--gap' as string]: `${gap}px` }}>
{children}
</div>

View File

@ -0,0 +1,856 @@
/**
* 项目总控台(LLM 编排 / Project Autopilot)。
*
* 为什么单独成文件:它是本页唯一有自己后端资源(`/agent/runs`)、自己轮询节奏
* (2.5 秒而不是项目 store 的 6 秒)、自己状态机的东西——「规划中 → 待确认 →
* 执行中 → 停在审核/阻塞/失败」一整套都在这儿。流程概览那六个面板只是读项目缓存,
* 两者混在一个文件里会让 1500 行的概览页谁也读不动。
*
* 交互上有三条是踩过坑的,迁移时一条都不能少:
* 1. 执行过程默认按指令收拢,一屏只展开一条(页面高度由指令条数决定,不由步骤数决定);
* 唯一的例外是自己刚下达/刚点执行的那条,由 replaceRun 主动展开。
* 2. 规划进度在后端线程里跑,前端只轮询那条 planning 记录:刷新页面计时也能接上。
* 3. 「点了执行但项目没动」以前只有一行 10px 小字,用户以为按钮坏了;
* 现在服务端拒绝(409)或记录已终结时,展开成一段常驻说明 + 「把这条指令重新下达」。
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import * as api from '../../api/client'
import { fmtAgo, fmtTime } from '../../lib/format'
import { cn } from '../../lib/cn'
import { notify } from '../../stores/notice'
import { useProjectStore } from '../../stores/project'
import { loadModels } from '../../stores/models'
import { Select } from '../../components/forms'
import {
BarRight, Between, Button, buttonCls, Check, Ctlbar, ErrorText, Eyebrow, Field, MONO, Mono, MUTED, Row, Tag, Value
} from '../../components/ui'
/** 计划里的一步(白名单动作),status: pending/running/succeeded/skipped/failed */
type AgentStep = {
action: string
label?: string
reason?: string
status: string
detail?: string
shot_ids?: number[]
}
/** 一次「指令 → 计划 → 执行」的完整记录(后端 agent.run_dict) */
type AgentRun = {
id: number
status: string
intent?: string
request_text?: string
reply?: string
summary?: string
provider?: string
model?: string
auto_approve?: boolean
cancel_requested?: boolean
steps?: AgentStep[]
blockers?: string[]
warnings?: string[]
error_message?: string
can_execute?: boolean
plan_stats?: {
elapsed_seconds?: number
completion_tokens?: number
reasoning_tokens?: number
thinking?: string
}
created_at?: string
updated_at?: string
finished_at?: string
}
/** 执行过程折叠时,一屏先给几条指令;其余收进「展开全部」 */
const HISTORY_PAGE = 6
const THINKING_OPTIONS = [
{ value: 'off', label: '快速(关思考)' },
{ value: 'low', label: '有限思考' },
{ value: 'high', label: '充分思考' }
]
/** 单步超时:生成类步骤(尤其是视频)动辄十几分钟,档位给到 4 小时封顶 */
const TIMEOUT_OPTIONS = [
{ value: 1800, label: '30 分钟' },
{ value: 3600, label: '1 小时' },
{ value: 7200, label: '2 小时' },
{ value: 14400, label: '4 小时' }
]
const PRESETS = [
'从当前进度继续,补齐关键帧和镜头,质检合格后在这里停下等我审核。',
'把已通过质检的镜头推进到时间线和最终成片,已有产物不要重复生成。',
'检查当前项目为什么不能交付,只处理能安全自动完成的步骤。'
]
const STATUS_LABELS: Record<string, string> = {
planning: 'LLM 规划中', planned: '待确认执行', running: '正在调度',
waiting_review: '等待人工审核', blocked: '存在阻塞', succeeded: '计划完成',
failed: '执行暂停', cancelled: '已取消'
}
const STATUS_TONES: Record<string, 'default' | 'ok' | 'bad' | 'warn' | 'info'> = {
planning: 'warn', planned: 'info', running: 'warn', waiting_review: 'warn', blocked: 'bad',
succeeded: 'ok', failed: 'bad', cancelled: 'default'
}
/** 阻塞 / 风险 / 提示三种配色的说明块共用一套骨架 */
const CALLOUT = 'mt-[10px] p-[10px_12px] border border-accent-line rounded-[8px] bg-raised'
const CALLOUT_TITLE = 'text-tiny tracking-[.7px]'
const CALLOUT_TEXT = 'mt-[5px] mb-0 text-ink-3 text-[10.5px] leading-[1.5]'
const CALLOUT_EMPTY = 'p-[18px] border border-dashed border-line-strong rounded-[10px] text-faint '
+ 'text-[11px] leading-[1.65] text-center'
/** planning 记录的起点时间:刷新页面后计时要继续接着走,不能从 0 重来 */
function planningSeconds(row: AgentRun | null) {
const iso = row?.created_at
if (!iso) return 0
const date = new Date(String(iso).endsWith('Z') ? String(iso) : `${iso}Z`)
if (Number.isNaN(date.getTime())) return 0
return Math.max(0, Math.round((Date.now() - date.getTime()) / 1000))
}
/** 计划元信息按行取:折叠列表里任何一条都可能被展开,不能再依赖「当前选中」 */
function planStat(row: AgentRun) {
const stats = row.plan_stats || {}
const bits: string[] = []
if (stats.elapsed_seconds) bits.push(`计划耗时 ${stats.elapsed_seconds}s`)
if (stats.completion_tokens) {
bits.push(stats.reasoning_tokens
? `输出 ${stats.completion_tokens} tokens(其中思考 ${stats.reasoning_tokens})`
: `输出 ${stats.completion_tokens} tokens`)
}
if (stats.thinking) {
bits.push(`深度思考:${THINKING_OPTIONS.find((item) => item.value === stats.thinking)?.label || stats.thinking}`)
}
return bits.join(' · ')
}
const handledSteps = (row: AgentRun) => (row.steps || [])
.filter((step) => step.status === 'succeeded' || step.status === 'skipped').length
const skippedSteps = (row: AgentRun) => (row.steps || [])
.filter((step) => step.status === 'skipped').length
/** 折叠着也要说清「现在跑到哪一步」,否则执行中还得点开确认 */
const runningStep = (row: AgentRun) => (row.steps || []).find((step) => step.status === 'running') || null
function stepStatusLabel(status: string) {
if (status === 'pending') return '待执行'
if (status === 'running') return '执行中'
if (status === 'skipped') return '无需重复执行'
if (status === 'failed') return '已暂停'
return '完成'
}
/** 质检这一步在「计划完成」的记录里必然是 skipped,光写「无需重复执行」会被当成漏跑 */
function stepDetail(step: AgentStep, run: AgentRun) {
if (step.action === 'quality_check' && step.status === 'skipped' && run.status === 'succeeded') {
return '生成阶段已完成自动质检,本步骤无需重复提交'
}
return step.detail || ''
}
/** 失败步骤该去哪个页签善后:动作 → 页签的白名单映射,和后端 STEP_HANDLERS 同构 */
function stepTarget(action: string) {
if (action === 'generate_keyframes') return 'storyboard'
if (action === 'generate_shots' || action === 'resume') return 'dispatch'
if (action === 'quality_check' || action === 'approve_passed') return 'review'
if (action === 'build_timeline') return 'timeline'
if (action === 'compose') return 'delivery'
return 'storyboard'
}
function executeLabel(row: AgentRun) {
if (row.status === 'waiting_review') return '继续剩余计划'
if (row.status === 'failed') return '重试暂停步骤'
return '确认并一键执行'
}
/** 折叠行的箭头:展开时转 90° 并点亮,「这一行能不能点开」不该靠猜 */
function Caret({ open }: { open: boolean }) {
return (
<span aria-hidden
className={cn('grid flex-none w-[26px] h-[26px] place-items-center rounded-full border leading-none '
+ 'transition-[transform,border-color,background,color] duration-150',
open ? 'rotate-90 border-accent-fill bg-accent-fill text-on-accent'
: 'border-line-strong bg-raised text-ink-2 group-hover:border-accent-line group-hover:text-ink-2')}>
<svg viewBox="0 0 20 20" className="block w-4 h-4">
<path d="M7.5 5 12.5 10 7.5 15" fill="none" stroke="currentColor" strokeWidth="2"
strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
)
}
/** 规划中/空态背景里那条来回扫的横线:表示「服务端还在算」,不是装饰 */
function Scanline() {
return <div aria-hidden className="absolute left-[9%] right-[9%] top-0 h-px opacity-[.45] animate-agent-scan bg-[linear-gradient(90deg,transparent,var(--c-accent-fill),transparent)]" />
}
/* 多段渐变背景各自保持成一个完整字面量:Tailwind 只扫描源码里连续出现的候选串,
一条类名被字符串拼接劈成两半就永远不会被生成。 */
const CONSOLE_BG = 'bg-[radial-gradient(circle_at_88%_-20%,color-mix(in_srgb,var(--c-accent)_16%,transparent),transparent_34%),radial-gradient(circle_at_10%_130%,var(--c-tint-accent),transparent_40%),linear-gradient(135deg,var(--c-bg-panel)_0%,var(--c-bg-card)_54%,var(--c-bg-raised)_100%)]'
const MARK_BG = 'bg-[linear-gradient(145deg,var(--c-accent-fill),var(--c-accent-fill-deep))]'
const MARK_GLOW = 'shadow-[0_0_28px_color-mix(in_srgb,var(--c-accent)_20%,transparent)]'
const PULSE_GLOW = 'shadow-[0_0_0_0_color-mix(in_srgb,var(--c-accent)_60%,transparent)]'
const THINKING_BG = 'bg-[radial-gradient(circle_at_50%_0%,var(--c-tint-accent),transparent_62%),repeating-radial-gradient(circle_at_center,transparent_0_25px,color-mix(in_srgb,var(--c-accent)_4%,transparent)_26px_27px)]'
const HERO_BG = 'bg-[radial-gradient(circle_at_center,color-mix(in_srgb,var(--c-accent)_8%,transparent),transparent_55%),repeating-radial-gradient(circle_at_center,transparent_0_25px,color-mix(in_srgb,var(--c-accent)_4%,transparent)_26px_27px)]'
const FADE_BG = 'bg-[linear-gradient(to_bottom,transparent,color-mix(in_srgb,var(--c-bg-card)_92%,transparent))]'
const REPLY_BG = 'bg-[color-mix(in_srgb,var(--c-accent)_6%,transparent)]'
/**
* 规划中的渐进清单。
*
* 一次计划 = 一次完整的模型调用,思考型模型要 30~120 秒,期间页面什么都不动。
* 旧版只有一句「正在生成计划」,用户普遍以为卡死并刷新页面;现在把后端那几步
* 摊开成清单按秒点亮(点亮节奏跟着思考档位走),并在 409 之外保留「取消这次规划」。
*/
function Thinking({ planSeconds, thinking, thinkingLabel, autoExecute, planMarks, busy, onCancel }: {
planSeconds: number; thinking: 'off' | 'low' | 'high'; thinkingLabel: string
autoExecute: boolean; planMarks: number[]; busy: string; onCancel: () => void
}) {
const items = [
{ text: '盘点镜头 / 关键帧 / 已生成产物', on: planSeconds >= 0 },
{ text: '核对人物、场景、声线与模型能力', on: planSeconds >= planMarks[0] },
{ text: '排定白名单步骤并做 JSON 校验', on: planSeconds >= planMarks[1] },
{ text: autoExecute ? '生成完立即开始执行' : '等待你点击「确认并一键执行」', on: autoExecute }
]
return (
<div className={cn('relative overflow-hidden p-[18px_16px] border border-accent-line rounded-[10px]', THINKING_BG)}>
<Scanline />
<b className="block text-ink-2 text-title">
LLM 正在盘点项目
<Mono className="ml-1.5 text-accent-fill text-[12px]">{planSeconds}s</Mono>
<Mono className="ml-1.5 px-1.5 py-px border border-current rounded-pill text-tiny font-medium opacity-75">
{thinkingLabel}
</Mono>
</b>
<p className="mt-2 mb-0 text-faint text-caption leading-[1.7]">
计划是一次完整的模型调用:{thinking === 'high' ? '充分思考通常需要 30~120 秒'
: thinking === 'low' ? '有限思考通常 5~20 秒' : '关思考通常 3~8 秒'};期间页面不会推进,属正常现象。
</p>
<Row className="mt-1 mb-2 gap-[10px]">
<Button variant="outline" size="sm" disabled={!!busy} onClick={onCancel}>取消这次规划</Button>
<span className="text-faint text-tiny">记录已落库,刷新页面也会继续显示进度</span>
</Row>
<ol className="m-[16px_0_0] p-0 list-none grid gap-2">
{items.map((item, i) => (
<li key={item.text}
className={cn('flex items-center gap-[9px] text-faint text-caption opacity-[.45] '
+ 'transition-[opacity,color] duration-300 min-w-0', item.on && 'text-ink-2 opacity-100')}>
<i className={cn('grid w-[19px] h-[19px] flex-none place-items-center border border-line-strong '
+ 'rounded-full font-mono text-tiny leading-none font-semibold',
item.on && 'border-accent-line bg-accent-fill text-on-accent')}>{i + 1}</i>
{item.text}
</li>
))}
</ol>
</div>
)
}
export default function AgentConsole() {
const projectId = useProjectStore((s) => s.id)
const project = useProjectStore((s) => s.project)
const [runs, setRuns] = useState<AgentRun[]>([])
/** 后端带回的总条数可能大于本页条数(上限 100),列表标题要按真实总数说 */
const [runsTotal, setRunsTotal] = useState(0)
/** 执行过程按指令折叠:这里只存「当前点开的是哪条指令」,null = 全部收拢 */
const [openId, setOpenId] = useState<number | null>(null)
const [busy, setBusy] = useState('')
const [planError, setPlanError] = useState('')
/** 执行被拒绝时的常驻提示:小字报错容易被忽略,用户会以为「点了执行没反应」 */
const [notice, setNotice] = useState<{ title: string; lines: string[]; runId: number | null } | null>(null)
const [message, setMessage] = useState('')
const [autoApprove, setAutoApprove] = useState(false)
const [autoExecute, setAutoExecute] = useState(true)
const [timeoutSec, setTimeoutSec] = useState(7200)
/** 思考型模型的回答耗时几乎全花在思考 token 上,三档实测 3.6s / 12s / 110s+ */
const [thinking, setThinking] = useState<'off' | 'low' | 'high'>('low')
const [planSeconds, setPlanSeconds] = useState(0)
const [historyExpanded, setHistoryExpanded] = useState(false)
const taRef = useRef<HTMLTextAreaElement | null>(null)
// 刚下达/刚启动的这几十秒里多轮询几次:计划刚落库时状态会短暂停在 planned,
// 服务端紧接着才翻到 running,只认 planning/running 会让页面停在「待确认执行」。
const pollUntil = useRef(0)
/* 轮询回调和几个动作函数都在 await 之后要读「当下」的状态,
直接闭包捕获会拿到发起请求那一刻的旧数组,统一用 ref 转接。
gate 每帧重写:2.5 秒的 interval 只想读最新值,不该为了读到新值重建定时器。 */
const runsRef = useRef(runs)
const openRunRef = useRef<AgentRun | null>(null)
const gate = useRef({ running: false, planning: false, pollUntil: 0 })
/** 展开查看的那条指令;全部折叠时为 null,右侧只剩一行行指令标题 */
const openRun = useMemo(() => runs.find((row) => row.id === openId) || null, [runs, openId])
/** 最新一条指令:折叠时模型标签以它为准 */
const latest = runs[0] || null
const planningRun = useMemo(() => runs.find((row) => row.status === 'planning') || null, [runs])
/** 有没有在跑得看全部记录:展开的那条未必是正在执行的那条 */
const isRunning = runs.some((row) => row.status === 'running')
// 规划状态以后端记录为准:请求返回后线程还在跑,刷新页面也能接着看
const planning = !!planningRun || busy.includes('LLM')
/** 三档思考耗时差一个数量级,渐进清单的点亮节奏要跟着档位走,否则看起来像卡死 */
const planMarks = thinking === 'off' ? [1, 2] : thinking === 'low' ? [3, 8] : [6, 15]
const thinkingLabel = THINKING_OPTIONS.find((row) => row.value === thinking)?.label || '有限思考'
runsRef.current = runs
openRunRef.current = openRun
gate.current = { running: isRunning, planning, pollUntil: pollUntil.current }
const visibleRuns = useMemo(() => {
const list = historyExpanded ? runs.slice() : runs.slice(0, HISTORY_PAGE)
if (openRun && !list.some((row) => row.id === openRun.id)) list.push(openRun)
return list
}, [runs, historyExpanded, openRun])
const loadAgent = useCallback(async (silent = true) => {
if (!projectId) return
if (!silent) setBusy('读取调度记录')
const wasPlanning = openRunRef.current?.status === 'planning'
const plannedId = openRunRef.current?.id ?? null
let list: AgentRun[] = []
try {
const data: any = await api.get(`/api/projects/${projectId}/agent/runs`, { limit: 30 })
list = data.runs || []
setRuns(list)
setRunsTotal(Number(data.total ?? list.length))
// 记录被清理或还没落库时,别留一个指向空气的展开态
setOpenId((cur) => (list.some((row) => row.id === cur) ? cur : null))
setPlanError('')
} catch (exc: any) {
setPlanError(exc.message)
} finally {
if (!silent) setBusy('')
}
if (!wasPlanning || !plannedId) return
const fresh = list.find((row) => row.id === plannedId)
if (!fresh || fresh.status === 'planning') return
if (fresh.status === 'failed') {
setPlanError(fresh.error_message || 'LLM 规划失败,请重新下达指令')
} else if (fresh.status === 'running') {
setNotice(null)
notify(`计划已生成(${fresh.steps?.length || 0} 步),服务端已开始执行,无需再点一次`)
} else if (fresh.status === 'planned') {
notify(`执行计划已生成(${fresh.steps?.length || 0} 步),请确认后执行`)
} else {
notify(fresh.summary || 'LLM 已完成诊断')
}
}, [projectId])
/** 刚下达/刚点执行的这条必须展开:用户要立刻看到计划生成与执行过程 */
const replaceRun = (run: AgentRun) => {
setRuns((cur) => {
const index = cur.findIndex((row) => row.id === run.id)
if (index < 0) return [run, ...cur]
const next = cur.slice()
next[index] = run
return next
})
setOpenId(run.id)
}
/** 解释「点了执行但项目没推进」:区分计划已跑完、没有待执行步骤、模型还在规划三种情况 */
const explainStaleRun = (run: AgentRun, raw = '') => {
const lines: string[] = []
if (raw) lines.push(`服务端返回:${raw}`)
if (run.status === 'succeeded') {
const endedAt = run.finished_at ? `${fmtTime(run.finished_at)} 结束` : '时间未记录'
lines.push(`RUN #${run.id} 已经执行完毕(${endedAt})。一条调度记录只跑一次,再点不会重复生成,也不会有新的推进。`)
lines.push(project?.status === 'delivered'
? '项目当前已是「已交付」:成片、时间线、配音都在,直接去成片页查看,或下达一条新指令让模型重做指定镜头。'
: '要看这次的结果请点开这条指令查看执行过程;要继续推进请下达一条新指令,模型会按当前进度重新排程,已有产物不会重复生成。')
} else if (run.status === 'cancelled') {
lines.push(`RUN #${run.id} 已被取消,剩余步骤不会再跑;请重新下达指令生成新的计划。`)
} else if (run.status === 'blocked') {
const blockers = (run.blockers || []).map((item) => String(item)).filter(Boolean)
lines.push(`RUN #${run.id} 的结论是「存在阻塞」:模型判断没有可以自动完成的步骤,所以项目不会推进。`)
lines.push(blockers.length
? `阻塞项:${blockers.join(';')}`
: '这条记录没有带回阻塞明细,请点开这条指令查看计划。')
lines.push(run.reply
? `模型建议:${run.reply}`
: '请把缺少的内容写进新指令重新下达,例如直接给出主题或先导入分镜。')
} else if (run.status === 'waiting_review') {
lines.push(`RUN #${run.id} 停在人工审核节点:到分镜工作台通过审核,或勾选「质检合格后允许 AI 代审」后重新下达指令继续。`)
} else if (run.status === 'running') {
lines.push('这条调度正在跑,重复点击不会追加执行;进度会在右侧这条指令上实时更新。')
} else if (run.status === 'planning') {
lines.push('LLM 还在盘点项目并生成计划(思考型模型可能要 1~2 分钟),计划落地前没有可执行步骤,稍候会自动出现。')
} else if (!run.steps?.length) {
lines.push(`RUN #${run.id} 的计划里没有可执行步骤:模型判断当前进度不需要重复生成,所以项目看起来「没动」。`)
lines.push('如果想强制重做,请在指令里写明范围,例如「重新生成镜头 2 的画面与配音」。')
} else {
lines.push(`这条记录当前状态是「${STATUS_LABELS[run.status] || run.status}」,不能再次执行。`)
}
setNotice({ title: '这次点击没有启动新的调度,原因如下', lines, runId: run.id ?? null })
notify('这条调度记录不能再执行一次,页面已给出下一步建议')
}
const planAgent = async () => {
if (!projectId || !message.trim()) return
setBusy('LLM 正在分析项目')
setPlanError('')
setNotice(null)
try {
// wait=false:后端先把 planning 记录落库并立刻返回,模型规划与后续执行
// 都在服务端线程里推进,页面只要轮询这条 run 就能看到进度
const data: any = await api.post(`/api/projects/${projectId}/agent/plan`, {
message: message.trim(),
auto_approve: autoApprove,
thinking,
wait: false,
auto_execute: autoExecute,
timeout_seconds: Number(timeoutSec)
})
replaceRun(data.run)
pollUntil.current = Date.now() + (autoExecute ? 120 : 30) * 1000
notify(autoExecute
? '指令已受理,LLM 正在盘点项目,计划生成后服务端会自动执行到底'
: '指令已受理,LLM 正在盘点项目,稍候可确认执行计划')
await loadAgent()
} catch (exc: any) {
setPlanError(exc.message)
} finally {
setBusy('')
}
}
const executeAgent = async (row?: AgentRun) => {
const run = row || openRun
if (!run || !projectId) return
setBusy('正在启动调度')
setPlanError('')
// 页面停留在旧状态时这里会拿到一条已终结的记录:先把话说清楚,
// 不要再发那次注定被服务端拒绝的请求(以前只有一行小字,像「点了没反应」)
if (!run.can_execute) {
setBusy('')
await loadAgent()
explainStaleRun(runsRef.current.find((item) => item.id === run.id) || run)
return
}
try {
const data: any = await api.post(`/api/projects/${projectId}/agent/runs/${run.id}/execute`, {
wait: false,
timeout_seconds: Number(timeoutSec)
})
setNotice(null)
replaceRun(data.run)
pollUntil.current = Date.now() + 30 * 1000
await loadAgent()
notify('项目调度已启动,进度会在这里实时更新')
} catch (exc: any) {
await loadAgent()
const fresh = runsRef.current.find((item) => item.id === run.id) || run
if (exc?.status === 409) explainStaleRun(fresh, exc.message)
else setPlanError(exc.message)
} finally {
setBusy('')
}
}
const cancelAgent = async (row?: AgentRun) => {
const run = row || openRun
if (!run || !projectId) return
setBusy('正在请求取消')
try {
const data: any = await api.post(`/api/projects/${projectId}/agent/runs/${run.id}/cancel`, {
reason: '用户在项目主页取消智能调度'
})
replaceRun(data.run)
notify(run.status === 'running' ? '已请求取消,当前步骤结束后停止'
: run.status === 'planning' ? '已取消这次规划,模型返回的结果将被丢弃' : '计划已取消')
} catch (exc: any) {
setPlanError(exc.message)
} finally {
setBusy('')
}
}
/** 把被拒那次指令原样放回输入框,用户改几个字就能重新下达 */
const reuseInstruction = () => {
const target = runs.find((row) => row.id === notice?.runId) || openRun
const text = String(target?.request_text || message || '').trim()
setNotice(null)
if (text) setMessage(text)
const box = taRef.current
if (box) {
box.focus()
box.setSelectionRange(text.length, text.length)
}
}
/** 点开一条、收起其余:一屏只有一条在渲染执行过程 */
const toggleRun = (id: number) => setOpenId((cur) => (cur === id ? null : id))
useEffect(() => {
loadModels()
void loadAgent(false)
}, [loadAgent])
// 2.5 秒轮询只在「有事发生」时跑:折叠列表里有一条在跑、有规划,
// 或刚下达/刚点执行还在 pollUntil 窗口内。其余时间一条请求都不发。
useEffect(() => {
const timer = window.setInterval(() => {
const g = gate.current
if (g.running || g.planning || Date.now() < g.pollUntil) void loadAgent()
}, 2500)
return () => window.clearInterval(timer)
}, [loadAgent])
/**
* 规划计时。
*
* 旧站用 start/stop/sync 三个函数手动开关一个 interval,漏调一次就永远转下去;
* 这里交给 effect:planning 为真就转,为假随卸载清掉,起点每次按 created_at 绝对回算。
* 起点只认 planningRun,不能退回到 latest——POST 还在飞的几十秒里 latest 是上一条
* 历史记录,拿它算会先蹦出一个几百秒的大数。
*/
useEffect(() => {
if (!planning) return
setPlanSeconds(planningRun ? planningSeconds(planningRun) : 0)
const tick = window.setInterval(() => setPlanSeconds((n) => n + 1), 1000)
return () => window.clearInterval(tick)
}, [planning, planningRun])
const sendLabel = planning ? `正在生成计划… ${planSeconds}s`
: busy || (autoExecute ? '生成计划并执行' : '生成执行计划')
/** 失败步骤该去哪个页签善后 */
const failurePath = (row: AgentRun) => {
const step = (row.steps || []).find((item) => item.status === 'failed')
return `/projects/${projectId}/${stepTarget(step?.action || '')}`
}
return (
<section className={cn('animate-agent-in relative min-w-0 overflow-hidden mb-5 rounded-[16px] border border-line-strong p-5 shadow-[0_18px_55px_var(--c-shade-2)] max-[620px]:p-[14px] max-[620px]:rounded-[12px]', CONSOLE_BG)}>
{/* 控制台底纹(旧 .agent-console::before):mask 要带 -webkit 前缀,
用内联样式一次写清,比在类名里叠四条 arbitrary 好读。 */}
<div aria-hidden className="pointer-events-none absolute inset-0 opacity-[.16]"
style={{
backgroundImage: 'linear-gradient(color-mix(in srgb, var(--c-accent) 8%, transparent) 1px, transparent 1px),'
+ 'linear-gradient(90deg, color-mix(in srgb, var(--c-accent) 8%, transparent) 1px, transparent 1px)',
backgroundSize: '32px 32px',
maskImage: 'linear-gradient(90deg, black, transparent 70%)',
WebkitMaskImage: 'linear-gradient(90deg, black, transparent 70%)'
}} />
<div className="relative z-[1] flex items-start justify-between gap-[18px] border-b border-hairline pb-[17px] min-w-0 max-[620px]:flex-col max-[620px]:items-start">
<div className="flex items-center gap-[13px] min-w-0">
<div className={cn('grid place-items-center w-[45px] h-[45px] flex-none rounded-[13px] text-on-accent text-[23px] font-extrabold', MARK_BG, MARK_GLOW)}>
N
</div>
<div className="min-w-0">
<Eyebrow>PROJECT AUTOPILOT · LLM ORCHESTRATION</Eyebrow>
<h2 className="mt-[3px] mb-0 text-lg font-bold"
title="用一句话下达目标。系统 LLM 负责诊断与排程,平台只执行已确认的白名单步骤。">
项目总控台
</h2>
</div>
</div>
<div className="flex items-center gap-2 text-muted text-[10.5px] whitespace-nowrap max-[620px]:whitespace-normal">
{latest
? <Tag tone="info" className="font-mono">{latest.provider}/{latest.model}</Tag>
: <Tag>读取默认 LLM</Tag>}
<span className={cn('w-[7px] h-[7px] flex-none rounded-full bg-line-bright',
isRunning && cn('bg-accent-fill animate-agent-pulse', PULSE_GLOW))} />
<span>{busy || (isRunning ? '调度进行中' : '等待指令')}</span>
</div>
</div>
<div className="relative z-[1] grid min-w-0 grid-cols-[minmax(290px,.82fr)_minmax(0,1.45fr)] gap-5 pt-[18px] max-nav:grid-cols-1">
{/* ── 左:下达指令 ─────────────────────────────────────────── */}
<div className="min-w-0 pr-5 border-r border-hairline max-nav:pr-0 max-nav:pb-[18px] max-nav:border-r-0 max-nav:border-b max-nav:border-hairline">
<label className="block m-0 mb-2 text-ink-2 text-[10px] font-bold tracking-[1.2px]" htmlFor="agent-command">
任务指令
</label>
<textarea
id="agent-command"
ref={taRef}
rows={5}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault()
void planAgent()
}
}}
placeholder="例如:把当前分镜完整生成到成片;质检合格后自动放行,已有产物不要重复生成。"
className="w-full min-h-[118px] resize-y px-[14px] py-[13px] border-accent-line bg-sunken leading-[1.65]"
/>
<div className="flex flex-wrap gap-1.5 mt-2 min-w-0">
{PRESETS.map((text) => (
<Button key={text} variant="outline" size="sm" className="max-w-full overflow-hidden text-ellipsis text-muted"
onClick={() => setMessage(text)}>
{text.slice(0, 18)}…
</Button>
))}
</div>
<Ctlbar className="mt-3 mb-2 gap-x-4">
<Check checked={autoExecute} onChange={setAutoExecute} className="text-ink-2 text-[11px]">
计划生成后立即执行
</Check>
<Check checked={autoApprove} onChange={setAutoApprove} className="text-ink-2 text-[11px]">
质检合格后允许 AI 代审
</Check>
<BarRight className="gap-[10px]">
<Field label="深度思考" width="narrow">
{/* 旧站 .agent-options :deep(.fselect-trigger){padding-inline:8px}:
紧凑档下拉的 10px 内边距在 122px 字段里会把「有限思考」顶出格子 */}
<Select value={thinking} onChange={(v) => setThinking(v)} options={THINKING_OPTIONS}
className="[&>button]:px-2" />
</Field>
<Field label="单步超时" width="narrow">
<Select value={timeoutSec} onChange={(v) => setTimeoutSec(v)} options={TIMEOUT_OPTIONS}
className="[&>button]:px-2" />
</Field>
</BarRight>
</Ctlbar>
<div className="flex items-center gap-2.5 mt-3 min-w-0">
<Button variant="primary" className="min-w-[142px]" disabled={!!busy || planning || !message.trim()}
onClick={() => void planAgent()}>
{sendLabel}
</Button>
<span className={MUTED}>⌘ / Ctrl + Enter</span>
</div>
<ErrorText className="mt-2.5 block p-[8px_10px] border border-danger-line rounded-control bg-raised">
{planError}
</ErrorText>
{notice && (
<div className={cn(CALLOUT, 'grid gap-1.5 border-danger-line')}>
<b className={CALLOUT_TITLE}>{notice.title}</b>
{notice.lines.map((line, i) => <p key={`an${i}`} className={CALLOUT_TEXT}>{line}</p>)}
<Row className="mt-1 gap-2">
<Button variant="primary" size="sm" onClick={reuseInstruction}>把这条指令重新下达</Button>
<Button variant="outline" size="sm" onClick={() => setNotice(null)}>知道了</Button>
</Row>
</div>
)}
</div>
{/* ── 右:指令列表 + 展开的执行过程 ─────────────────────────── */}
<div className="min-w-0 max-h-[min(760px,78vh)] overflow-auto pr-[3px] scrollbar-slim max-nav:max-h-none">
{planning && !planningRun && (
<p className={cn('relative overflow-hidden m-0 mb-[9px] p-[9px_11px] border border-accent-line rounded-[10px] text-muted text-[10.5px]', THINKING_BG)}>
LLM 正在盘点项目 <Mono className="ml-[5px] text-accent-fill">{planSeconds}s</Mono>
,计划生成后挂在对应的指令下,点开即可查看。
</p>
)}
{!!runs.length && (
<>
<div className="flex flex-wrap items-center gap-[9px] pb-2 border-b border-line text-muted text-tiny min-w-0">
<b className="text-ink-2 text-[10.5px] tracking-[.4px]" title="执行过程默认收拢,点任意一行即可展开">
指令 · 共 {Math.max(runsTotal, runs.length)} 条
</b>
{runs.length > HISTORY_PAGE && (
<button type="button" onClick={() => setHistoryExpanded((on) => !on)}
className="px-[7px] py-[2px] border border-line rounded-pill bg-transparent text-ink-2 text-tiny hover:border-line-strong hover:bg-raised">
{historyExpanded ? `只看最近 ${HISTORY_PAGE} 条` : `全部 ${runs.length} 条`}
</button>
)}
{runsTotal > runs.length && <Value className="text-faint text-[10px]">这里显示最近 {runs.length} 条</Value>}
</div>
{visibleRuns.map((row) => {
const open = row.id === openId
const live = row.status === 'running' || row.status === 'planning'
const step = runningStep(row)
return (
<div key={row.id}
className={cn('group mt-[5px] rounded-[9px] border transition-colors duration-150',
open ? 'border-line-strong bg-raised'
: live ? 'border-warn-line'
: 'border-transparent hover:border-line hover:bg-raised')}>
<button type="button" aria-expanded={open} onClick={() => toggleRun(row.id)}
title={open ? '收起这条指令的执行过程' : '展开这条指令的执行过程'}
className="flex w-full items-center gap-[9px] p-[8px_9px] rounded-[9px] border-0 bg-transparent text-left text-tiny text-muted cursor-pointer [&>*]:self-center max-[620px]:flex-wrap max-[620px]:gap-y-[5px]">
<Caret open={open} />
<Mono className={cn('flex-none', open ? 'text-ink-3' : 'text-faint')}>#{row.id}</Mono>
<span className="flex flex-col gap-[3px] min-w-[120px] flex-1 max-[620px]:order-5 max-[620px]:min-w-0 max-[620px]:flex-[1_1_100%]">
<span className={cn('line-clamp-2 whitespace-normal leading-[1.5] break-words',
open ? 'text-ink-2' : 'group-hover:text-ink-2')}
title={row.request_text}>
{row.request_text || '(这条没有留下指令原文)'}
</span>
{row.status === 'planning' && (
<span className={cn('inline-flex items-center gap-[5px] text-warn-bright text-[10px]', 'before:content-[""] before:flex-none before:w-[5px] before:h-[5px] before:rounded-full before:bg-current', live && 'before:animate-agent-pulse')}>
LLM 正在盘点项目 <Mono className="ml-[3px]">{planSeconds}s</Mono>
</span>
)}
{row.status !== 'planning' && step && (
<span className="inline-flex items-center gap-[5px] text-warn-bright text-[10px] before:content-[''] before:flex-none before:w-[5px] before:h-[5px] before:rounded-full before:bg-current before:animate-agent-pulse">
正在执行第 {handledSteps(row) + 1}/{row.steps?.length} 步:{step.label}
</span>
)}
</span>
{!!row.steps?.length && (
<span className="flex-none text-tiny px-[6px] py-px rounded-pill bg-hover text-ink-2">
{handledSteps(row)}/{row.steps.length} 步
</span>
)}
<span className="flex-none text-tiny text-faint tabular-nums">
{fmtAgo(row.finished_at || row.updated_at || row.created_at)}
</span>
<Tag tone={STATUS_TONES[row.status] || 'default'}
className={cn('flex-none', row.status === 'cancelled' && 'text-danger-bright')}>
{STATUS_LABELS[row.status] || row.status}
</Tag>
<span className={cn('flex-none px-[11px] py-[5px] rounded-pill border bg-raised text-ink-2 text-caption font-medium whitespace-nowrap transition-[border-color,background,color] duration-150',
open ? 'border-accent-fill bg-accent-fill text-on-accent font-semibold'
: 'border-line-strong group-hover:border-accent-line group-hover:text-accent')}>
{open ? '收起执行过程' : '展开执行过程'}
</span>
</button>
{open && (
<div className="mt-0 mr-[9px] mb-[9px] ml-[19px] p-[2px_6px_4px_15px] border-l border-dashed border-line-strong min-w-0 max-[620px]:ml-[7px] max-[620px]:pl-[10px]">
{row.status === 'planning'
? <Thinking planSeconds={planSeconds} thinking={thinking} thinkingLabel={thinkingLabel}
autoExecute={autoExecute} planMarks={planMarks} busy={busy}
onCancel={() => void cancelAgent(row)} />
: (
<>
<div className="flex items-start justify-between gap-3 min-w-0">
<div className="min-w-0">
<h3 className="mt-[2px] mb-0 text-[13.5px] font-bold">{row.summary || '执行计划'}</h3>
{/* 旧站这里写的是 var(--muted,#8b93a7),令牌表里没有 --c-muted,
取不到值时永远走硬编码灰:改成真令牌,深浅主题才会跟着翻。 */}
{!!planStat(row) && (
<p className={cn(MONO, 'mt-1 mb-0 text-caption text-muted')}>{planStat(row)}</p>
)}
</div>
<Row className="[--ctl-h:var(--ctl-h-md)]">
{row.status === 'running' && (
<Button variant="outline" size="sm" disabled={!!busy} onClick={() => void cancelAgent(row)}>
取消
</Button>
)}
</Row>
</div>
{row.reply && (
<div className={cn('mt-[10px] p-[12px_14px] border-l-2 border-accent-fill rounded-r-[9px] text-ink-2 text-label leading-[1.68]', REPLY_BG)}>
{row.reply}
</div>
)}
{!!row.blockers?.length && (
<div className={cn(CALLOUT, 'border-danger-line')}>
<b className={CALLOUT_TITLE}>需要处理</b>
{row.blockers.map((item, i) => (
<p key={`b${i}`} className={CALLOUT_TEXT}>{item}</p>
))}
</div>
)}
{!!row.warnings?.length && (
<div className={cn(CALLOUT, 'border-warn-line')}>
<b className={CALLOUT_TITLE}>风险提醒</b>
{row.warnings.map((item, i) => (
<p key={`w${i}`} className={CALLOUT_TEXT}>{item}</p>
))}
</div>
)}
{!!row.steps?.length ? (
<div className="flex flex-col gap-[7px] mt-[11px] min-w-0">
{row.steps.map((stepItem, index) => (
<div key={stepItem.action}
className={cn('grid grid-cols-[28px_minmax(0,1fr)] gap-[10px] p-[10px_11px] rounded-[9px] border border-line bg-card min-w-0',
(stepItem.status === 'succeeded' || stepItem.status === 'running') && 'border-success-line bg-raised',
stepItem.status === 'failed' && 'border-danger-line bg-raised',
stepItem.status === 'skipped' && 'opacity-[.68]')}>
<div className={cn('grid place-items-center w-6 h-6 rounded-full bg-active text-muted text-tiny font-bold',
stepItem.status === 'succeeded' && 'bg-accent-fill text-on-accent',
stepItem.status === 'running' && 'bg-warn-fill text-warn-ink animate-agent-step',
stepItem.status === 'failed' && 'bg-danger text-danger-ink')}>
{stepItem.status === 'succeeded' ? '✓' : stepItem.status === 'failed' ? '!' : index + 1}
</div>
<div className="min-w-0">
<Between>
<b className="text-label">{stepItem.label}</b>
<Tag tone={stepItem.status === 'succeeded' ? 'ok'
: stepItem.status === 'failed' ? 'bad'
: stepItem.status === 'running' ? 'warn'
: stepItem.status === 'skipped' ? 'info' : 'default'}>
{stepStatusLabel(stepItem.status)}
</Tag>
</Between>
<p className="mt-1 mb-0 text-faint text-[10.5px] leading-[1.45]">{stepItem.reason}</p>
{!!stepDetail(stepItem, row) && (
<small className="block mt-[5px] text-ink-3 text-tiny leading-[1.5]">
{stepDetail(stepItem, row)}
</small>
)}
</div>
</div>
))}
</div>
) : row.status === 'succeeded' ? (
<div className={CALLOUT_EMPTY}>项目当前已完成,没有需要重复执行的步骤。</div>
) : (
<div className={CALLOUT_EMPTY}>
LLM 没有生成可执行步骤;请根据上方阻塞项补齐素材后重新下达指令。
</div>
)}
<div className="flex items-center justify-between gap-3 mt-3 pt-[13px] border-t border-line min-w-0 max-[620px]:flex-col max-[620px]:items-start">
<Row className="[--ctl-h:var(--ctl-h-main)]">
{row.can_execute && row.status !== 'running' && (
<Button variant="primary" disabled={!!busy} onClick={() => void executeAgent(row)}>
{executeLabel(row)}
</Button>
)}
{row.status === 'waiting_review' && (
<Link className={cn(buttonCls({ variant: 'secondary' }), 'no-underline')}
to={`/projects/${projectId}/review`}>逐镜人工审核 →</Link>
)}
{row.status === 'blocked' && (
<Link className={cn(buttonCls({ variant: 'secondary' }), 'no-underline')}
to={`/projects/${projectId}/storyboard`}>去分镜工作台 →</Link>
)}
{row.status === 'failed' && (
<Link className={cn(buttonCls({ variant: 'secondary' }), 'no-underline')}
to={failurePath(row)}>打开失败节点 →</Link>
)}
</Row>
{!!row.steps?.length && (
<span className={MUTED}>
{handledSteps(row)}/{row.steps.length} 步已处理
{!!skippedSteps(row) && <> · {skippedSteps(row)} 步无需重复执行</>}
</span>
)}
</div>
</>
)}
</div>
)}
</div>
)
})}
</>
)}
{!runs.length && (
<div className={cn(CALLOUT_EMPTY, 'relative flex min-h-[250px] flex-col items-center justify-center overflow-hidden p-[38px] border-solid max-[620px]:min-h-[190px] max-[620px]:p-[22px]', HERO_BG)}>
<Scanline />
<b className="text-ink-2 text-[15px]">还没有调度记录</b>
</div>
)}
{/* 面板自己滚动,末尾用一条 sticky 渐隐收尾,免得步骤卡被硬生生切断 */}
<div aria-hidden className={cn('sticky bottom-0 -mt-[22px] h-[22px] pointer-events-none', FADE_BG)} />
</div>
</div>
</section>
)
}

View File

@ -1,4 +1,538 @@
/** 待迁移:流程概览(占位,见 .local/vue-ref/src/views/tabs/Overview.vue) */
export default function Overview() {
return <div className="p-[26px] text-center text-faint text-body">流程概览 迁移中…</div>
/**
* 流程概览(项目工作台第一个页签)。
*
* 一屏回答四个问题:流程走到哪了(节点明细)、能不能开跑(素材预检)、
* 项目是怎么配的(设置)、下一步点哪里(建议 + 事件流)。
* 顶上那块「项目总控台」是本页唯一的写入口之一(拆在 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, ChipBar, 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, 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 eyebrow="PIPELINE DETAIL" 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
eyebrow="PREFLIGHT · 检查素材"
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
eyebrow="SETTINGS"
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>
<ChipBar>
<Chip as="span">生成模式 {modeLabels}</Chip>
<Chip as="span">可用档位 {videoCaps.resolutions.join(' / ') || '未声明'}</Chip>
<Chip as="span">帧率 {videoCaps.fps || '未声明'}fps</Chip>
<Chip as="span">单镜 {videoCaps.minDuration || '?'}–{videoCaps.maxDuration || '?'} 秒</Chip>
<Chip as="span">参考图上限 {videoCaps.maxReferenceImages || '未声明'}</Chip>
</ChipBar>
{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 eyebrow="NEXT ACTIONS" 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 eyebrow="ASSETS" 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 />
<ChipBar>
{Object.entries(stats?.shot_status || {}).map(([k, v]) => (
<Chip key={k} as="span">{statusLabel(k)} {String(v)}</Chip>
))}
{!Object.keys(stats?.shot_status || {}).length && <span className={MUTED}>尚无镜头状态数据</span>}
</ChipBar>
</Panel>
<Panel>
<PanelHead
eyebrow="EVENTS"
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>
)
}

View File

@ -322,11 +322,29 @@
/* 弹层出现:只做淡入。面板向上翻边时靠 transform:translateY(-100%) 定位,
位移类动画会和它打架(面板会跳一下)。 */
--animate-fade-in: nex-fade-in .12s ease-out;
/* 项目总控台(LLM 编排)的四个状态动画。
它们表达的是「服务端还在干活」,不是装饰:控制台一打开就要让人看出
这条指令是在跑还是在等,所以命名按用途取,不复用 pulse-soft。
prefers-reduced-motion 由 base.css 全局降级(时长压到 .01ms),这里不再各写一份。 */
--animate-agent-in: nex-agent-in .45s ease-out both;
--animate-agent-pulse: nex-agent-pulse 1.4s infinite;
--animate-agent-step: nex-agent-step 1.1s ease-in-out infinite alternate;
--animate-agent-scan: nex-agent-scan 4s linear infinite;
}
@keyframes nex-spin { to { transform: rotate(360deg) } }
@keyframes nex-fade-in { from { opacity: 0 } }
@keyframes nex-pulse { 50% { opacity: .45 } }
@keyframes nex-agent-in { from { opacity: 0; transform: translateY(8px) } }
@keyframes nex-agent-pulse {
70% { box-shadow: 0 0 0 7px color-mix(in srgb, var(--c-accent) 0%, transparent) }
100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--c-accent) 0%, transparent) }
}
@keyframes nex-agent-step {
to { box-shadow: 0 0 14px color-mix(in srgb, var(--c-warn-bright) 35%, transparent) }
}
@keyframes nex-agent-scan { from { top: 5% } to { top: 95% } }
/* 浅色变体:极少数「同一元素两个主题形状不同」的场合用 light:,
能用令牌解决的不要用它(令牌已经跟着 data-theme 翻了)。 */