From 569f4c2f1dcfcf627764b7512ede698ce7a591a2 Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Sun, 1 Nov 2026 18:19:43 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=81=E7=A7=BB=E9=A1=B9=E7=9B=AE=E6=80=BB?= =?UTF-8?q?=E6=8E=A7=E5=8F=B0=E4=B8=8E=E6=B5=81=E7=A8=8B=E6=A6=82=E8=A7=88?= =?UTF-8?q?=EF=BC=9ALLM=20=E6=8C=87=E4=BB=A4=E5=8F=B0=EF=BC=88=E6=8A=98?= =?UTF-8?q?=E5=8F=A0=E6=89=A7=E8=A1=8C=E8=BF=87=E7=A8=8B/=E8=A7=84?= =?UTF-8?q?=E5=88=92=E8=AE=A1=E6=97=B6/=E9=98=BB=E5=A1=9E=E8=A7=A3?= =?UTF-8?q?=E9=87=8A=EF=BC=89+=20=E8=8A=82=E7=82=B9=E6=98=8E=E7=BB=86/?= =?UTF-8?q?=E9=A2=84=E6=A3=80/=E9=A1=B9=E7=9B=AE=E8=AE=BE=E7=BD=AE/?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1/=E4=BA=8B=E4=BB=B6=E6=B5=81=EF=BC=9BGrid=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E4=B8=A4=E6=AE=B5=E5=BC=8F=E9=99=8D=E5=88=97?= =?UTF-8?q?=20steps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/components/ui/Panel.tsx | 14 +- frontend/src/pages/project/AgentConsole.tsx | 856 ++++++++++++++++++++ frontend/src/pages/project/Overview.tsx | 540 +++++++++++- frontend/src/styles/tokens.css | 18 + 4 files changed, 1422 insertions(+), 6 deletions(-) create mode 100644 frontend/src/pages/project/AgentConsole.tsx diff --git a/frontend/src/components/ui/Panel.tsx b/frontend/src/components/ui/Panel.tsx index 7354308..0afc725 100644 --- a/frontend/src/components/ui/Panel.tsx +++ b/frontend/src/components/ui/Panel.tsx @@ -73,9 +73,12 @@ export function Stat({ label, value, hint, className }: { label: ReactNode; valu const STEP_CLS: Record = { '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 (
*]: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}
diff --git a/frontend/src/pages/project/AgentConsole.tsx b/frontend/src/pages/project/AgentConsole.tsx new file mode 100644 index 0000000..82571d7 --- /dev/null +++ b/frontend/src/pages/project/AgentConsole.tsx @@ -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 = { + planning: 'LLM 规划中', planned: '待确认执行', running: '正在调度', + waiting_review: '等待人工审核', blocked: '存在阻塞', succeeded: '计划完成', + failed: '执行暂停', cancelled: '已取消' +} +const STATUS_TONES: Record = { + 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 ( + + + + + + ) +} + +/** 规划中/空态背景里那条来回扫的横线:表示「服务端还在算」,不是装饰 */ +function Scanline() { + return
+} + +/* 多段渐变背景各自保持成一个完整字面量: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 ( +
+ + + LLM 正在盘点项目 + {planSeconds}s + + {thinkingLabel} + + +

+ 计划是一次完整的模型调用:{thinking === 'high' ? '充分思考通常需要 30~120 秒' + : thinking === 'low' ? '有限思考通常 5~20 秒' : '关思考通常 3~8 秒'};期间页面不会推进,属正常现象。 +

+ + + 记录已落库,刷新页面也会继续显示进度 + +
    + {items.map((item, i) => ( +
  1. + {i + 1} + {item.text} +
  2. + ))} +
+
+ ) +} + +export default function AgentConsole() { + const projectId = useProjectStore((s) => s.id) + const project = useProjectStore((s) => s.project) + + const [runs, setRuns] = useState([]) + /** 后端带回的总条数可能大于本页条数(上限 100),列表标题要按真实总数说 */ + const [runsTotal, setRunsTotal] = useState(0) + /** 执行过程按指令折叠:这里只存「当前点开的是哪条指令」,null = 全部收拢 */ + const [openId, setOpenId] = useState(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(null) + // 刚下达/刚启动的这几十秒里多轮询几次:计划刚落库时状态会短暂停在 planned, + // 服务端紧接着才翻到 running,只认 planning/running 会让页面停在「待确认执行」。 + const pollUntil = useRef(0) + + /* 轮询回调和几个动作函数都在 await 之后要读「当下」的状态, + 直接闭包捕获会拿到发起请求那一刻的旧数组,统一用 ref 转接。 + gate 每帧重写:2.5 秒的 interval 只想读最新值,不该为了读到新值重建定时器。 */ + const runsRef = useRef(runs) + const openRunRef = useRef(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 ( +
+ {/* 控制台底纹(旧 .agent-console::before):mask 要带 -webkit 前缀, + 用内联样式一次写清,比在类名里叠四条 arbitrary 好读。 */} +
+ +
+
+
+ N +
+
+ PROJECT AUTOPILOT · LLM ORCHESTRATION +

+ 项目总控台 +

+
+
+
+ {latest + ? {latest.provider}/{latest.model} + : 读取默认 LLM} + + {busy || (isRunning ? '调度进行中' : '等待指令')} +
+
+ +
+ {/* ── 左:下达指令 ─────────────────────────────────────────── */} +
+ +