mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-17 19:01:59 +00:00
界面与交互全面翻修(前两波):运行态有了 HUD 和时间轴,终态会收尾,全站令牌、组件、文案统一
来自 2026-09 的 UI/UX 审查(142 条)。本提交是前两波,第三波(记录页接入时间轴、跨页互链、check-ui 更新、全站扫尾)另行提交。 地基 - 设计令牌:全局规则和 .btn/.field/.chip 放进 CSS 层,Tailwind 工具类重新生效,选中态、开启态不再被吞掉;字号阶梯; 辅助文字在所有底色上 >= 4.5:1;状态色专用,节点类型色与之拉开色相;「跟随系统」真的跟随,首帧不闪深色;新字标与 favicon - 基础组件:confirmDialog / promptDialog 取代原生对话框;toast 出错不自动消失、可复制、读屏可播报;离线横幅与断线恢复; 九种剪影的状态徽标;唯一一份状态文案(lib/status)、格式化(lib/format)、术语(lib/terms)、报错人话(lib/errors) - 运行态内核:事件折成航迹(run/trace.ts),可投影到任意时刻;取消 / 失败 / 服务重启后统一收尾,不再永远转圈; run.status 随事件回写;token 事件不再堆进 events - 后端:协作成员逐个完成即发事件,调度者决策有事件;时长分执行 / 墙钟 / 等人;API 时间带时区; 中断的运行也发 stream.end;运行列表可筛选翻页;删除运行 / 工作流有保护;运行默认值接通;可测未保存的配置; 报错说清发生了什么、为什么、怎么办 功能 - 画布:状态四重编码、固定高度遥测槽、按缩放三档、运行胶囊与 HUD、航迹时间轴与回放、执行轨迹边、 等待闸门、跟随执行、正式运行只读、一次性时刻(开场点亮、回扫、阻断级联、出具印章) - 编辑:撤销重做、版本历史、问题面板可定位、三栏可收起、模板与表达式字段区分、变量血缘、快捷键、带搜索的选择器 - 回答流 / 问数据:贴底才跟随滚动、工件下钻、出具横幅列出缺口、答案可复制导出、按会话的忙闲、 答案不再在 2000 字处截断、重启后这一轮会收尾 - 记录页:待审批 / 运行中 / 失败页签、筛选翻页、实时接流、排错路径指到节点、封存凭证常驻 - 管理页:新的「数据」页、写操作失败都有反馈、弹窗里先测连接、统一持久的连接状态 - 外壳:导航改版、⌘K 命令面板、? 快捷键帮助、404、页面标题与 favicon 状态点、后台提醒 验证(沙箱):tsc 干净,pytest 579 passed,14 个检查脚本中 13 个全绿;check-ui 剩 1 项旧断言(按旧日期格式找运行行),第三波更新。
This commit is contained in:
@@ -1,15 +1,24 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ChevronLeft, ChevronRight, Code2, Eraser, Hand, Play, Square } from 'lucide-react'
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
ChevronLeft, ChevronRight, Code2, Crosshair, Hand, History, MessageSquarePlus, Play, Square,
|
||||
Undo2, Wand2,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { Spinner } from '../components/ui'
|
||||
import { useStudio, type CopilotTurn } from '../store/studio'
|
||||
import { IconButton, StatusBadge, toast } from '../components/ui'
|
||||
import { formatClock, formatCost, formatDuration, formatTokens, shortId, NONE } from '../lib/format'
|
||||
import { statusLabel } from '../lib/status'
|
||||
import { runClassLabel } from '../lib/terms'
|
||||
import { AssistantStream, type StreamTurn } from './AssistantStream'
|
||||
import { Composer } from './Composer'
|
||||
import {
|
||||
decodeCopilot, decodeRun, formatDuration, isAwaitingHuman, type Step,
|
||||
copilotOutcome, decodeCopilot, decodeRun, SELF_CHECK_ROUNDS, type CopilotIssue, type Step,
|
||||
} from './decode'
|
||||
import { ApprovalCard } from './RunPanel'
|
||||
import { isSettled, liveAt, project, type RunPhase } from './trace'
|
||||
import { useRunClock } from './useRunClock'
|
||||
|
||||
/**
|
||||
* 画布右栏。
|
||||
@@ -52,35 +61,190 @@ export function AssistantPanel() {
|
||||
// 对话:和 Copilot 说话的地方
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function ChatView({ hasRun, onOpenRun }: { hasRun: boolean; onOpenRun: () => void }) {
|
||||
const copilotTurns = useStudio((s) => s.copilotTurns)
|
||||
const copilot = useStudio((s) => s.copilot)
|
||||
const clearCopilot = useStudio((s) => s.clearCopilot)
|
||||
/** 一轮开始的时刻:store 记了就用它,老轮次没有 */
|
||||
type TurnExtras = CopilotTurn & { startedAt?: number }
|
||||
|
||||
const turns = useMemo<StreamTurn[]>(() => copilotTurns.map((t) => ({
|
||||
const PHASE_TEXT: Record<string, string> = {
|
||||
connecting: '正在连接模型',
|
||||
planning: '正在理解需求、规划步骤',
|
||||
building: '正在搭建流程',
|
||||
wiring: '正在连接数据流',
|
||||
finalizing: '正在排版和校验',
|
||||
repairing: '正在按自查结果修正',
|
||||
}
|
||||
|
||||
/**
|
||||
* 一轮 Copilot 的卡片标题。只看 phase 的话,只回了一句话、自查没修好、少放了
|
||||
* 一步,全都写「流程已更新到画布」——而这几种的下一步完全不同
|
||||
*/
|
||||
function copilotTurn(t: TurnExtras, live: { lastOp: string; phase: string; repairing?: number }): StreamTurn {
|
||||
const running = t.phase === 'running'
|
||||
const out = copilotOutcome(t.ops, running)
|
||||
const found = t.ops.find((o) => o.op === 'check' && o.status === 'repairing')
|
||||
const foundN = Array.isArray(found?.issues) ? found!.issues.length : 0
|
||||
const reply = out.reply ?? t.reply
|
||||
const errorOp = out.error
|
||||
const steps = decodeCopilot(t.ops, { context: 'canvas' })
|
||||
// 回执说清改了什么:「流程已更新」不说改了哪几处,改坏了都不知道从哪看起
|
||||
const d = t.diff
|
||||
const changed = d ? [
|
||||
d.added.length ? `新增 ${d.added.length}` : '',
|
||||
d.changed.length ? `修改 ${d.changed.length}` : '',
|
||||
d.removed.length ? `删除 ${d.removed.length}` : '',
|
||||
].filter(Boolean).join(' · ') : ''
|
||||
const updated = changed ? `已更新画布(${changed})` : '已更新画布'
|
||||
|
||||
let status = ''
|
||||
let tone: StreamTurn['tone']
|
||||
let statusCode: string | undefined
|
||||
if (running) {
|
||||
status = live.lastOp
|
||||
|| (live.phase === 'repairing' && out.repairing
|
||||
? `${PHASE_TEXT.repairing}(第 ${out.repairing}/${SELF_CHECK_ROUNDS} 轮)`
|
||||
: PHASE_TEXT[live.phase] ?? '正在生成…')
|
||||
} else if (t.outcome === 'reverted') {
|
||||
status = '已撤回,画布回到了这一轮之前'
|
||||
statusCode = 'cancelled'
|
||||
} else if (t.phase === 'error' || errorOp) {
|
||||
status = '这一轮没能完成'
|
||||
} else if (reply && out.kind !== 'built') {
|
||||
status = '已回答(没有改动画布)'
|
||||
} else if (out.kind === 'built') {
|
||||
if (out.check?.status === 'failed') {
|
||||
status = `已放到画布,但还有 ${out.check.issues.length} 处问题要你处理`
|
||||
tone = 'warn'
|
||||
} else if (out.skipped.length) {
|
||||
status = `已放到画布,但有 ${out.skipped.length} 步没放上`
|
||||
tone = 'warn'
|
||||
} else if (out.check?.status === 'passed' && out.check.repaired) {
|
||||
status = `${updated} · 自查发现 ${foundN || '几'} 处问题,已自动修好`
|
||||
} else if (out.check?.status === 'passed') {
|
||||
status = `${updated} · 自查通过`
|
||||
} else {
|
||||
status = updated
|
||||
}
|
||||
} else {
|
||||
// 流正常收尾,却既没有交回图也没有回话(停止了,或者模型什么都没给)
|
||||
status = '没有改动画布'
|
||||
statusCode = 'cancelled'
|
||||
}
|
||||
|
||||
return {
|
||||
id: t.id,
|
||||
question: t.instruction,
|
||||
phase: t.phase === 'running' ? 'running' : t.phase === 'error' ? 'error' : 'done',
|
||||
// 生成期间不能只给一个孤零零的转圈图标,具体阶段从实时状态里取
|
||||
status: t.phase === 'running' ? (copilot.lastOp || '正在生成流程…')
|
||||
: t.phase === 'done' ? '流程已更新到画布' : '',
|
||||
steps: decodeCopilot(t.ops),
|
||||
output: t.explanation ? { 说明: t.explanation } : null,
|
||||
error: t.error,
|
||||
})), [copilotTurns, copilot.lastOp])
|
||||
phase: running ? 'running' : t.phase === 'error' || errorOp ? 'error' : 'done',
|
||||
status,
|
||||
tone,
|
||||
statusCode,
|
||||
steps,
|
||||
output: reply ? { 回答: reply } : t.explanation ? { 说明: t.explanation } : null,
|
||||
error: errorOp
|
||||
? { error: errorOp.message, hint: errorOp.hint, detail: errorOp.raw }
|
||||
: t.error || undefined,
|
||||
startedAt: t.startedAt,
|
||||
}
|
||||
}
|
||||
|
||||
const empty = !turns.length
|
||||
function ChatView({ hasRun, onOpenRun }: { hasRun: boolean; onOpenRun: () => void }) {
|
||||
const copilotTurns = useStudio((s) => s.copilotTurns) as TurnExtras[]
|
||||
const copilot = useStudio((s) => s.copilot)
|
||||
const retryCopilot = useStudio((s) => s.retryCopilot)
|
||||
const repairWithCopilot = useStudio((s) => s.repairWithCopilot)
|
||||
const undoCopilotTurn = useStudio((s) => s.undoCopilotTurn)
|
||||
const newCopilotConversation = useStudio((s) => s.newCopilotConversation)
|
||||
const memory = useStudio((s) => s.copilotMemory)
|
||||
const focusNode = useStudio((s) => s.focusNode)
|
||||
const select = useStudio((s) => s.select)
|
||||
const [showPast, setShowPast] = useState(false)
|
||||
|
||||
const turns = useMemo<StreamTurn[]>(() => copilotTurns.map((t) => copilotTurn(t, copilot)),
|
||||
[copilotTurns, copilot])
|
||||
// 打开这张图之前就有的那几轮:模型下一条指令照样会带上它们。面板上一片空白、
|
||||
// 模型却记着之前的事,它引用「刚才那个团队」时用户无从理解
|
||||
const settledHere = copilotTurns.filter((t) => t.phase !== 'running').length
|
||||
const earlier = memory.past.slice(0, Math.max(0, memory.past.length - settledHere))
|
||||
const pastTurns = useMemo<StreamTurn[]>(() => earlier.map((t) => ({
|
||||
id: `past-${t.id}`,
|
||||
question: t.question,
|
||||
phase: t.status === 'error' ? 'error' : 'done',
|
||||
status: t.status === 'error' ? '这一轮没能完成' : t.graph ? '改过画布' : '已回答',
|
||||
steps: [],
|
||||
output: t.answer ? { 回答: t.answer } : t.explanation ? { 说明: t.explanation } : null,
|
||||
error: t.status === 'error' ? t.error || undefined : undefined,
|
||||
})), [earlier])
|
||||
const shown = showPast ? [...pastTurns, ...turns] : turns
|
||||
const streamRef = useRef<HTMLDivElement>(null)
|
||||
// 展开之前的轮次:它们补在最上面,视野不动的话人什么也看不到,像是没点上。回到
|
||||
// 顶上从补出来的第一轮往下读(不按那一轮的位置滚:它刚挂上、还在淡入位移,量出来差几像素)
|
||||
useLayoutEffect(() => {
|
||||
if (!showPast) return
|
||||
const el = streamRef.current?.querySelector<HTMLElement>('[data-stream-scroll]')
|
||||
if (el) el.scrollTop = 0
|
||||
}, [showPast])
|
||||
|
||||
const empty = !copilotTurns.length && !earlier.length
|
||||
|
||||
const locate = (id: string) => { select(id); focusNode(id) }
|
||||
|
||||
/** 一轮之后的动作:定位问题节点、让 Copilot 再修、撤销这次生成、重试 */
|
||||
const actions = (turn: StreamTurn, i: number) => {
|
||||
if (i !== shown.length - 1 || turn.phase === 'running') return null
|
||||
const source = copilotTurns.find((t) => t.id === turn.id)
|
||||
if (!source) return null
|
||||
const out = copilotOutcome(source.ops)
|
||||
if (turn.phase === 'error') {
|
||||
return (
|
||||
<button type="button" className="btn btn-xs" onClick={() => retryCopilot()}>
|
||||
<Wand2 size={11} aria-hidden /> 用同一句话重试
|
||||
</button>
|
||||
)
|
||||
}
|
||||
const issues = out.check?.status === 'failed' ? out.check.issues : []
|
||||
const undo = source.outcome === 'applied' || (out.kind === 'built' && source.outcome !== 'reverted')
|
||||
if (!issues.length && !out.skipped.length) {
|
||||
return undo ? (
|
||||
<button type="button" className="btn btn-xs btn-ghost" onClick={() => undoCopilotTurn(source.id)}>
|
||||
<Undo2 size={11} aria-hidden /> 撤销这次生成
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
return (
|
||||
<div className="w-full space-y-1.5">
|
||||
{/* 没修好的问题直接摊开,不折叠:这是此刻唯一要做的事 */}
|
||||
{issues.length > 0 && <IssueList issues={issues} onLocate={locate} />}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<button type="button" className="btn btn-xs btn-primary"
|
||||
onClick={() => repairWithCopilot(source.id)}>
|
||||
<Wand2 size={11} aria-hidden /> {issues.length ? '让 Copilot 再修' : '让 Copilot 补上'}
|
||||
</button>
|
||||
{undo && (
|
||||
<button type="button" className="btn btn-xs btn-ghost" onClick={() => undoCopilotTurn(source.id)}>
|
||||
<Undo2 size={11} aria-hidden /> 撤销这次生成
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!empty && (
|
||||
<div className="flex shrink-0 items-center gap-2 border-b px-2.5 py-1.5">
|
||||
<span className="text-[11px] font-semibold">Copilot</span>
|
||||
<span className="text-2xs font-semibold">助手</span>
|
||||
{memory.turns > 0 && (
|
||||
<span className="chip tnum text-2xs"
|
||||
title={`下一条指令会带上最近 ${memory.turns} 轮对话和上一轮的工作流,模型据此理解"刚才那个"指的是什么`}>
|
||||
参考前 {memory.turns} 轮
|
||||
</span>
|
||||
)}
|
||||
<span className="flex-1" />
|
||||
<button className="rounded p-1 text-faint transition-colors hover:bg-hover"
|
||||
title="清空对话(不影响画布)" onClick={clearCopilot}>
|
||||
<Eraser size={12} />
|
||||
</button>
|
||||
<IconButton
|
||||
label="开始新对话(不影响画布;模型不再参考之前的对话,旧对话保留)"
|
||||
onClick={() => void newCopilotConversation()}
|
||||
>
|
||||
<MessageSquarePlus size={12} aria-hidden />
|
||||
</IconButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -91,8 +255,22 @@ function ChatView({ hasRun, onOpenRun }: { hasRun: boolean; onOpenRun: () => voi
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="min-h-0 flex-1">
|
||||
<AssistantStream turns={turns} dense />
|
||||
{earlier.length > 0 && (
|
||||
<button type="button"
|
||||
className="flex shrink-0 items-center gap-1.5 border-b px-2.5 py-1 text-left text-2xs text-dim transition-colors hover:bg-hover hover:text-fg"
|
||||
aria-expanded={showPast}
|
||||
onClick={() => setShowPast((v) => !v)}>
|
||||
<History size={11} aria-hidden />
|
||||
{showPast ? '收起之前的对话' : `之前的 ${earlier.length} 轮(模型仍会参考)`}
|
||||
<ChevronRight size={10} aria-hidden className="ml-auto transition-transform"
|
||||
style={{ transform: showPast ? 'rotate(90deg)' : 'none' }} />
|
||||
</button>
|
||||
)}
|
||||
<div ref={streamRef} className="min-h-0 flex-1">
|
||||
{/* 定位只认这张图上的对话:在前面补出之前的轮次不算换了一批,不再被拽到底 */}
|
||||
<AssistantStream turns={shown} dense landing="end" renderTurnActions={actions}
|
||||
resetKey={turns[0]?.id ?? ''}
|
||||
empty={<div className="flex-1" />} />
|
||||
</div>
|
||||
<Composer hero={false} />
|
||||
</>
|
||||
@@ -103,40 +281,66 @@ function ChatView({ hasRun, onOpenRun }: { hasRun: boolean; onOpenRun: () => voi
|
||||
)
|
||||
}
|
||||
|
||||
/** 自查没修好的问题,逐条带「定位」。问题落在哪个节点上认得出来才给 */
|
||||
function IssueList({ issues, onLocate }: { issues: CopilotIssue[]; onLocate: (id: string) => void }) {
|
||||
return (
|
||||
<ul className="space-y-0.5 rounded border px-2 py-1.5 text-2xs leading-relaxed"
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--st-waiting) 45%, var(--border))',
|
||||
background: 'var(--st-waiting-soft)' }}>
|
||||
{issues.map((x, i) => (
|
||||
<li key={i} className="flex items-start gap-1.5">
|
||||
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]">
|
||||
{x.nodeId && <span className="mono text-dim">「{x.nodeId}」</span>}{x.message}
|
||||
</span>
|
||||
{x.nodeId && (
|
||||
<button type="button"
|
||||
className="inline-flex shrink-0 items-center gap-0.5 rounded px-1 text-dim transition-colors hover:bg-hover hover:text-fg"
|
||||
onClick={() => onLocate(x.nodeId!)}>
|
||||
<Crosshair size={10} aria-hidden /> 定位
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 对话下面那条运行进度。
|
||||
*
|
||||
* 运行搬去自己那一层之后,这条是它在对话视图里留下的唯一痕迹——没有它,
|
||||
* 点了运行再切回对话,这次运行在眼前就彻底没了。
|
||||
* 点了运行再切回对话,这次运行在眼前就彻底没了。状态只读 runPhase:以前这里
|
||||
* 看步骤、审批列表、streaming 三样各自猜,等审批时会同时写"正在执行"。
|
||||
*/
|
||||
function RunStrip({ onClick }: { onClick: () => void }) {
|
||||
const run = useStudio((s) => s.run)
|
||||
const events = useStudio((s) => s.events)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const phase = useStudio((s) => s.runPhase)
|
||||
const steps = useMemo(() => (phase === 'running' ? decodeRun(events) : []), [events, phase])
|
||||
if (!run) return null
|
||||
|
||||
const steps = decodeRun(events)
|
||||
const waiting = isAwaitingHuman(steps)
|
||||
const last = lastMeaningful(steps)
|
||||
const failed = events.some((e) => e.type === 'run.failed')
|
||||
const last = phase === 'running' ? lastMeaningful(steps) : undefined
|
||||
const waiting = phase === 'waiting'
|
||||
const alert = phase === 'failed' || phase === 'suspended'
|
||||
|
||||
return (
|
||||
<button
|
||||
className="flex w-full shrink-0 items-center gap-2 border-t px-2.5 py-1.5 text-left text-[10.5px] transition-colors hover:bg-hover"
|
||||
style={waiting ? { background: 'color-mix(in srgb, var(--warn) 10%, transparent)' } : undefined}
|
||||
type="button"
|
||||
className="flex w-full shrink-0 items-center gap-2 border-t px-2.5 py-1.5 text-left text-2xs transition-colors hover:bg-hover"
|
||||
style={waiting ? { background: 'var(--st-waiting-soft)' } : undefined}
|
||||
title="看这次运行的完整过程" onClick={onClick}
|
||||
>
|
||||
{waiting ? <Hand size={11} className="shrink-0" style={{ color: 'var(--warn)' }} />
|
||||
: streaming ? <Spinner size={10} />
|
||||
: <Play size={10} className="shrink-0 text-faint" fill="currentColor" />}
|
||||
<span className={clsx('min-w-0 flex-1 truncate',
|
||||
waiting && 'text-[var(--warn)]', failed && 'text-[var(--err)]')}>
|
||||
{waiting ? '等你确认'
|
||||
: failed ? '运行失败'
|
||||
: streaming ? (last?.title || '正在执行…')
|
||||
: '这次运行已结束'}
|
||||
{phase === 'idle'
|
||||
? <Play size={10} className="shrink-0 text-faint" fill="currentColor" aria-hidden />
|
||||
: <StatusBadge status={phase === 'succeeded' ? 'succeeded' : phase} size={11} decorative />}
|
||||
<span className={clsx('min-w-0 flex-1 truncate', !waiting && !alert && 'text-dim')}
|
||||
style={waiting ? { color: 'var(--st-waiting)' } : alert ? { color: 'var(--st-failed)' } : undefined}>
|
||||
{waiting ? `${statusLabel('waiting')} · 去处理`
|
||||
: phase === 'running' ? (last?.title || statusLabel('running'))
|
||||
: phase === 'idle' ? '运行'
|
||||
: `这次运行${statusLabel(phase)}`}
|
||||
</span>
|
||||
<ChevronRight size={11} className="shrink-0 text-faint" />
|
||||
<ChevronRight size={11} className="shrink-0 text-faint" aria-hidden />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -145,104 +349,230 @@ function RunStrip({ onClick }: { onClick: () => void }) {
|
||||
// 运行:过程和结果,没有输入框
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
const STREAM_PHASE: Record<RunPhase, StreamTurn['phase']> = {
|
||||
idle: 'running', queued: 'running', running: 'running', waiting: 'waiting',
|
||||
succeeded: 'done', failed: 'error', cancelled: 'done', suspended: 'done',
|
||||
}
|
||||
|
||||
function RunView({ onBack }: { onBack: () => void }) {
|
||||
const run = useStudio((s) => s.run)!
|
||||
const events = useStudio((s) => s.events)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const phase = useStudio((s) => s.runPhase)
|
||||
const trace = useStudio((s) => s.trace)
|
||||
const attachRun = useStudio((s) => s.attachRun)
|
||||
const stopRun = useStudio((s) => s.stopRun)
|
||||
const setHoveredNode = useStudio((s) => s.setHoveredNode)
|
||||
const focusNode = useStudio((s) => s.focusNode)
|
||||
const hoveredNodeId = useStudio((s) => s.hoveredNodeId)
|
||||
const approvals = useCatalog((s) => s.approvals)
|
||||
const pending = approvals.filter((a) => a.run_id === run.id && a.status === 'pending')
|
||||
const refreshApprovals = useCatalog((s) => s.refreshApprovals)
|
||||
// 运行已经收尾了就不再挂卡:审批列表 4 秒才轮询一次,别处批过的卡会在跑完的运行上多挂几秒
|
||||
const pending = isSettled(phase) ? []
|
||||
: approvals.filter((a) => a.run_id === run.id && a.status === 'pending')
|
||||
const [raw, setRaw] = useState(false)
|
||||
const [stopping, setStopping] = useState(false)
|
||||
const bodyRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const turns = useMemo<StreamTurn[]>(() => {
|
||||
const finished = [...events].reverse().find((e) => e.type === 'run.finished')
|
||||
const failedEvent = [...events].reverse().find((e) => e.type === 'run.failed')
|
||||
const steps = decodeRun(events)
|
||||
// 从事件推,不查审批列表——那是 4 秒轮询一次的,中断后会有几秒钟
|
||||
// 这里说"完成",而实际上它正等着你点通过
|
||||
const waiting = isAwaitingHuman(steps)
|
||||
// 结局以 runPhase 为准,连同对账查到的状态一起喂给解码器:服务被强杀、
|
||||
// 事件停在半路的运行,右栏的行也得收住,不能一直转
|
||||
const steps = decodeRun(events, { status: run.status })
|
||||
const output = run.output && Object.keys(run.output).length ? run.output : finished?.data?.output
|
||||
return [{
|
||||
id: run.id,
|
||||
// 运行没有"提问"——它的输入是工具栏那张表单。硬塞一个问题气泡
|
||||
// 只会让它看起来像一次对话,而它不是
|
||||
question: undefined,
|
||||
phase: failedEvent ? 'error'
|
||||
: waiting ? 'waiting'
|
||||
: streaming ? 'running'
|
||||
: finished ? 'done' : 'running',
|
||||
status: streaming ? '正在执行…' : waiting ? '等待你的确认' : finished ? '完成' : '',
|
||||
phase: STREAM_PHASE[phase],
|
||||
status: statusLabel(phase === 'idle' ? 'queued' : phase),
|
||||
statusCode: phase === 'idle' ? 'queued' : phase,
|
||||
tone: phase === 'suspended' ? 'warn' : undefined,
|
||||
steps,
|
||||
// run 对象是启动时的快照,成果在 run.finished 事件里
|
||||
output: finished?.data?.output ?? run.output ?? null,
|
||||
error: failedEvent ? String(failedEvent.data?.error ?? '运行失败') : run.error || undefined,
|
||||
runId: run.id,
|
||||
output: phase === 'succeeded' || phase === 'failed' ? output ?? null : null,
|
||||
// 原始异常(run.failed.data.detail)收进可展开的技术细节,人话在上面
|
||||
error: phase === 'failed'
|
||||
? { error: String(failedEvent?.data?.error ?? run.error ?? '运行失败'),
|
||||
...(failedEvent?.data?.detail ? { detail: String(failedEvent.data.detail) } : {}) }
|
||||
: undefined,
|
||||
// #runId 已经在栏头上了(可点,去运行记录),卡片里不再重复
|
||||
runClass: run.run_class,
|
||||
startedAt: trace.startedAt,
|
||||
elapsedMs: run.usage?.active_ms ?? run.usage?.duration_ms,
|
||||
}]
|
||||
}, [run, events, streaming])
|
||||
}, [run, events, phase, trace.startedAt])
|
||||
|
||||
// 停下来等人的那一刻就去取审批卡。列表 4 秒才轮询一次:头上已经写着「等待审批」,
|
||||
// 通过/驳回却要晚几秒才出来
|
||||
const hasCard = pending.length > 0
|
||||
const [looked, setLooked] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (phase !== 'waiting' || hasCard) return
|
||||
let alive = true
|
||||
void refreshApprovals().finally(() => { if (alive) setLooked(run.id) })
|
||||
return () => { alive = false }
|
||||
}, [phase, hasCard, run.id, refreshApprovals])
|
||||
|
||||
// 画布上选中节点时不在这里滚动定位:选中即滑入的属性面板整个盖住这一栏,滚了也
|
||||
// 看不见,反倒让藏在下面的时间线离开底部、断了跟随——关掉属性面板回来,人看到
|
||||
// 的不是原处而是一枚「跳到最新」。联动靠悬停(activeNodeId)和点行取景
|
||||
|
||||
const stop = async () => {
|
||||
setStopping(true)
|
||||
try {
|
||||
await stopRun()
|
||||
} catch (e) {
|
||||
// 409 多半是它其实早就不在跑了(服务重启过、刚好结束)。store 已经对过账,
|
||||
// 这里说清楚发生了什么,不能静默吞掉
|
||||
toast.error(e)
|
||||
} finally {
|
||||
setStopping(false)
|
||||
}
|
||||
}
|
||||
const toApproval = () => {
|
||||
const slot = bodyRef.current?.querySelector<HTMLElement>('[data-approval-slot]:not(:empty)')
|
||||
const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
slot?.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' })
|
||||
slot?.querySelector<HTMLElement>('textarea, input, button')?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
const live = phase === 'running' || phase === 'queued'
|
||||
|
||||
return (
|
||||
<div className="sheet-in flex h-full min-h-0 flex-col">
|
||||
<div className="flex shrink-0 items-center gap-1.5 border-b px-2 py-1.5">
|
||||
<button
|
||||
className="flex items-center gap-0.5 rounded-md px-1 py-1 text-faint transition-colors hover:bg-hover hover:text-fg"
|
||||
title="回到 Copilot 对话" onClick={onBack}
|
||||
type="button"
|
||||
className="flex items-center gap-0.5 rounded-md px-1 py-1 text-dim transition-colors hover:bg-hover hover:text-fg"
|
||||
title="回到和助手的对话" onClick={onBack}
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
<span className="text-[10px]">Copilot</span>
|
||||
<ChevronLeft size={14} aria-hidden />
|
||||
<span className="text-2xs">助手</span>
|
||||
</button>
|
||||
<span className="mx-0.5 h-3.5 w-px shrink-0" style={{ background: 'var(--border)' }} />
|
||||
<span className="text-[11px] font-semibold">运行</span>
|
||||
<span className="mono text-[9.5px] text-faint" title={run.id}>#{run.id.slice(0, 6)}</span>
|
||||
<span className="text-2xs font-semibold">运行</span>
|
||||
<Link to={`/runs/${run.id}`} title="在运行记录中查看"
|
||||
className="mono text-2xs text-dim underline-offset-2 hover:text-fg hover:underline">
|
||||
{shortId(run.id)}
|
||||
</Link>
|
||||
<span className="flex-1" />
|
||||
{streaming && (
|
||||
<button className="rounded p-1 transition-colors hover:bg-hover"
|
||||
style={{ color: 'var(--err)' }} title="停止这次运行"
|
||||
onClick={() => void stopRun()}>
|
||||
<Square size={11} fill="currentColor" />
|
||||
{phase === 'waiting' && pending.length > 0 && (
|
||||
// 等人时工具栏不给"停止"(后端对停在审批上的运行没有取消路径,点了必然
|
||||
// 409),给的是此刻真正该做的事
|
||||
<button type="button" className="btn btn-xs" style={{ color: 'var(--st-waiting)' }} onClick={toApproval}>
|
||||
<Hand size={11} aria-hidden /> 去审批
|
||||
</button>
|
||||
)}
|
||||
{live && (
|
||||
<IconButton label="停止这次运行" variant="danger" disabled={stopping} onClick={() => void stop()}>
|
||||
<Square size={11} fill="currentColor" aria-hidden />
|
||||
</IconButton>
|
||||
)}
|
||||
{/* 原始事件是排查用的开发者视图,不该占一个常驻 tab——但也不能删,
|
||||
翻译层出问题时它是唯一能对照的东西 */}
|
||||
<button
|
||||
className={clsx('rounded p-1 transition-colors hover:bg-hover',
|
||||
raw ? 'text-[var(--accent)]' : 'text-faint')}
|
||||
title={raw ? '回到可读视图' : `看原始事件(${events.length} 条)`}
|
||||
<IconButton
|
||||
label={raw ? '回到可读视图' : `看原始事件(${events.length} 条)`}
|
||||
className={raw ? 'text-[var(--accent)]' : undefined}
|
||||
aria-pressed={raw}
|
||||
onClick={() => setRaw((v) => !v)}
|
||||
>
|
||||
<Code2 size={12} />
|
||||
</button>
|
||||
<Code2 size={12} aria-hidden />
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1">
|
||||
<div ref={bodyRef} className="min-h-0 flex-1">
|
||||
{raw ? <RawEvents /> : (
|
||||
<AssistantStream
|
||||
turns={turns}
|
||||
dense
|
||||
clockSkewMs={trace.skewMs ?? 0}
|
||||
onStepHover={setHoveredNode}
|
||||
onStepFocus={focusNode}
|
||||
activeNodeId={hoveredNodeId}
|
||||
// 审批卡插在它所属的那一轮里,而不是浮在整栏顶上:
|
||||
// 要确认的那件事和确认按钮之间不该隔着整条执行过程
|
||||
approvalsFor={() => (pending.length ? (
|
||||
<div className="fade-up mt-2 overflow-hidden rounded-lg border"
|
||||
style={{ borderColor: 'var(--warn)' }}>
|
||||
{pending.map((a) => (
|
||||
<ApprovalCard key={a.id} approval={a}
|
||||
<ApprovalCard key={a.id} approval={a} showWorkflow={false}
|
||||
onResolved={(runId) => attachRun(runId)} />
|
||||
))}
|
||||
</div>
|
||||
) : phase === 'waiting' ? (
|
||||
<div className="mt-2 rounded-lg border border-dashed px-2.5 py-2 text-2xs text-dim"
|
||||
style={{ borderColor: 'var(--st-waiting)' }}>
|
||||
{looked === run.id ? (
|
||||
<>
|
||||
没找到这次运行的待审批卡,可能已经在别处处理过了 ·{' '}
|
||||
<Link to={`/runs/${run.id}`} className="underline underline-offset-2 hover:text-fg">看运行记录</Link>
|
||||
</>
|
||||
) : '正在取审批卡…'}
|
||||
</div>
|
||||
) : null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2 border-t px-2.5 py-1 text-[9.5px] text-faint">
|
||||
{run.run_class === 'formal'
|
||||
? <span className="chip" style={{ color: 'var(--ok)', borderColor: 'var(--ok)' }}>正式 v{run.version}</span>
|
||||
: <span className="chip">探索</span>}
|
||||
<span className="flex-1" />
|
||||
{!!run.usage?.total_tokens && <span>{run.usage.total_tokens} tok</span>}
|
||||
{run.usage?.cost_usd ? <span>${Number(run.usage.cost_usd).toFixed(4)}</span> : null}
|
||||
{run.usage?.duration_ms ? <span>{formatDuration(run.usage.duration_ms)}</span> : null}
|
||||
</div>
|
||||
<RunFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 底栏:运行级别、执行时长、等人时长、tokens、成本。
|
||||
*
|
||||
* 以前读的是 POST /runs 返回的 queued 快照,跑完也是空的。运行中读实时累加的
|
||||
* usageLive,前面标「≥」——agent 和协作成员的模型调用以前不发 llm.end,
|
||||
* 老后端上这个数会偏少,不能装作是总数;到终态换成后端累计的 run.usage。
|
||||
* 执行和等人分开写:审批停了三分钟的运行,混成一个数哪个都不对。
|
||||
*/
|
||||
function RunFooter() {
|
||||
const run = useStudio((s) => s.run)!
|
||||
const phase = useStudio((s) => s.runPhase)
|
||||
const trace = useStudio((s) => s.trace)
|
||||
const usageLive = useStudio((s) => s.usageLive)
|
||||
const settled = isSettled(phase)
|
||||
const ticking = !settled && phase !== 'idle' && trace.startedAt != null
|
||||
const now = useRunClock(ticking)
|
||||
const view = trace.startedAt != null ? project(trace, liveAt(trace, now)) : undefined
|
||||
|
||||
const u = run.usage ?? {}
|
||||
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
|
||||
const activeMs = settled ? num(u.active_ms) ?? num(u.duration_ms) ?? view?.activeMs : view?.activeMs
|
||||
const waitMs = settled ? num(u.wait_ms) ?? view?.waitMs : view?.waitMs
|
||||
const finalTokens = num(u.total_tokens)
|
||||
?? (num(u.input_tokens) != null || num(u.output_tokens) != null
|
||||
? (num(u.input_tokens) ?? 0) + (num(u.output_tokens) ?? 0) : undefined)
|
||||
const liveTokens = usageLive.tokensIn + usageLive.tokensOut
|
||||
const tokens = settled ? finalTokens ?? (liveTokens || undefined) : liveTokens
|
||||
const cost = settled ? num(u.cost_usd) ?? (usageLive.costUsd || undefined) : usageLive.costUsd
|
||||
const approx = !settled && phase !== 'idle'
|
||||
|
||||
return (
|
||||
// 360px 的栏里放得下一行就不折:等人时五样数都在,11px 会把成本挤到第二行
|
||||
<div className="tnum flex shrink-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 border-t px-2.5 py-1 text-[10.5px] text-dim"
|
||||
aria-label="这次运行的用量">
|
||||
<span className="chip" style={run.run_class === 'formal'
|
||||
? { color: 'var(--st-done)', borderColor: 'var(--st-done)' } : undefined}>
|
||||
{runClassLabel(run.run_class ?? 'exploratory', run.version)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
<span title="执行时长:各段执行之和,不含等人审批的时间">
|
||||
执行 <span className="mono text-fg">
|
||||
{activeMs == null ? NONE : ticking ? formatClock(activeMs) : formatDuration(activeMs)}
|
||||
</span>
|
||||
</span>
|
||||
{(waitMs ?? 0) > 0 && (
|
||||
<span title="等人审批的总时长" style={phase === 'waiting' ? { color: 'var(--st-waiting)' } : undefined}>
|
||||
等人 <span className="mono">{ticking ? formatClock(waitMs!) : formatDuration(waitMs!)}</span>
|
||||
</span>
|
||||
)}
|
||||
<span title={approx ? '运行中实时累加,可能偏少;跑完以后端累计为准' : '后端累计'}>
|
||||
<span className="mono">{approx && tokens ? '≥' : ''}{tokens ? formatTokens(tokens, { compact: true }) : `${NONE} tok`}</span>
|
||||
</span>
|
||||
<span className="mono">{approx && cost ? '≥' : ''}{cost != null && (cost > 0 || settled) ? formatCost(cost) : NONE}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -258,32 +588,37 @@ export function lastMeaningful(steps: Step[]): Step | undefined {
|
||||
return [...flat].reverse().find((s) => s.kind !== 'lifecycle') ?? flat[flat.length - 1]
|
||||
}
|
||||
|
||||
/** 原始事件。翻译层出问题时用来对照,平时收着。 */
|
||||
/** 原始事件。翻译层出问题时用来对照,平时收着。和步骤流一样只在贴底时跟随 */
|
||||
function RawEvents() {
|
||||
const events = useStudio((s) => s.events)
|
||||
const bottom = useRef<HTMLDivElement>(null)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const pinned = useRef(true)
|
||||
useEffect(() => {
|
||||
bottom.current?.scrollIntoView({ block: 'end' })
|
||||
const el = ref.current
|
||||
if (el && pinned.current) el.scrollTop = el.scrollHeight
|
||||
}, [events.length])
|
||||
|
||||
if (!events.length) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-[11px] text-faint">
|
||||
<div className="flex h-full items-center justify-center text-2xs text-dim">
|
||||
还没有事件
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="h-full overflow-y-auto p-2">
|
||||
<div ref={ref} className="h-full overflow-y-auto p-2"
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget
|
||||
pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 64
|
||||
}}>
|
||||
{events.map((e) => (
|
||||
<div key={e.seq} className="mono border-b px-1 py-1 text-[9.5px] leading-relaxed last:border-0">
|
||||
<span className="text-faint">#{e.seq}</span>{' '}
|
||||
<div key={e.seq} className="mono border-b px-1 py-1 text-[10px] leading-relaxed last:border-0">
|
||||
<span className="text-dim">#{e.seq}</span>{' '}
|
||||
<span className="text-[var(--accent)]">{e.type}</span>{' '}
|
||||
{e.node_id && <span className="text-dim">{e.node_id}</span>}
|
||||
<div className="break-all text-faint">{JSON.stringify(e.data).slice(0, 400)}</div>
|
||||
<div className="break-all text-dim">{JSON.stringify(e.data).slice(0, 400)}</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={bottom} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+1491
-287
File diff suppressed because it is too large
Load Diff
+151
-77
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
|
||||
import { ArrowUp, Database, Settings2, Sparkles, Square, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
@@ -31,7 +31,6 @@ export function Composer({ hero, onFocusChange }: {
|
||||
const tools = useCatalog((s) => s.tools)
|
||||
const [text, setText] = useState('')
|
||||
const [opts, setOpts] = useState(false)
|
||||
const [focused, setFocused] = useState(false)
|
||||
const [model, setModel] = useState('')
|
||||
const [effective, setEffective] = useState('')
|
||||
const [useBase, setUseBase] = useState(true)
|
||||
@@ -81,7 +80,7 @@ export function Composer({ hero, onFocusChange }: {
|
||||
{hero && <HeroHeader sources={sources} toolCount={tools?.length ?? 0} />}
|
||||
|
||||
{copilot.error && (
|
||||
<div className="fade-up mb-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-[10.5px]"
|
||||
<div role="alert" className="fade-up mb-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-[10.5px]"
|
||||
style={{ borderColor: 'var(--err)', color: 'var(--err)' }}>
|
||||
<span className="min-w-0 flex-1 leading-relaxed">{copilot.error}</span>
|
||||
{/* 失败多半跟需求本身无关(模型抽风、协议跑偏、网断了),
|
||||
@@ -92,82 +91,46 @@ export function Composer({ hero, onFocusChange }: {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 输入坞。整块是一个框,输入区和操作条在里面——比"输入框 + 旁边三个按钮"
|
||||
更像一个可以对它说话的地方 */}
|
||||
<div
|
||||
className={clsx(
|
||||
'rounded-xl border bg-bg transition-[box-shadow,border-color] duration-150',
|
||||
focused && 'dock-focus',
|
||||
)}
|
||||
>
|
||||
<textarea
|
||||
ref={ref}
|
||||
className="w-full resize-none bg-transparent px-3 pt-2.5 text-[12.5px] leading-relaxed outline-none placeholder:text-faint"
|
||||
rows={hero ? 3 : 2}
|
||||
value={text}
|
||||
placeholder={nodes.length
|
||||
? '告诉它这张图要改成什么样…'
|
||||
: '描述你想要的流程,它会直接画到左边'}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onFocus={() => { setFocused(true); onFocusChange?.(true) }}
|
||||
onBlur={() => { setFocused(false); onFocusChange?.(false) }}
|
||||
onKeyDown={(e) => {
|
||||
// 输入法组字期间的回车是"选词",不是"发送"。不判 isComposing 的话
|
||||
// 中文用户每打一个词就发出去一次
|
||||
if (e.key === 'Enter' && !e.shiftKey && !isComposing(e)) {
|
||||
e.preventDefault()
|
||||
send()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-1 px-2 pb-2">
|
||||
<button
|
||||
className={clsx('rounded-md p-1.5 transition-colors hover:bg-hover',
|
||||
opts ? 'text-[var(--accent)]' : 'text-faint')}
|
||||
title="模型和生成方式"
|
||||
onClick={() => setOpts((v) => !v)}
|
||||
>
|
||||
<Settings2 size={13} />
|
||||
</button>
|
||||
{!!nodes.length && (
|
||||
<PromptBox
|
||||
inputRef={ref}
|
||||
size="panel"
|
||||
rows={hero ? 3 : 2}
|
||||
value={text}
|
||||
onChange={setText}
|
||||
onSubmit={() => send()}
|
||||
busy={copilot.active}
|
||||
onStop={stopCopilot}
|
||||
stopLabel="停止生成"
|
||||
label="告诉助手要画什么流程"
|
||||
placeholder={nodes.length
|
||||
? '告诉它这张图要改成什么样…'
|
||||
: '描述你想要的流程,它会直接画到左边'}
|
||||
onFocusChange={onFocusChange}
|
||||
leading={
|
||||
<>
|
||||
<button
|
||||
className={clsx('rounded-md px-1.5 py-1 text-[10px] transition-colors hover:bg-hover',
|
||||
useBase ? 'text-dim' : 'text-faint')}
|
||||
title={useBase ? '在当前这张图上改' : '不看现有的图,重新生成一张'}
|
||||
onClick={() => setUseBase((v) => !v)}
|
||||
className={clsx('rounded-md p-1.5 transition-colors hover:bg-hover',
|
||||
opts ? 'text-[var(--accent)]' : 'text-faint')}
|
||||
title="模型和生成方式"
|
||||
aria-label="模型和生成方式"
|
||||
aria-expanded={opts}
|
||||
onClick={() => setOpts((v) => !v)}
|
||||
>
|
||||
{useBase ? '改现有的图' : '重新生成'}
|
||||
<Settings2 size={13} />
|
||||
</button>
|
||||
)}
|
||||
<span className="flex-1" />
|
||||
<span className="pr-1 text-[9.5px] text-faint">
|
||||
{text.trim() ? '⏎ 发送 · ⇧⏎ 换行' : ''}
|
||||
</span>
|
||||
{copilot.active ? (
|
||||
<button
|
||||
className="flex h-7 w-7 items-center justify-center rounded-lg transition-colors"
|
||||
style={{ background: 'var(--err)', color: '#fff' }}
|
||||
title="停止生成" onClick={stopCopilot}
|
||||
>
|
||||
<Square size={11} fill="currentColor" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="flex h-7 w-7 items-center justify-center rounded-lg transition-all duration-150 disabled:opacity-30"
|
||||
style={{
|
||||
background: text.trim() ? 'var(--accent)' : 'var(--bg-hover)',
|
||||
color: text.trim() ? '#fff' : 'var(--text-faint)',
|
||||
}}
|
||||
disabled={!text.trim()}
|
||||
title="发送(⏎)"
|
||||
onClick={() => send()}
|
||||
>
|
||||
<ArrowUp size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!!nodes.length && (
|
||||
<button
|
||||
className={clsx('rounded-md px-1.5 py-1 text-[10px] transition-colors hover:bg-hover',
|
||||
useBase ? 'text-dim' : 'text-faint')}
|
||||
title={useBase ? '在当前这张图上改' : '不看现有的图,重新生成一张'}
|
||||
onClick={() => setUseBase((v) => !v)}
|
||||
>
|
||||
{useBase ? '改现有的图' : '重新生成'}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{opts && (
|
||||
<div className="fade-up mt-2 space-y-2 rounded-lg border bg-panel p-2.5">
|
||||
@@ -222,6 +185,117 @@ export function Composer({ hero, onFocusChange }: {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入坞:画布助手栏和问数据页共用的那一块。
|
||||
*
|
||||
* 整块是一个框,输入区和操作条在里面——比"输入框 + 旁边三个按钮"更像一个可以
|
||||
* 对它说话的地方。两个页面各写一份的话,焦点光晕、快捷键提示、停止键的颜色
|
||||
* 迟早各走各的。
|
||||
*
|
||||
* size:panel 是 360px 助手栏里的紧凑版;dock 是问数据页底部;hero 是问数据页
|
||||
* 空会话时居中的主输入。
|
||||
*/
|
||||
export function PromptBox({
|
||||
value, onChange, onSubmit, onStop, busy = false, blocked, placeholder, label,
|
||||
rows = 2, size = 'dock', inputRef, leading, onFocusChange, stopLabel = '停止', autoFocus,
|
||||
}: {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onSubmit: () => void
|
||||
/** 给了它,busy 期间发送键换成停止键 */
|
||||
onStop?: () => void
|
||||
busy?: boolean
|
||||
/** 暂时不能发的原因(历史没取回来之类)。输入照样能打,草稿不丢 */
|
||||
blocked?: string | null
|
||||
placeholder: string
|
||||
/** 读屏念的名字:占位符一有内容就不见了,不能拿它当标签 */
|
||||
label: string
|
||||
rows?: number
|
||||
size?: 'panel' | 'dock' | 'hero'
|
||||
inputRef?: RefObject<HTMLTextAreaElement | null>
|
||||
/** 操作条左侧的附加按钮 */
|
||||
leading?: ReactNode
|
||||
onFocusChange?: (focused: boolean) => void
|
||||
stopLabel?: string
|
||||
autoFocus?: boolean
|
||||
}) {
|
||||
const [focused, setFocused] = useState(false)
|
||||
const ready = !!value.trim() && !blocked
|
||||
const big = size === 'hero'
|
||||
const btn = big ? 'h-8 w-8' : 'h-7 w-7'
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'rounded-xl border bg-bg transition-[box-shadow,border-color] duration-150',
|
||||
big && 'shadow-elev-2',
|
||||
focused && 'dock-focus',
|
||||
)}
|
||||
>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
aria-label={label}
|
||||
className={clsx(
|
||||
'w-full resize-none bg-transparent leading-relaxed outline-none placeholder:text-faint',
|
||||
size === 'panel' ? 'px-3 pt-2.5 text-[12.5px]' : big ? 'px-4 pt-3.5 text-base' : 'px-3 pt-2.5 text-sm',
|
||||
)}
|
||||
rows={rows}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
autoFocus={autoFocus}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onFocus={() => { setFocused(true); onFocusChange?.(true) }}
|
||||
onBlur={() => { setFocused(false); onFocusChange?.(false) }}
|
||||
onKeyDown={(e) => {
|
||||
// 输入法组字期间的回车是"选词",不是"发送"。不判 isComposing 的话
|
||||
// 中文用户每打一个词就发出去一次
|
||||
if (e.key === 'Enter' && !e.shiftKey && !isComposing(e)) {
|
||||
e.preventDefault()
|
||||
if (!busy && ready) onSubmit()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={clsx('flex items-center gap-1', big ? 'px-3 pb-3' : 'px-2 pb-2')}>
|
||||
{leading}
|
||||
<span className="flex-1" />
|
||||
<span className={clsx('min-w-0 truncate pr-1 text-faint', size === 'panel' ? 'text-[9.5px]' : 'text-2xs')}
|
||||
role={blocked ? 'status' : undefined}>
|
||||
{blocked || (value.trim() ? '⏎ 发送 · ⇧⏎ 换行' : '')}
|
||||
</span>
|
||||
{/* 两个键各带 key:同一位置的同类元素 React 会复用,停止键的红底会顺着
|
||||
transition 慢慢褪成发送键,中间那几帧像是一个粉色的发送键 */}
|
||||
{busy && onStop ? (
|
||||
<button
|
||||
key="stop"
|
||||
className={clsx('flex shrink-0 items-center justify-center rounded-lg transition-colors', btn)}
|
||||
style={{ background: 'var(--err-solid)', color: 'var(--on-err)' }}
|
||||
title={stopLabel}
|
||||
aria-label={stopLabel}
|
||||
onClick={onStop}
|
||||
>
|
||||
<Square size={11} fill="currentColor" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
key="send"
|
||||
className={clsx('flex shrink-0 items-center justify-center rounded-lg transition-[background-color,color,opacity] duration-150 disabled:opacity-30', btn)}
|
||||
style={{
|
||||
background: ready ? 'var(--accent-solid)' : 'var(--bg-hover)',
|
||||
color: ready ? 'var(--on-accent)' : 'var(--text-faint)',
|
||||
}}
|
||||
disabled={!ready || busy}
|
||||
title={blocked || '发送(⏎)'}
|
||||
aria-label="发送"
|
||||
onClick={onSubmit}
|
||||
>
|
||||
<ArrowUp size={big ? 16 : 14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* hero 态的抬头。
|
||||
*
|
||||
@@ -236,7 +310,7 @@ function HeroHeader({ sources, toolCount }: { sources: any[]; toolCount: number
|
||||
<Sparkles size={18} style={{ color: 'var(--accent)' }} />
|
||||
</div>
|
||||
<div className="text-[13.5px] font-semibold">想让它做什么?</div>
|
||||
<div className="mt-1 text-[11px] leading-relaxed text-faint">
|
||||
<div className="mt-1 text-2xs leading-relaxed text-faint">
|
||||
说一句话,它把流程画到左边的画布上
|
||||
</div>
|
||||
<div className="mt-2 flex items-center justify-center gap-3 text-[10px] text-faint">
|
||||
|
||||
+167
-26
@@ -1,5 +1,7 @@
|
||||
import { Fragment, type ReactNode } from 'react'
|
||||
import { createContext, Fragment, useContext, useState, type ReactNode } from 'react'
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { toast } from '../components/ui'
|
||||
|
||||
/**
|
||||
* 模型输出的 Markdown 渲染。
|
||||
@@ -21,15 +23,62 @@ import clsx from 'clsx'
|
||||
* 全程构造 React 元素,一处 dangerouslySetInnerHTML 都没有。模型输出是不
|
||||
* 可信内容,走 innerHTML 就等于给自己开了个 XSS 口子。
|
||||
*/
|
||||
export function Markdown({ text, dense }: { text: string; dense?: boolean }) {
|
||||
export function Markdown({ text, dense, marks }: {
|
||||
text: string
|
||||
dense?: boolean
|
||||
/** 要在正文里标出来的词:出具时无法回指的数字、能回指到口径卡的数字 */
|
||||
marks?: MarkSpec[]
|
||||
}) {
|
||||
if (!text?.trim()) return null
|
||||
return (
|
||||
<div className={clsx('space-y-2 leading-relaxed', dense ? 'text-[11.5px]' : 'text-[12.5px]')}>
|
||||
{parseBlocks(text).map((b, i) => <Block key={i} block={b} dense={dense} />)}
|
||||
</div>
|
||||
<MarksContext.Provider value={marks?.length ? marks : null}>
|
||||
<div className={clsx('space-y-2 leading-relaxed', dense ? 'text-[11.5px]' : 'text-sm')}>
|
||||
{parseBlocks(text).map((b, i) => <Block key={i} block={b} dense={dense} />)}
|
||||
</div>
|
||||
</MarksContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 正文里要标出来的一个词。
|
||||
*
|
||||
* 出具校验认得出「哪些数字回指不到口径卡」,但以前只在横幅里列一串孤零零的
|
||||
* token——读的人得自己回正文里找「6」是哪句话里的那个 6。直接在原句上画出来,
|
||||
* 悬停说明原因,证据才落到读的地方。
|
||||
*/
|
||||
export interface MarkSpec {
|
||||
token: string
|
||||
title: string
|
||||
tone: 'warn' | 'ok'
|
||||
}
|
||||
|
||||
const MarksContext = createContext<MarkSpec[] | null>(null)
|
||||
|
||||
/** 纯文本段里的标记词包一层。数字按词边界认:「6」不能命中「94.26」里的那个 6 */
|
||||
function markText(text: string, marks: MarkSpec[] | null, keyBase: number): ReactNode[] {
|
||||
if (!marks || !text) return [text]
|
||||
const alts = [...marks].sort((a, b) => b.token.length - a.token.length)
|
||||
.map((m) => m.token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
||||
const re = new RegExp(`(?<![\\d.])(?:${alts.join('|')})(?![\\d]|\\.\\d)`, 'g')
|
||||
const out: ReactNode[] = []
|
||||
let last = 0
|
||||
for (let m = re.exec(text); m; m = re.exec(text)) {
|
||||
if (m.index > last) out.push(text.slice(last, m.index))
|
||||
const spec = marks.find((x) => x.token === m![0])!
|
||||
out.push(
|
||||
<span key={`mk${keyBase}-${m.index}`} title={spec.title}
|
||||
className="cursor-help underline decoration-dotted underline-offset-[3px]"
|
||||
style={{ textDecorationColor: spec.tone === 'warn' ? 'var(--st-waiting)' : 'var(--st-done)' }}
|
||||
data-mark={spec.tone}>
|
||||
{m[0]}
|
||||
</span>,
|
||||
)
|
||||
last = m.index + m[0].length
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last))
|
||||
return out
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 块级
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -40,14 +89,14 @@ type Block =
|
||||
| { kind: 'code'; lang: string; code: string }
|
||||
| { kind: 'quote'; text: string }
|
||||
| { kind: 'hr' }
|
||||
| { kind: 'list'; ordered: boolean; items: { text: string; depth: number }[] }
|
||||
| { kind: 'list'; ordered: boolean; start?: number; items: { text: string; depth: number }[] }
|
||||
| { kind: 'table'; head: string[]; rows: string[][] }
|
||||
|
||||
const FENCE = /^\s*```(\w*)\s*$/
|
||||
const HEADING = /^(#{1,6})\s+(.*)$/
|
||||
const HR = /^\s*(-{3,}|\*{3,}|_{3,})\s*$/
|
||||
const BULLET = /^(\s*)[-*+]\s+(.*)$/
|
||||
const ORDERED = /^(\s*)\d+[.)]\s+(.*)$/
|
||||
const ORDERED = /^(\s*)(\d+)[.)]\s+(.*)$/
|
||||
const QUOTE = /^\s*>\s?(.*)$/
|
||||
const TABLE_ROW = /^\s*\|(.+)\|\s*$/
|
||||
const TABLE_SEP = /^\s*\|[\s:|-]+\|\s*$/
|
||||
@@ -112,9 +161,11 @@ function parseBlocks(text: string): Block[] {
|
||||
const isOrdered = !!ordered
|
||||
const items: { text: string; depth: number }[] = []
|
||||
while (i < lines.length) {
|
||||
const m = lines[i].match(BULLET) || lines[i].match(ORDERED)
|
||||
if (m) {
|
||||
items.push({ text: m[2], depth: Math.floor(m[1].replace(/\t/g, ' ').length / 2) })
|
||||
const b = lines[i].match(BULLET)
|
||||
const o = b ? null : lines[i].match(ORDERED)
|
||||
if (b || o) {
|
||||
const indent = (b ?? o)![1]
|
||||
items.push({ text: b ? b[2] : o![3], depth: Math.floor(indent.replace(/\t/g, ' ').length / 2) })
|
||||
i += 1
|
||||
} else if (lines[i].trim() && !isBlockStart(lines[i]) && items.length) {
|
||||
// 悬挂缩进的续行接到上一条上,不要另起一段
|
||||
@@ -122,7 +173,10 @@ function parseBlocks(text: string): Block[] {
|
||||
i += 1
|
||||
} else break
|
||||
}
|
||||
out.push({ kind: 'list', ordered: isOrdered, items })
|
||||
// 模型常把有序列表写成被空行隔开的几段,每段各自一块。不记起始序号的话
|
||||
// 三段都从 1 开始,「1. 1. 1.」读起来像三条并列的第一条
|
||||
out.push({ kind: 'list', ordered: isOrdered, items,
|
||||
...(ordered ? { start: Number(ordered[2]) } : {}) })
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -151,7 +205,9 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
case 'h': {
|
||||
// 侧栏只有 360px 宽,一级标题按 h1 的字号会大得不像话。
|
||||
// 按层级递减但整体压扁,保住层次感就够了
|
||||
const size = ['text-[14px]', 'text-[13px]', 'text-[12.5px]'][Math.min(block.level, 3) - 1]
|
||||
const size = dense
|
||||
? ['text-[13px]', 'text-[12px]', 'text-[11.5px]'][Math.min(block.level, 3) - 1]
|
||||
: ['text-base', 'text-sm', 'text-sm'][Math.min(block.level, 3) - 1]
|
||||
return (
|
||||
<div className={clsx('mt-3 font-semibold first:mt-0', size)}>
|
||||
<Inline text={block.text} />
|
||||
@@ -161,11 +217,7 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
case 'hr':
|
||||
return <hr className="my-2 border-t" />
|
||||
case 'code':
|
||||
return (
|
||||
<pre className="mono overflow-x-auto rounded-lg border bg-bg px-2.5 py-2 text-[10.5px] leading-relaxed">
|
||||
<code>{block.code}</code>
|
||||
</pre>
|
||||
)
|
||||
return <CodeBlock lang={block.lang} code={block.code} dense={dense} />
|
||||
case 'quote':
|
||||
return (
|
||||
<blockquote className="border-l-2 pl-2.5 text-dim" style={{ borderColor: 'var(--accent)' }}>
|
||||
@@ -175,8 +227,9 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
case 'list': {
|
||||
const Tag = block.ordered ? 'ol' : 'ul'
|
||||
return (
|
||||
<Tag className={clsx('space-y-1', block.ordered ? 'list-decimal' : 'list-disc',
|
||||
'ml-4 marker:text-faint')}>
|
||||
<Tag start={block.ordered && block.start && block.start !== 1 ? block.start : undefined}
|
||||
className={clsx('space-y-1', block.ordered ? 'list-decimal' : 'list-disc',
|
||||
'ml-4 marker:text-faint')}>
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i} style={{ marginLeft: it.depth * 14 }}>
|
||||
<Inline text={it.text} />
|
||||
@@ -185,14 +238,23 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
</Tag>
|
||||
)
|
||||
}
|
||||
case 'table':
|
||||
case 'table': {
|
||||
// 数值列右对齐、等宽数字:一列金额左对齐时小数点对不上,没法一眼比大小
|
||||
const numeric = block.head.map((h, j) => {
|
||||
if (CODE_COLUMN.test(h.replace(/[*`]/g, '').trim())) return false
|
||||
const cells = block.rows.map((r) => (r[j] ?? '').replace(/[*`]/g, '').trim()).filter(Boolean)
|
||||
return cells.length > 0 && cells.every((c) => NUMERIC_CELL.test(c) && !LEADING_ZERO.test(c))
|
||||
})
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className={clsx('w-full', dense ? 'text-[10.5px]' : 'text-[11px]')}>
|
||||
<div className="group/table relative overflow-x-auto rounded-lg border">
|
||||
<CopyChip label="复制为 CSV" text={() => toCsv(block.head, block.rows)}
|
||||
className="absolute right-1 top-1 opacity-0 group-hover/table:opacity-100 focus-visible:opacity-100" />
|
||||
<table className={clsx('w-full', dense ? 'text-[10.5px]' : 'text-xs')}>
|
||||
<thead>
|
||||
<tr className="border-b bg-elev">
|
||||
{block.head.map((h, i) => (
|
||||
<th key={i} className="px-2 py-1 text-left font-medium text-faint">
|
||||
<th key={i} className={clsx('px-2 py-1 font-medium text-dim',
|
||||
numeric[i] ? 'text-right' : 'text-left')}>
|
||||
<Inline text={h} />
|
||||
</th>
|
||||
))}
|
||||
@@ -204,7 +266,8 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
{/* 用表头的列数对齐:模型偶尔会少写一格,少的补空,
|
||||
多的截掉——否则整张表会错位 */}
|
||||
{block.head.map((_, j) => (
|
||||
<td key={j} className="px-2 py-1 align-top text-dim">
|
||||
<td key={j} className={clsx('px-2 py-1 align-top text-dim',
|
||||
numeric[j] && 'tnum text-right')}>
|
||||
<Inline text={row[j] ?? ''} />
|
||||
</td>
|
||||
))}
|
||||
@@ -214,6 +277,7 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
default:
|
||||
return <p className="whitespace-pre-wrap"><Inline text={block.text} /></p>
|
||||
}
|
||||
@@ -244,8 +308,11 @@ function Inline({ text, depth = 0 }: { text: string; depth?: number }): ReactNod
|
||||
// 里可以套行内代码),不每次重置就会从上一层留下的位置接着扫
|
||||
const re = new RegExp(INLINE.source, 'g')
|
||||
|
||||
const marks = useContext(MarksContext)
|
||||
const plain = (t: string) => out.push(...markText(t, marks, key++))
|
||||
|
||||
for (let m = re.exec(text); m; m = re.exec(text)) {
|
||||
if (m.index > last) out.push(text.slice(last, m.index))
|
||||
if (m.index > last) plain(text.slice(last, m.index))
|
||||
const [, , code, linkText, href, bold1, bold2, italic, strike] = m
|
||||
|
||||
// 强调的内容要再解析一层。模型很爱写 **`table_name`**(粗体里套代码),
|
||||
@@ -270,7 +337,7 @@ function Inline({ text, depth = 0 }: { text: string; depth?: number }): ReactNod
|
||||
}
|
||||
last = m.index + m[0].length
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last))
|
||||
if (last < text.length) plain(text.slice(last))
|
||||
return <>{out.map((n, i) => <Fragment key={i}>{n}</Fragment>)}</>
|
||||
}
|
||||
|
||||
@@ -292,3 +359,77 @@ function Link({ href, text }: { href: string; text: string }) {
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 代码块、复制
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** 「1,234」「-3.5」「94.23%」「$0.031」「12 ms」这类都算数值格 */
|
||||
const NUMERIC_CELL = /^[-+]?[$¥€]?\d[\d,]*(\.\d+)?\s*(%|‰|ms|s|k|万|亿)?$/
|
||||
|
||||
/** 0 打头的整数串('001'、'0086')是编号不是数:右对齐、拿来排序都没有意义 */
|
||||
export const LEADING_ZERO = /^[-+]?0\d/
|
||||
|
||||
/**
|
||||
* 列名看得出是编号、代码、分组、类型的:值再像数也不当"量"。factory_code 的 1063、
|
||||
* attribute_group 的 001 按数右对齐、给出「按 attribute_group 从高到低排」都说不通
|
||||
*/
|
||||
export const CODE_COLUMN =
|
||||
/(^id$|_id$|^id_|code|_no$|(^|_)(group|type|status|kind|class|category)$|编号|编码|代码|序号|分组|类型|状态)/i
|
||||
|
||||
function toCsv(head: string[], rows: string[][]): string {
|
||||
const cell = (v: string) => {
|
||||
const t = v.replace(/\*\*|__|`/g, '')
|
||||
return /[",\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t
|
||||
}
|
||||
return [head, ...rows.map((r) => head.map((_, j) => r[j] ?? ''))]
|
||||
.map((r) => r.map(cell).join(',')).join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* 代码块带语言标签和复制按钮。模型给的 SQL、脚本十有八九要被拿去别处跑,
|
||||
* 手动框选容易漏掉首尾一行
|
||||
*/
|
||||
function CodeBlock({ lang, code, dense }: { lang: string; code: string; dense?: boolean }) {
|
||||
return (
|
||||
<div className="group/code relative overflow-hidden rounded-lg border bg-bg">
|
||||
<div className="flex items-center gap-2 border-b px-2.5 py-1 text-2xs text-faint">
|
||||
<span className="mono">{lang || '代码'}</span>
|
||||
<span className="flex-1" />
|
||||
<CopyChip label="复制" text={() => code} />
|
||||
</div>
|
||||
<pre className={clsx('mono overflow-x-auto px-2.5 py-2 leading-relaxed', dense ? 'text-[10.5px]' : 'text-xs')}>
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 小号的复制键:点了变成对勾一秒半,失败走 toast */
|
||||
export function CopyChip({ label, text, className }: {
|
||||
label: string; text: () => string; className?: string
|
||||
}) {
|
||||
const [done, setDone] = useState(false)
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={clsx('inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-2xs text-dim transition-colors hover:bg-hover hover:text-fg',
|
||||
className)}
|
||||
style={{ background: 'var(--bg-panel)' }}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
const value = text()
|
||||
if (!navigator.clipboard) { toast.error('复制失败:浏览器没有给剪贴板权限'); return }
|
||||
void navigator.clipboard.writeText(value).then(() => {
|
||||
setDone(true)
|
||||
setTimeout(() => setDone(false), 1500)
|
||||
}, () => toast.error('复制失败:浏览器没有给剪贴板权限'))
|
||||
}}
|
||||
>
|
||||
{done ? <Check size={11} aria-hidden /> : <Copy size={11} aria-hidden />}
|
||||
{done ? '已复制' : label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
+280
-133
@@ -1,7 +1,15 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, Play, RotateCw, ShieldCheck, Square } from 'lucide-react'
|
||||
import { ChevronDown, Play, ShieldCheck } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { isComposing, Kbd, Skeleton, Spinner, toast } from '../components/ui'
|
||||
import { errorMessage } from '../lib/errors'
|
||||
import { matchShortcut } from '../lib/keys'
|
||||
import { runClassLabel } from '../lib/terms'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { isComposing, Spinner, useToast } from '../components/ui'
|
||||
import type { WorkflowVersion } from '../types'
|
||||
import { escapeRun, RunCapsule } from './RunHud'
|
||||
import { isActivePhase } from './trace'
|
||||
|
||||
/**
|
||||
* 工具栏上的运行控件。
|
||||
@@ -10,185 +18,324 @@ import { isComposing, Spinner, useToast } from '../components/ui'
|
||||
* "主要动作",互相压着——而它们其实是两种不同的意图(改这张图 / 跑这张图),
|
||||
* 不该争同一块地方。运行是对整个文档的动作,和保存、发布是一类,属于工具栏。
|
||||
*
|
||||
* 有输入字段就弹出表单填了再跑;没有字段就一键直接跑,不为了统一而多一次点击。
|
||||
* 有了运行之后,这里多一枚运行胶囊(run/RunHud.tsx):跑的时候它就是全部——
|
||||
* 计时、进度、用量、停止都在里面;结束了它收成结果,旁边再露出发起按钮。
|
||||
* 相位一律读 store 的 runPhase(由事件推出),不再读启动时那份 run 快照:
|
||||
* 那份快照的 status 永远是 queued,失败后「接着跑」出不来、续跑完「停止」卡死。
|
||||
*
|
||||
* 两个入口互不牵连:
|
||||
* - 「运行」用画布当前内容发起探索运行,画布有错误时不能点;
|
||||
* - 「正式运行 vN」跑已发布的不可变版本,只看 published_version,和画布上的
|
||||
* 错误、未保存改动都无关(改了只提示「不含画布改动」),表单字段取那一版的。
|
||||
*/
|
||||
export function RunControl() {
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const run = useStudio((s) => s.run)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const issues = useStudio((s) => s.issues)
|
||||
const workflow = useStudio((s) => s.workflow)
|
||||
const dirty = useStudio((s) => s.dirty)
|
||||
const { startRun, startFormalRun, stopRun, continueRun } = useStudio()
|
||||
const toast = useToast()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const wrap = useRef<HTMLDivElement>(null)
|
||||
|
||||
const inputFields = useMemo(() => {
|
||||
const entry = nodes.find((n) => n.data.nodeType === 'input')
|
||||
return (entry?.data.config?.fields ?? []) as any[]
|
||||
}, [nodes])
|
||||
type Field = { name: string; required?: boolean; description?: string; default?: unknown; example?: unknown }
|
||||
|
||||
const errors = issues.filter((i) => i.level === 'error')
|
||||
const canFormal = !!workflow
|
||||
&& (workflow.status === 'published' || workflow.status === 'governed')
|
||||
&& !!workflow.published_version
|
||||
const running = streaming || run?.status === 'running'
|
||||
/** 已发布版本的入口字段,按 (工作流, 版本) 缓存:发布之后那一版就不会再变 */
|
||||
const versionFields = new Map<string, Field[]>()
|
||||
|
||||
// 点外面关掉。浮层不能只靠再点一次按钮关——那是很容易漏掉的死路
|
||||
function fieldsOfGraph(graph: WorkflowVersion['graph']): Field[] {
|
||||
const entry = graph?.nodes?.find((n) => n.type === 'input')
|
||||
return ((entry?.data?.config?.fields ?? []) as Field[]).filter((f) => f?.name)
|
||||
}
|
||||
|
||||
const shown = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : JSON.stringify(v))
|
||||
|
||||
function payloadOf(fields: Field[], values: Record<string, string>): Record<string, any> {
|
||||
const payload: Record<string, any> = {}
|
||||
for (const field of fields) {
|
||||
// 留空就用默认值。占位符里写着「默认:…」,照它说的办
|
||||
const typed = values[field.name]
|
||||
const raw = typed != null && typed.trim() !== '' ? typed : field.default ?? ''
|
||||
// 看起来像 JSON 就按 JSON 传,让数组/对象类型的输入能用
|
||||
if (typeof raw === 'string' && /^\s*[[{]/.test(raw)) {
|
||||
try { payload[field.name] = JSON.parse(raw) } catch { payload[field.name] = raw }
|
||||
} else {
|
||||
payload[field.name] = raw
|
||||
}
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
function FieldsForm({ fields, values, onChange, onSubmit }: {
|
||||
fields: Field[]
|
||||
values: Record<string, string>
|
||||
onChange: (v: Record<string, string>) => void
|
||||
onSubmit: () => void
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{fields.map((field, i) => (
|
||||
<div key={field.name} className="mb-2.5">
|
||||
<label className="label" htmlFor={`run-field-${field.name}`}>
|
||||
{field.name}
|
||||
{field.required && <span className="ml-1 text-[var(--err)]" aria-label="必填">*</span>}
|
||||
{field.description && (
|
||||
<span className="ml-1.5 font-normal text-faint">{field.description}</span>
|
||||
)}
|
||||
</label>
|
||||
<textarea
|
||||
id={`run-field-${field.name}`}
|
||||
className="field"
|
||||
rows={2}
|
||||
autoFocus={i === 0}
|
||||
value={values[field.name] ?? ''}
|
||||
// 占位符不复用 description(标签旁已经写着):有默认值说默认值,有示例给示例,都没有就空着
|
||||
placeholder={field.default != null && shown(field.default) !== ''
|
||||
? `默认:${shown(field.default)}`
|
||||
: field.example != null ? `例如:${shown(field.example)}` : ''}
|
||||
onChange={(e) => onChange({ ...values, [field.name]: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (!isComposing(e) && matchShortcut(e.nativeEvent, 'Mod+Enter')) {
|
||||
e.preventDefault()
|
||||
onSubmit()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** 点外面、按 Esc 关掉浮层。浮层不能只靠再点一次按钮关——那是很容易漏掉的死路 */
|
||||
function useDismiss(open: boolean, close: () => void, wrap: React.RefObject<HTMLDivElement | null>) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onDown = (e: MouseEvent) => {
|
||||
if (!wrap.current?.contains(e.target as Node)) setOpen(false)
|
||||
if (!wrap.current?.contains(e.target as Node)) close()
|
||||
}
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape' || e.isComposing) return
|
||||
e.preventDefault()
|
||||
close()
|
||||
}
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
|
||||
window.addEventListener('mousedown', onDown)
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', onDown)
|
||||
window.removeEventListener('keydown', onKey)
|
||||
}
|
||||
}, [open])
|
||||
}, [open, close, wrap])
|
||||
}
|
||||
|
||||
const launch = async (formal = false) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const payload: Record<string, any> = {}
|
||||
for (const field of inputFields) {
|
||||
if (!field.name) continue
|
||||
const raw = values[field.name] ?? field.default ?? ''
|
||||
// 看起来像 JSON 就按 JSON 传,让数组/对象类型的输入能用
|
||||
if (typeof raw === 'string' && /^\s*[[{]/.test(raw)) {
|
||||
try { payload[field.name] = JSON.parse(raw) } catch { payload[field.name] = raw }
|
||||
} else {
|
||||
payload[field.name] = raw
|
||||
}
|
||||
}
|
||||
if (formal) await startFormalRun(payload)
|
||||
else await startRun(payload)
|
||||
setOpen(false)
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '启动失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (running) {
|
||||
return (
|
||||
<button className="btn btn-danger" onClick={stopRun}>
|
||||
<Square size={11} fill="currentColor" /> 停止
|
||||
</button>
|
||||
)
|
||||
}
|
||||
/** 探索运行:画布当前这张图。tight:旁边有运行胶囊,窄屏上只留图标 */
|
||||
function ExploreLauncher({ tight }: { tight: boolean }) {
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const issues = useStudio((s) => s.issues)
|
||||
const startRun = useStudio((s) => s.startRun)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const wrap = useRef<HTMLDivElement>(null)
|
||||
useDismiss(open, () => setOpen(false), wrap)
|
||||
|
||||
const fields = useMemo(() => {
|
||||
const entry = nodes.find((n) => n.data.nodeType === 'input')
|
||||
return ((entry?.data.config?.fields ?? []) as Field[]).filter((f) => f?.name)
|
||||
}, [nodes])
|
||||
const errors = issues.filter((i) => i.level === 'error')
|
||||
const blocked = !!errors.length || !nodes.length
|
||||
|
||||
const resume = async () => {
|
||||
const launch = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await continueRun()
|
||||
toast('从断点接着跑,前面跑过的节点不重来', 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '接着跑失败', 'error')
|
||||
await startRun(payloadOf(fields, values))
|
||||
setOpen(false)
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative flex items-center gap-1.5" ref={wrap}>
|
||||
{/* 图挂在半路时,"接着跑"才是用户接下来最想做的事:他刚在画布上把那个
|
||||
写错的模型 id / 循环条件改好,重跑一遍意味着前面查过的表、跑过的 SQL
|
||||
全部重来。断点一直在 checkpoint 里躺着,只是以前没有入口 */}
|
||||
{run?.status === 'failed' && !blocked && (
|
||||
<button className="btn gap-1.5" disabled={busy} onClick={resume}
|
||||
title="从失败的那个节点接着跑,前面跑过的节点不重来。只能改节点配置,改了结构要重新发起">
|
||||
{busy ? <Spinner size={11} /> : <RotateCw size={11} />}
|
||||
接着跑
|
||||
</button>
|
||||
)}
|
||||
<div className="relative" ref={wrap}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary gap-1.5"
|
||||
disabled={busy || blocked}
|
||||
aria-label="运行"
|
||||
aria-expanded={fields.length ? open : undefined}
|
||||
title={blocked
|
||||
? (errors.length ? `${errors.length} 个问题会阻止运行:${errors[0].message}` : '画布是空的')
|
||||
: '用画布当前内容跑一次,结果标探索性'}
|
||||
: `用画布当前内容发起一次${runClassLabel('exploratory')}`}
|
||||
onClick={() => {
|
||||
// 没有输入字段就没什么可填的,多弹一层只是多一次点击
|
||||
if (!inputFields.length && !canFormal) void launch(false)
|
||||
if (!fields.length) void launch()
|
||||
else setOpen((v) => !v)
|
||||
}}
|
||||
>
|
||||
{busy ? <Spinner size={11} /> : <Play size={11} fill="currentColor" />}
|
||||
运行
|
||||
{(inputFields.length > 0 || canFormal) && (
|
||||
<ChevronDown size={10} className="opacity-60 transition-transform"
|
||||
<span className={tight ? 'hidden xl:inline' : undefined}>运行</span>
|
||||
{fields.length > 0 && (
|
||||
<ChevronDown size={10} className={clsx('opacity-60 transition-transform', tight && 'hidden xl:block')}
|
||||
style={{ transform: open ? 'rotate(180deg)' : 'none' }} />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="sheet-in absolute right-0 top-full z-50 mt-1.5 w-[340px] rounded-xl border bg-panel p-3 shadow-xl">
|
||||
{inputFields.map((field) => (
|
||||
<div key={field.name} className="mb-2.5">
|
||||
<label className="label">
|
||||
{field.name}
|
||||
{field.required && <span className="ml-1 text-[var(--err)]">*</span>}
|
||||
{field.description && (
|
||||
<span className="ml-1.5 font-normal text-faint">{field.description}</span>
|
||||
)}
|
||||
</label>
|
||||
<textarea
|
||||
className="field"
|
||||
rows={2}
|
||||
autoFocus={field === inputFields[0]}
|
||||
value={values[field.name] ?? (typeof field.default === 'string'
|
||||
? field.default
|
||||
: field.default ? JSON.stringify(field.default) : '')}
|
||||
placeholder={field.required ? '必填' : '可留空'}
|
||||
onChange={(e) => setValues({ ...values, [field.name]: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && !isComposing(e)) void launch(false)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{!inputFields.length && (
|
||||
<div className="mb-2.5 text-[11px] text-faint">这张图没有输入节点,将直接运行</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button className="btn btn-primary flex-1 justify-center" disabled={busy}
|
||||
onClick={() => launch(false)}>
|
||||
<Play size={11} fill="currentColor" /> 试运行
|
||||
</button>
|
||||
{canFormal && (
|
||||
<button
|
||||
className="btn flex-1 justify-center"
|
||||
style={{ borderColor: 'var(--ok)', color: 'var(--ok)' }}
|
||||
disabled={busy || dirty}
|
||||
title={dirty
|
||||
? '有未保存改动,正式运行只跑已发布版本'
|
||||
: `从已发布的 v${workflow?.published_version} 不可变版本发起`}
|
||||
onClick={() => launch(true)}
|
||||
>
|
||||
<ShieldCheck size={11} /> 正式 v{workflow?.published_version}
|
||||
</button>
|
||||
)}
|
||||
<div className="sf-pop sheet-in" role="dialog" aria-label={runClassLabel('exploratory')} data-esc-layer>
|
||||
<div className="sf-pop-head">
|
||||
<Play size={11} fill="currentColor" className="text-[var(--accent)]" />
|
||||
<span>{runClassLabel('exploratory')}</span>
|
||||
<span className="sf-dim">· 用画布当前内容,结果不归档</span>
|
||||
</div>
|
||||
{canFormal && dirty && (
|
||||
<div className="mt-1.5 text-[10px] leading-relaxed text-faint">
|
||||
画布有未保存改动;正式运行永远执行已发布的不可变版本
|
||||
<FieldsForm fields={fields} values={values} onChange={setValues} onSubmit={() => void launch()} />
|
||||
<button type="button" className="btn btn-primary w-full justify-center" disabled={busy}
|
||||
onClick={() => void launch()}>
|
||||
{busy ? <Spinner size={11} /> : <Play size={11} fill="currentColor" />} {runClassLabel('exploratory')}
|
||||
</button>
|
||||
<div className="mt-1.5 flex items-center gap-1 text-2xs text-faint">
|
||||
<Kbd combo="Mod+Enter" /> 在输入框里直接{runClassLabel('exploratory')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 正式运行:已发布的不可变版本。
|
||||
*
|
||||
* 以前它要求工作流状态是已发布 / 受管——可保存一次就退回草稿,入口跟着消失,
|
||||
* 而后端只看 published_version。它也不受画布上的错误和未保存改动影响:跑的
|
||||
* 根本不是画布。表单字段必须取那一版的入口:画布改过字段名时照画布填,
|
||||
* 传过去的就是错的参数。
|
||||
*/
|
||||
function FormalLauncher({ workflowId, version }: { workflowId: string; version: number }) {
|
||||
const dirty = useStudio((s) => s.dirty)
|
||||
const canvasVersion = useStudio((s) => s.workflow?.version)
|
||||
const startFormalRun = useStudio((s) => s.startFormalRun)
|
||||
const key = `${workflowId}@${version}`
|
||||
const [open, setOpen] = useState(false)
|
||||
const [fields, setFields] = useState<Field[] | null>(versionFields.get(key) ?? null)
|
||||
const [loadError, setLoadError] = useState<unknown>(null)
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const wrap = useRef<HTMLDivElement>(null)
|
||||
useDismiss(open, () => setOpen(false), wrap)
|
||||
|
||||
useEffect(() => {
|
||||
setFields(versionFields.get(key) ?? null)
|
||||
setValues({})
|
||||
}, [key])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || versionFields.has(key)) return
|
||||
let alive = true
|
||||
setLoadError(null)
|
||||
api.workflows.version(workflowId, version)
|
||||
.then((v) => {
|
||||
const list = (v.input_fields?.length ? v.input_fields : fieldsOfGraph(v.graph)) as Field[]
|
||||
versionFields.set(key, list)
|
||||
if (alive) setFields(list)
|
||||
})
|
||||
.catch((e) => { if (alive) setLoadError(e) })
|
||||
return () => { alive = false }
|
||||
}, [open, key, workflowId, version])
|
||||
|
||||
// 画布和已发布版本不是同一份:有未保存的改动,或者保存过但没重新发布
|
||||
const ahead = dirty || (canvasVersion != null && canvasVersion !== version)
|
||||
const label = runClassLabel('formal', version)
|
||||
|
||||
const launch = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await startFormalRun(payloadOf(fields ?? [], values))
|
||||
setOpen(false)
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative" ref={wrap}>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx('btn gap-1.5', ahead && 'sf-ahead')}
|
||||
disabled={busy}
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
title={`从已发布的 v${version} 发起${runClassLabel('formal')},结果归档、可审计${ahead ? '。不含画布上的改动' : ''}`}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
{busy ? <Spinner size={11} /> : <ShieldCheck size={12} />}
|
||||
{/* 窄屏上工具栏放不下全名:留盾牌和版本号,全名在 aria-label 和 title 里 */}
|
||||
<span aria-hidden><span className="hidden xl:inline">{runClassLabel('formal')} </span>v{version}</span>
|
||||
<ChevronDown size={10} className="hidden opacity-60 transition-transform xl:block"
|
||||
style={{ transform: open ? 'rotate(180deg)' : 'none' }} />
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="sf-pop sheet-in" role="dialog" aria-label={label} data-esc-layer>
|
||||
<div className="sf-pop-head">
|
||||
<ShieldCheck size={12} />
|
||||
<span>{label}</span>
|
||||
<span className="sf-dim">· 已发布的不可变版本,结果归档</span>
|
||||
</div>
|
||||
{ahead && (
|
||||
<div className="sf-pop-note">
|
||||
不含画布改动:{dirty ? '画布上有未保存的改动' : `画布是 v${canvasVersion},还没发布`},这次执行的是 v{version}。
|
||||
</div>
|
||||
)}
|
||||
{!!inputFields.length && (
|
||||
<div className="mt-1.5 text-[10px] text-faint">⌘⏎ 直接运行</div>
|
||||
{fields == null && !loadError && <Skeleton rows={2} height={28} className="mb-2.5" />}
|
||||
{loadError != null && (
|
||||
<div className="sf-pop-note is-err">
|
||||
取不到 v{version} 的输入字段:{errorMessage(loadError)}。
|
||||
<button type="button" className="underline" onClick={() => { setLoadError(null); setOpen(false); setTimeout(() => setOpen(true)) }}>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{fields && !fields.length && (
|
||||
<div className="mb-2.5 text-2xs text-faint">v{version} 没有输入字段,将直接运行</div>
|
||||
)}
|
||||
{fields && (
|
||||
<FieldsForm fields={fields} values={values} onChange={setValues} onSubmit={() => void launch()} />
|
||||
)}
|
||||
<button type="button" className="btn w-full justify-center sf-formal-go"
|
||||
disabled={busy || fields == null} onClick={() => void launch()}>
|
||||
{busy ? <Spinner size={11} /> : <ShieldCheck size={12} />} {label}
|
||||
</button>
|
||||
{!!fields?.length && (
|
||||
<div className="mt-1.5 flex items-center gap-1 text-2xs text-faint">
|
||||
<Kbd combo="Mod+Enter" /> 在输入框里直接{runClassLabel('formal')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function RunControl() {
|
||||
const phase = useStudio((s) => s.runPhase)
|
||||
const workflowId = useStudio((s) => s.workflow?.id)
|
||||
const published = useStudio((s) => s.workflow?.published_version)
|
||||
const active = isActivePhase(phase)
|
||||
|
||||
// Esc:回放中先回到实时,运行结束后清掉画布上的结果。别的层(输入框、弹窗、
|
||||
// 属性面板、发起浮层)先处理 Esc 时这里让路
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => { if (escapeRun(e)) e.preventDefault() }
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5" data-run-control>
|
||||
{phase !== 'idle' && <RunCapsule />}
|
||||
{/* 运行中只留胶囊:同一张画布同一时刻只跟一次运行 */}
|
||||
{!active && (
|
||||
<>
|
||||
<ExploreLauncher tight={phase !== 'idle'} />
|
||||
{workflowId && published ? <FormalLauncher workflowId={workflowId} version={published} /> : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,727 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from 'react'
|
||||
import {
|
||||
ChevronDown, Crosshair, Eraser, Hand, History, LocateFixed, Radio, RotateCw, Square,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { Kbd, Spinner, StatusBadge, toast } from '../components/ui'
|
||||
import { formatClock, formatCost, formatDuration, formatTokens, NONE } from '../lib/format'
|
||||
import { isTypingTarget, matchShortcut } from '../lib/keys'
|
||||
import { statusMeta, STATUS, type StatusCode } from '../lib/status'
|
||||
import { issuanceLabel, runClassLabel } from '../lib/terms'
|
||||
import { lastStampOf, projectSettled, useDock, waitedMs } from '../canvas/RunTimeline'
|
||||
import { structureSig, useStudio } from '../store/studio'
|
||||
import { topology } from './derive'
|
||||
import {
|
||||
isActivePhase, isSettled, isTerminal, liveAt, project, type NodeState, type RunPhase, type Trace,
|
||||
} from './trace'
|
||||
import { useRunClock } from './useRunClock'
|
||||
|
||||
/**
|
||||
* 运行胶囊与遥测面板。
|
||||
*
|
||||
* 以前运行时工具栏只剩一个「停止」:跑了多久、跑到哪、卡在哪、花了多少,
|
||||
* 要么翻右栏时间线去拼,要么不知道。这里把它们收成一枚胶囊,点开是一块
|
||||
* 遥测面板,数字全部来自航迹(run/trace.ts)——画布、时间轴、这里讲同一个故事。
|
||||
*
|
||||
* 规矩:
|
||||
* - 只显示诚实的量。拿不到写「—」;不画确定百分比的进度条(分支图里总有节点
|
||||
* 走不到,循环会让同一节点跑好几遍,百分比要么停在 6/8 要么超过 100%)。
|
||||
* - 正常态安静:运行中只有一圈转动的徽标;等人、失败、挂起才上底色。
|
||||
* - 主动作随相位变:在跑能停止,等人去审批,失败定位 + 接着跑,结束了回放 + 清除。
|
||||
* 等审批时后端已经不在执行,停止必然 409,所以那时不给停止。
|
||||
*/
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 时限:GET /api/system 的 limits,全站取一次
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
let limitCache: number | null | undefined
|
||||
let limitLoading: Promise<void> | null = null
|
||||
|
||||
function useRunLimit(): number | null {
|
||||
const [ms, setMs] = useState<number | null>(limitCache ?? null)
|
||||
useEffect(() => {
|
||||
if (limitCache !== undefined) return
|
||||
limitLoading ??= api.system()
|
||||
.then((s) => {
|
||||
const sec = Number(s?.limits?.max_run_seconds)
|
||||
limitCache = Number.isFinite(sec) && sec > 0 ? sec * 1000 : null
|
||||
})
|
||||
.catch(() => { limitCache = null })
|
||||
void limitLoading.then(() => setMs(limitCache ?? null))
|
||||
}, [])
|
||||
return ms
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 一次运行此刻的样子。胶囊、面板、属性面板底部那条都读它
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export interface Attention {
|
||||
kind: 'failed' | 'waiting' | 'budget'
|
||||
nodeId?: string
|
||||
title: string
|
||||
detail?: string
|
||||
}
|
||||
|
||||
export interface RunGlance {
|
||||
phase: RunPhase
|
||||
/** 显示用的状态码(lib/status) */
|
||||
code: StatusCode
|
||||
label: string
|
||||
replay: boolean
|
||||
/** 正在看的时刻(毫秒) */
|
||||
at: number
|
||||
elapsedMs: number
|
||||
activeMs: number
|
||||
waitMs: number
|
||||
/** 一句话:此刻在跑谁 / 停在谁 / 失败于谁 */
|
||||
headline: string
|
||||
executing: boolean
|
||||
/** 拓扑序的每个节点此刻的状态 */
|
||||
cells: { id: string; label: string; state: NodeState }[]
|
||||
done: number
|
||||
visited: number
|
||||
parallelNow: number
|
||||
series: [number, number][]
|
||||
tokens: number | null
|
||||
cost: number | null
|
||||
/** 这一段执行还剩多少时间;null = 不知道上限或眼下不在计时 */
|
||||
remainingMs: number | null
|
||||
limitMs: number | null
|
||||
attention: Attention[]
|
||||
failedNodeId?: string
|
||||
waitingNodeId?: string
|
||||
}
|
||||
|
||||
const firstLine = (s: string | undefined | null): string => (s ?? '').trim().split('\n')[0].slice(0, 90)
|
||||
|
||||
/** 相位的叫法。挂起在窄处写短名「已中断」,完整说法放 title */
|
||||
export function phaseLabel(phase: RunPhase): string {
|
||||
if (phase === 'suspended') return STATUS.suspended.short
|
||||
return statusMeta(phase).label
|
||||
}
|
||||
|
||||
function headlineOf(t: Trace, phase: RunPhase, states: Record<string, NodeState>, at: number,
|
||||
label: (id: string) => string, errorText: string | null | undefined): string {
|
||||
const running = Object.keys(states).filter((id) => states[id] === 'running')
|
||||
switch (phase) {
|
||||
case 'queued':
|
||||
return '排队中:等空出执行名额'
|
||||
case 'running': {
|
||||
const exec = running.filter((id) => !t.nodes[id]?.looping)
|
||||
if (!exec.length) {
|
||||
const loop = running.find((id) => t.nodes[id]?.looping)
|
||||
return loop ? `「${label(loop)}」第 ${t.nodes[loop]?.iteration ?? 1} 轮之间` : '调度下一步…'
|
||||
}
|
||||
// 协作团队:几个人同时在干
|
||||
const team = exec.map((id) => {
|
||||
const members = t.nodes[id]?.segments.filter((s) => s.kind === 'member' && s.start <= at
|
||||
&& (s.end == null || s.end > at)).length ?? 0
|
||||
return members > 1 ? `${label(id)} · ${members} 人并行` : label(id)
|
||||
})
|
||||
return team.slice(0, 2).join(' // ') + (team.length > 2 ? ` 等 ${team.length} 个` : '')
|
||||
}
|
||||
case 'waiting': {
|
||||
// 相位已经写着「等待审批」,这一句说停在谁、等了多久(和坞头、泳道同一个数,见 waitedMs)
|
||||
const id = t.waitingNodeId ?? Object.keys(states).find((k) => states[k] === 'waiting')
|
||||
if (!id) return '等人处理审批卡'
|
||||
const waited = waitedMs(t, id, at)
|
||||
return `停在「${label(id)}」${waited != null ? ` · 已等 ${formatClock(waited)}` : ''}`
|
||||
}
|
||||
case 'failed': {
|
||||
const id = t.failedNodeId
|
||||
const why = firstLine(t.nodes[id ?? '']?.error || errorText)
|
||||
return `${id ? `失败于「${label(id)}」` : '运行失败'}${why ? `:${why}` : ''}`
|
||||
}
|
||||
case 'succeeded':
|
||||
return t.issuance?.tier ? `执行完成 · ${issuanceLabel(t.issuance.tier)}` : '执行完成'
|
||||
case 'cancelled': {
|
||||
const stopped = Object.keys(states).filter((id) => states[id] === 'cancelled')
|
||||
return stopped.length ? `停在「${label(stopped[0])}」` : '已取消'
|
||||
}
|
||||
case 'suspended':
|
||||
return '服务重启时挂起,可从断点接着跑'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function useRunGlance(active: boolean): RunGlance {
|
||||
const trace = useStudio((s) => s.trace)
|
||||
const phaseLive = useStudio((s) => s.runPhase)
|
||||
const replayAt = useStudio((s) => s.replayAt)
|
||||
const usage = useStudio((s) => s.usageLive)
|
||||
const runUsage = useStudio((s) => s.run?.usage)
|
||||
const runError = useStudio((s) => s.run?.error)
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const limitMs = useRunLimit()
|
||||
const ticking = active && replayAt == null && isActivePhase(phaseLive)
|
||||
const now = useRunClock(ticking)
|
||||
|
||||
const order = useMemo(() => topology({ nodes, edges }).order, [nodes, edges])
|
||||
const labels = useMemo(() => new Map(nodes.map((n) => [n.id, n.data.label || n.id])), [nodes])
|
||||
const label = (id: string) => labels.get(id) ?? id
|
||||
|
||||
const live = isActivePhase(phaseLive)
|
||||
const at = replayAt ?? (live ? liveAt(trace, now) : lastStampOf(trace))
|
||||
// 停下之后按「最后一刻之后」投影:节点状态含推导出的阻断 / 未到达,时长用后端给的
|
||||
const proj = replayAt == null && !live ? projectSettled(trace) : project(trace, at)
|
||||
const phase = replayAt != null ? proj.phase : phaseLive
|
||||
const states: Record<string, NodeState> = {}
|
||||
for (const id of order) states[id] = proj.nodes[id]?.state ?? 'idle'
|
||||
for (const id of Object.keys(proj.nodes)) states[id] ??= proj.nodes[id].state
|
||||
|
||||
const cells = order.map((id) => ({ id, label: label(id), state: states[id] }))
|
||||
const done = cells.filter((c) => c.state === 'done' || c.state === 'skipped').length
|
||||
const visited = cells.filter((c) => (trace.nodes[c.id]?.count ?? 0) > 0 || c.state === 'skipped').length
|
||||
|
||||
// 用量:跑的时候看实时累加,终态用后端累计校正(老后端的 agent / 协作调用不发 llm.end)。
|
||||
// 还没收到任何一次模型调用的用量时写「—」,不写「0 tok」:那是不知道,不是零
|
||||
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
||||
const settledUsage = isTerminal(phaseLive) && runUsage
|
||||
const backendTok = settledUsage && (num(runUsage.input_tokens) != null || num(runUsage.output_tokens) != null)
|
||||
? (num(runUsage.input_tokens) ?? 0) + (num(runUsage.output_tokens) ?? 0)
|
||||
: settledUsage ? num(runUsage.total_tokens) : null
|
||||
const backendCost = settledUsage ? num(runUsage.cost_usd) : null
|
||||
const seen = usage.tokensIn + usage.tokensOut > 0 || usage.costUsd > 0
|
||||
const tokens = replayAt != null ? null : backendTok ?? (seen ? usage.tokensIn + usage.tokensOut : null)
|
||||
const cost = replayAt != null ? null : backendCost ?? (seen ? usage.costUsd : null)
|
||||
|
||||
// 时限按"这一段执行"计:等人工审批时执行已经结束,那段不算(和后端一致)
|
||||
const drive = trace.drives[trace.drives.length - 1]
|
||||
const remainingMs = limitMs != null && phase === 'running' && drive && drive[1] == null
|
||||
? Math.max(0, limitMs - (at - drive[0])) : null
|
||||
|
||||
const attention: Attention[] = []
|
||||
for (const c of cells) {
|
||||
if (c.state !== 'failed') continue
|
||||
attention.push({ kind: 'failed', nodeId: c.id, title: `失败 · ${c.label}`, detail: firstLine(trace.nodes[c.id]?.error) || undefined })
|
||||
}
|
||||
for (const c of cells) {
|
||||
if (c.state !== 'waiting') continue
|
||||
const waited = waitedMs(trace, c.id, at)
|
||||
attention.push({
|
||||
kind: 'waiting', nodeId: c.id, title: `等待审批 · ${c.label}`,
|
||||
detail: waited != null ? `已等 ${formatClock(waited)}` : undefined,
|
||||
})
|
||||
}
|
||||
if (remainingMs != null && limitMs != null && remainingMs < Math.max(60_000, limitMs * 0.2)) {
|
||||
const running = cells.find((c) => c.state === 'running')
|
||||
attention.push({
|
||||
kind: 'budget', nodeId: running?.id, title: '时限将尽',
|
||||
detail: `这一段执行还剩 ${formatClock(remainingMs).replace(/\.\d$/, '')},上限 ${formatDuration(limitMs)}`,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
phase, code: phase, label: phaseLabel(phase), replay: replayAt != null, at,
|
||||
elapsedMs: proj.elapsedMs, activeMs: proj.activeMs, waitMs: proj.waitMs,
|
||||
headline: headlineOf(trace, phase, states, at, label, runError),
|
||||
executing: phase === 'running' && cells.some((c) => c.state === 'running' && !trace.nodes[c.id]?.looping),
|
||||
cells, done, visited, parallelNow: proj.parallelNow, series: trace.parallelSeries,
|
||||
tokens, cost, remainingMs, limitMs, attention,
|
||||
failedNodeId: trace.failedNodeId, waitingNodeId: trace.waitingNodeId,
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 动作
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 去审批:不在画布上另做审批控件,只把人带到右栏那张审批卡——同一个组件、同一套
|
||||
* 治理口径(只认明确的同意,带备注)。右栏归助手面板:先广播一声,让它在对话层时
|
||||
* 切到运行层;再等几帧找卡片,找到就滚过去、描一圈、把焦点放进去。
|
||||
*/
|
||||
function gotoApproval(nodeId: string | undefined): void {
|
||||
const s = useStudio.getState()
|
||||
// 属性面板盖在右栏上:先让开,审批卡在右栏里
|
||||
s.select(null)
|
||||
if (nodeId) s.focusNode(nodeId)
|
||||
window.dispatchEvent(new CustomEvent('agentlab:goto-approval', { detail: { runId: s.run?.id, nodeId } }))
|
||||
let tries = 0
|
||||
const find = () => {
|
||||
const slot = document.querySelector<HTMLElement>('[data-approval-slot]:not(:empty)')
|
||||
if (!slot) {
|
||||
if (tries++ < 12) requestAnimationFrame(find)
|
||||
// 审批列表几秒轮询一次:刚停下来时卡片可能还没到,说实话,别让按钮像是坏了
|
||||
else toast.info('审批卡还没出现在右栏:审批列表每几秒刷新一次,稍等再点', { key: 'hud:approval' })
|
||||
return
|
||||
}
|
||||
const card = slot.querySelector<HTMLElement>('[data-approval]') ?? slot
|
||||
card.scrollIntoView({ block: 'center', behavior: reducedMotion() ? 'auto' : 'smooth' })
|
||||
card.classList.add('sf-flash')
|
||||
setTimeout(() => card.classList.remove('sf-flash'), 1600)
|
||||
card.querySelector<HTMLElement>('textarea, input, button')?.focus({ preventScroll: true })
|
||||
}
|
||||
requestAnimationFrame(find)
|
||||
}
|
||||
|
||||
const reducedMotion = (): boolean =>
|
||||
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
try {
|
||||
await useStudio.getState().stopRun()
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
function startReplay(trace: Trace): void {
|
||||
if (trace.startedAt == null) return
|
||||
useDock.getState().set({ open: true, playing: true })
|
||||
useStudio.getState().setReplayAt(trace.startedAt)
|
||||
}
|
||||
|
||||
function clear(): void {
|
||||
useDock.getState().set({ playing: false })
|
||||
useStudio.getState().clearRun()
|
||||
}
|
||||
|
||||
/** 接着跑:失败的从失败节点续;服务重启挂起的从断点恢复(和记录页同一条路) */
|
||||
function useResume(phase: RunPhase) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const snapshot = useStudio((s) => s.runSnapshot?.structure)
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const errors = useStudio((s) => s.issues.filter((i) => i.level === 'error').length)
|
||||
// 骨架签名要排序,按图算一次;别写进选择器里——那样每个 token 事件都会重排一遍
|
||||
const structure = useMemo(
|
||||
() => (phase === 'failed' && snapshot != null ? structureSig(nodes, edges) : null),
|
||||
[phase, snapshot, nodes, edges],
|
||||
)
|
||||
const structureChanged = structure != null && snapshot !== structure
|
||||
const blockedBy = structureChanged
|
||||
? '增删过节点或连线:接着跑只接受结构不变的图,需要重新运行'
|
||||
: phase === 'failed' && errors ? `画布上有 ${errors} 个问题要先改掉` : ''
|
||||
const resume = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const s = useStudio.getState()
|
||||
if (phase === 'suspended' && s.run) {
|
||||
await api.runs.resume(s.run.id, null)
|
||||
await s.attachRun(s.run.id)
|
||||
} else {
|
||||
await s.continueRun()
|
||||
}
|
||||
toast.ok('从断点接着跑,前面跑过的节点不重来')
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
return { busy, resume, blockedBy }
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 小件
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** 并行度的迷你阶梯线 */
|
||||
function Spark({ series, at, width = 64, height = 16 }: { series: [number, number][]; at: number; width?: number; height?: number }) {
|
||||
if (series.length < 1) return <span className="sf-dim">{NONE}</span>
|
||||
const t0 = series[0][0]
|
||||
const span = Math.max(1, at - t0)
|
||||
const peak = Math.max(1, ...series.map(([, v]) => v))
|
||||
const x = (t: number) => ((Math.min(t, at) - t0) / span) * width
|
||||
const y = (v: number) => height - 1 - (v / peak) * (height - 3)
|
||||
let d = `M0 ${y(0)}`
|
||||
for (const [ts, v] of series) {
|
||||
if (ts > at) break
|
||||
d += ` H${x(ts).toFixed(1)} V${y(v).toFixed(1)}`
|
||||
}
|
||||
d += ` H${width}`
|
||||
return (
|
||||
<svg className="sf-spark" width={width} height={height} aria-hidden>
|
||||
<path d={`${d} V${height} H0 Z`} className="sf-spark-area" />
|
||||
<path d={d} className="sf-spark-line" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
/** 时限余量的小圆环:静态的,不转 */
|
||||
function Budget({ remaining, limit }: { remaining: number; limit: number }) {
|
||||
const r = 7
|
||||
const c = 2 * Math.PI * r
|
||||
const f = Math.max(0, Math.min(1, remaining / limit))
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" className="sf-budget" aria-hidden>
|
||||
<circle cx="9" cy="9" r={r} className="sf-budget-track" />
|
||||
<circle cx="9" cy="9" r={r} className="sf-budget-fill" strokeDasharray={`${c * f} ${c}`}
|
||||
transform="rotate(-90 9 9)" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
/** 拓扑序小格条。格子可以有七十多个:整条只占一个 Tab 位,左右键在格子间走 */
|
||||
function Cells({ cells, onPick }: { cells: RunGlance['cells']; onPick: (id: string) => void }) {
|
||||
const [cur, setCur] = useState(0)
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const at = Math.min(cur, Math.max(0, cells.length - 1))
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
const next = e.key === 'ArrowRight' ? at + 1 : e.key === 'ArrowLeft' ? at - 1
|
||||
: e.key === 'Home' ? 0 : e.key === 'End' ? cells.length - 1 : null
|
||||
if (next == null) return
|
||||
e.preventDefault()
|
||||
const i = Math.max(0, Math.min(cells.length - 1, next))
|
||||
setCur(i)
|
||||
box.current?.querySelectorAll<HTMLButtonElement>('.sf-cell')[i]?.focus()
|
||||
}
|
||||
return (
|
||||
<div className="sf-cells" role="list" aria-label="各节点状态(按拓扑序,左右键切换)" ref={box} onKeyDown={onKeyDown}>
|
||||
{cells.map((c, i) => {
|
||||
const name = `${c.label} · ${statusMeta(c.state).label}`
|
||||
return (
|
||||
<div key={c.id} role="listitem" className="sf-cell-slot">
|
||||
<button type="button" className={`sf-cell sf-st-${c.state}`} tabIndex={i === at ? 0 : -1}
|
||||
title={name} aria-label={`${name},在画布上定位`}
|
||||
onFocus={() => setCur(i)} onClick={() => onPick(c.id)} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const COUNT_ORDER: NodeState[] = [
|
||||
'running', 'waiting', 'failed', 'suspended', 'done', 'queued', 'blocked', 'unreached', 'skipped', 'cancelled',
|
||||
]
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 胶囊(工具栏里)+ 展开的面板
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export function RunCapsule() {
|
||||
const [open, setOpen] = useState(false)
|
||||
const g = useRunGlance(true)
|
||||
const run = useStudio((s) => s.run)
|
||||
const trace = useStudio((s) => s.trace)
|
||||
const follow = useStudio((s) => s.follow)
|
||||
const phaseLive = useStudio((s) => s.runPhase)
|
||||
const { busy, resume, blockedBy } = useResume(g.phase)
|
||||
const wrap = useRef<HTMLDivElement>(null)
|
||||
const cycle = useRef(0)
|
||||
const active = isActivePhase(g.phase)
|
||||
const runClass = run?.run_class ?? trace.runClass ?? 'exploratory'
|
||||
const focus = (id?: string) => { if (id) useStudio.getState().focusNode(id) }
|
||||
|
||||
// 点外面、按 Esc 关掉面板
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onDown = (e: MouseEvent) => { if (!wrap.current?.contains(e.target as Node)) setOpen(false) }
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape' || e.isComposing || isTypingTarget(e.target)) return
|
||||
e.preventDefault()
|
||||
setOpen(false)
|
||||
}
|
||||
window.addEventListener('mousedown', onDown)
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', onDown)
|
||||
window.removeEventListener('keydown', onKey)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
// F:在「需要处理」里逐个定位(失败 > 等人 > 时限将尽)
|
||||
const attentionRef = useRef(g.attention)
|
||||
attentionRef.current = g.attention
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented || isTypingTarget(e.target) || !matchShortcut(e, 'F')) return
|
||||
// 有选中的节点时 F 是"对准选中的"(编排页的快捷键表)。两个监听谁先注册说不准,这里自己让路
|
||||
if (useStudio.getState().selectedId) return
|
||||
const items = attentionRef.current.filter((a) => a.nodeId)
|
||||
if (!items.length) return
|
||||
e.preventDefault()
|
||||
const item = items[cycle.current % items.length]
|
||||
cycle.current += 1
|
||||
focus(item.nodeId)
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
const alert = g.phase === 'waiting' || g.phase === 'failed' || g.phase === 'suspended'
|
||||
const terminal = isSettled(g.phase)
|
||||
// 运行本身结束了(回放时 g.phase 是游标那一刻的相位):工具栏上还要放发起按钮,胶囊收窄
|
||||
const narrow = isSettled(phaseLive)
|
||||
const tokens = g.tokens != null ? formatTokens(g.tokens, { compact: true }) : NONE
|
||||
const nodesText = terminal && !g.replay ? `${g.visited}/${g.cells.length}` : `${g.done}/${g.cells.length}`
|
||||
|
||||
// compact = 胶囊里:结束之后发起按钮也要挤进工具栏,次要动作在窄屏上只留图标
|
||||
const actions = (compact: boolean) => {
|
||||
if (g.replay) {
|
||||
return (
|
||||
<Act icon={<Radio size={11} />} text="回到实时" title="游标回到现在"
|
||||
onClick={() => { useDock.getState().set({ playing: false }); useStudio.getState().setReplayAt(null) }} />
|
||||
)
|
||||
}
|
||||
switch (g.phase) {
|
||||
case 'queued':
|
||||
case 'running':
|
||||
return (
|
||||
<Act className="btn-danger" icon={<Square size={10} fill="currentColor" />} text="停止"
|
||||
title="停止这次运行" onClick={() => void stop()} />
|
||||
)
|
||||
case 'waiting':
|
||||
return (
|
||||
<Act className="sf-btn-warn" icon={<Hand size={11} />} text="去审批"
|
||||
title="到右栏的审批卡上处理。等审批时运行已经停在断点上,停止不了"
|
||||
onClick={() => gotoApproval(g.waitingNodeId ?? g.attention.find((a) => a.kind === 'waiting')?.nodeId)} />
|
||||
)
|
||||
case 'failed':
|
||||
return (
|
||||
<>
|
||||
{g.failedNodeId && (
|
||||
<Act icon={<LocateFixed size={11} />} text="定位" iconOnly={compact}
|
||||
title="画布取景到失败的节点" onClick={() => focus(g.failedNodeId)} />
|
||||
)}
|
||||
<Act className="btn-primary" disabled={busy || !!blockedBy} text="接着跑"
|
||||
icon={busy ? <Spinner size={10} /> : <RotateCw size={11} />}
|
||||
title={blockedBy || '从失败的那个节点接着跑,前面跑过的节点不重来。只能改节点配置'}
|
||||
onClick={() => void resume()} />
|
||||
{!compact && <ClearButton kbd />}
|
||||
</>
|
||||
)
|
||||
case 'suspended':
|
||||
return (
|
||||
<>
|
||||
<Act className="btn-primary" disabled={busy} text="接着跑"
|
||||
icon={busy ? <Spinner size={10} /> : <RotateCw size={11} />}
|
||||
title="服务重启打断了这次运行,checkpoint 完好,从断点恢复"
|
||||
onClick={() => void resume()} />
|
||||
{!compact && <ClearButton kbd />}
|
||||
</>
|
||||
)
|
||||
case 'succeeded':
|
||||
case 'cancelled':
|
||||
return (
|
||||
<>
|
||||
{/* 结束之后工具栏上还有两个发起按钮:1536 以下这两个只留图标,面板里有全名 */}
|
||||
<Act icon={<History size={11} />} text="回放" textFrom={compact ? '2xl' : undefined}
|
||||
disabled={trace.startedAt == null}
|
||||
title="在画布上按时间重放这次运行" onClick={() => startReplay(trace)} />
|
||||
<ClearButton kbd={!compact} textFrom={compact ? '2xl' : undefined} />
|
||||
</>
|
||||
)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<div className="relative" ref={wrap}>
|
||||
<div className={clsx('sf-capsule', alert && 'is-alert')} data-phase={g.phase} data-replay={g.replay ? '1' : undefined}>
|
||||
<button type="button" className="sf-cap-main" onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open} aria-haspopup="dialog"
|
||||
title={open ? '收起运行遥测' : `${g.label} · ${g.headline}\n点开看遥测`}>
|
||||
<StatusBadge status={g.code} size={14} animate={g.executing} decorative />
|
||||
<span className="sf-cap-label">{g.replay ? `回放 · ${g.label}` : g.label}</span>
|
||||
{/* 结束之后工具栏还要放发起按钮:窄屏上计时收进面板和航迹里 */}
|
||||
<span className={clsx('sf-cap-sep', narrow && 'hidden xl:block')} />
|
||||
<span className={clsx('sf-cap-clock tnum', narrow && 'hidden xl:inline')} data-clock>
|
||||
{formatClock(g.elapsedMs)}
|
||||
</span>
|
||||
{/* 窄处只留相位和计时;节点数、用量在面板里。结束之后胶囊让出地方给发起按钮 */}
|
||||
{!narrow && !g.replay && (
|
||||
<>
|
||||
<span className="sf-cap-sep hidden lg:block" />
|
||||
<span className="sf-cap-nodes tnum hidden lg:inline" title="完成的节点 / 全部节点">{nodesText}</span>
|
||||
<span className="sf-cap-sep hidden xl:block" />
|
||||
<span className="sf-cap-usage tnum hidden xl:inline">
|
||||
{tokens}{g.cost ? ` · ${formatCost(g.cost)}` : ''}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<ChevronDown size={11} className={clsx('sf-cap-chev', narrow && 'hidden xl:block')}
|
||||
style={{ transform: open ? 'rotate(180deg)' : undefined }} />
|
||||
</button>
|
||||
<div className="sf-cap-actions">{actions(true)}</div>
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<div className="sf-hud sheet-in" role="dialog" aria-label="运行遥测" data-phase={g.phase} data-esc-layer>
|
||||
<div className="sf-hud-top">
|
||||
<StatusBadge status={g.code} size={18} animate={g.executing} decorative />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="sf-hud-phase">{g.replay ? `回放 · ${g.label}` : g.label}</span>
|
||||
<span className={clsx('sf-class', runClass === 'formal' && 'is-formal')}>
|
||||
{runClassLabel(runClass, run?.version)}{runClass === 'formal' && active ? ' · 画布只读' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="sf-hud-line" title={g.headline}>{g.headline || NONE}</div>
|
||||
</div>
|
||||
{/* 跟随只对还在跑的运行有意义:结束了、在回放时画布不会自己动 */}
|
||||
{isActivePhase(phaseLive) && !g.replay && (
|
||||
<label className="sf-follow-toggle" title="跟着正在执行的节点平移画布;手动平移后暂停 10 秒">
|
||||
<input type="checkbox" checked={follow} onChange={(e) => useStudio.getState().setFollow(e.target.checked)} />
|
||||
<Crosshair size={11} /> 跟随
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="sf-hud-grid">
|
||||
<div className="sf-metric">
|
||||
<div className="sf-metric-k">墙钟</div>
|
||||
<div className="sf-metric-v tnum">T+{formatClock(g.elapsedMs)}</div>
|
||||
{/* 执行和等人分两行:挤在一行时后半截被截掉,恰好是等人那段 */}
|
||||
<div className="sf-metric-s tnum">执行 {formatClock(g.activeMs)}</div>
|
||||
{(g.waitMs > 0 || g.phase === 'waiting') && (
|
||||
<div className={clsx('sf-metric-s tnum', g.phase === 'waiting' && 'sf-warn')}>等人 {formatClock(g.waitMs)}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="sf-metric sf-metric-wide">
|
||||
<div className="sf-metric-k">节点</div>
|
||||
<div className="sf-metric-v tnum">
|
||||
{nodesText}
|
||||
<span className="sf-metric-u">{terminal && !g.replay ? ' 经过' : ' 完成'}</span>
|
||||
</div>
|
||||
<Cells cells={g.cells} onPick={focus} />
|
||||
</div>
|
||||
<div className="sf-metric">
|
||||
<div className="sf-metric-k">并行</div>
|
||||
<div className="sf-metric-v tnum">{active || g.replay ? `${g.parallelNow} 路` : NONE}</div>
|
||||
<Spark series={g.series} at={g.at} />
|
||||
</div>
|
||||
<div className="sf-metric">
|
||||
<div className="sf-metric-k">用量</div>
|
||||
<div className="sf-metric-v tnum">{tokens}</div>
|
||||
<div className="sf-metric-s tnum">{g.cost != null ? `≈ ${formatCost(g.cost)}` : NONE}</div>
|
||||
</div>
|
||||
<div className="sf-metric">
|
||||
<div className="sf-metric-k">时限</div>
|
||||
{g.remainingMs != null && g.limitMs != null ? (
|
||||
<>
|
||||
<div className={clsx('sf-metric-v tnum flex items-center gap-1.5',
|
||||
g.remainingMs < g.limitMs * 0.2 && 'sf-warn')}>
|
||||
<Budget remaining={g.remainingMs} limit={g.limitMs} />
|
||||
余 {formatClock(g.remainingMs).replace(/\.\d$/, '')}
|
||||
</div>
|
||||
<div className="sf-metric-s" title="每一段执行各算各的:审批恢复、接着跑之后重新计">
|
||||
上限 {formatDuration(g.limitMs)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="sf-metric-v">{g.phase === 'waiting' ? '暂停计时' : NONE}</div>
|
||||
<div className="sf-metric-s" title={g.phase === 'waiting' ? '等人审批不算执行时间,时限不走' : undefined}>
|
||||
{g.phase === 'waiting' ? '等人不计时' : g.limitMs ? `上限 ${formatDuration(g.limitMs)}` : ''}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sf-hud-counts">
|
||||
{COUNT_ORDER.map((st) => {
|
||||
const ids = g.cells.filter((c) => c.state === st).map((c) => c.id)
|
||||
if (!ids.length) return null
|
||||
const meta = statusMeta(st)
|
||||
return (
|
||||
<button key={st} type="button" className="sf-count" title={`${meta.label} ${ids.length} 个 · 点一下逐个定位`}
|
||||
onClick={() => { focus(ids[cycle.current % ids.length]); cycle.current += 1 }}>
|
||||
<StatusBadge status={st} size={12} animate={false} decorative />
|
||||
<span className="tnum">{ids.length}</span>
|
||||
<span className="sf-dim">{meta.short}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{g.attention.length > 0 && (
|
||||
<div className="sf-queue">
|
||||
<div className="sf-queue-head">
|
||||
<span>需要处理</span>
|
||||
<span className="tnum sf-dim">{g.attention.length}</span>
|
||||
<span className="flex-1" />
|
||||
<span className="sf-dim">逐个定位</span> <Kbd combo="F" />
|
||||
</div>
|
||||
{g.attention.map((a, i) => (
|
||||
<div key={`${a.kind}${a.nodeId ?? i}`} className={clsx('sf-queue-item', `is-${a.kind}`)}>
|
||||
<StatusBadge status={a.kind === 'budget' ? 'waiting' : a.kind} size={12} animate={false} decorative />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate">{a.title}</div>
|
||||
{a.detail && <div className="sf-dim truncate tnum">{a.detail}</div>}
|
||||
</div>
|
||||
{a.kind === 'waiting' ? (
|
||||
<button type="button" className="btn btn-xs" onClick={() => gotoApproval(a.nodeId)}>去审批</button>
|
||||
) : a.nodeId ? (
|
||||
<button type="button" className="btn btn-xs" onClick={() => focus(a.nodeId)}>定位</button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="sf-hud-actions">
|
||||
{g.phase === 'failed' && blockedBy && <span className="sf-dim flex-1 truncate" title={blockedBy}>{blockedBy}</span>}
|
||||
<span className="flex-1" />
|
||||
{actions(false)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 文字从多宽开始露出来。类名要写全,Tailwind 按字面扫描 */
|
||||
const TEXT_FROM = { xl: 'hidden xl:inline', '2xl': 'hidden 2xl:inline' } as const
|
||||
|
||||
/**
|
||||
* 胶囊和面板里的动作按钮。iconOnly 只留图标;textFrom 在那个宽度以下只留图标。
|
||||
* 文字始终在 aria-label 里,读屏和检查脚本按名字找得到
|
||||
*/
|
||||
function Act({ icon, text, className, iconOnly = false, textFrom, children, ...rest }:
|
||||
ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
icon: ReactNode; text: string; iconOnly?: boolean; textFrom?: keyof typeof TEXT_FROM
|
||||
}) {
|
||||
return (
|
||||
<button type="button" className={clsx('btn btn-sm', className)} aria-label={text} {...rest}>
|
||||
{icon}
|
||||
{!iconOnly && <span className={textFrom ? TEXT_FROM[textFrom] : undefined}>{text}</span>}
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function ClearButton({ kbd = false, textFrom }: { kbd?: boolean; textFrom?: keyof typeof TEXT_FROM }) {
|
||||
return (
|
||||
<Act className="btn-ghost" icon={<Eraser size={11} />} text="清除" textFrom={textFrom} onClick={clear}
|
||||
title="清除这次运行在画布上的结果,回到编辑态(Esc)">
|
||||
{kbd && <Kbd combo="Esc" className="ml-0.5" />}
|
||||
</Act>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Esc 的分层:有别的东西在处理 Esc(输入框、弹窗、属性面板、胶囊面板)时让路;
|
||||
* 在回放就先回到实时;运行已经结束才清掉结果。返回 true 表示这一下被用掉了。
|
||||
*/
|
||||
export function escapeRun(e: KeyboardEvent): boolean {
|
||||
if (e.key !== 'Escape' || e.defaultPrevented || e.isComposing || isTypingTarget(e.target)) return false
|
||||
// 弹窗、发起浮层、遥测面板开着时,Esc 是关它们的
|
||||
if (document.querySelector('[role="dialog"][aria-modal="true"], [data-esc-layer]')) return false
|
||||
// 只认画布这一片(画布、航迹坞、工具栏的运行控件)或焦点哪儿都不在。焦点在右栏的
|
||||
// 步骤行、别的面板上时按 Esc 是想收起那一处,把整次运行的结果清掉就太意外了
|
||||
const focus = document.activeElement
|
||||
if (focus && focus !== document.body && !focus.closest('.react-flow, .tl, [data-run-control]')) return false
|
||||
const s = useStudio.getState()
|
||||
if (s.selectedId) return false
|
||||
if (s.replayAt != null) {
|
||||
useDock.getState().set({ playing: false })
|
||||
s.setReplayAt(null)
|
||||
return true
|
||||
}
|
||||
if (s.run && isSettled(s.runPhase)) {
|
||||
clear()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,28 +1,52 @@
|
||||
import { useState } from 'react'
|
||||
import { Ban, Check, Hand, Wrench } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Ban, Check, Hand, PenLine, Wrench } from 'lucide-react'
|
||||
import { api } from '../api/client'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { NODE_DEFS } from '../canvas/nodeDefs'
|
||||
import { StatusDot, useToast } from '../components/ui'
|
||||
import { formatDateTime, formatTime, parseServerTime } from '../lib/format'
|
||||
import { runClassLabel } from '../lib/terms'
|
||||
import { useRunClock } from './useRunClock'
|
||||
import { Markdown } from './Markdown'
|
||||
import type { Approval } from '../types'
|
||||
|
||||
// 发起运行的表单搬去了 run/RunControl.tsx 的工具栏控件里。它原先常驻在
|
||||
// 助手栏顶部,和 Copilot 输入框两个"主要动作"互相压着——而它们是两种不同的
|
||||
// 意图(跑这张图 / 改这张图),不该争同一块地方。运行是对整张图的动作,
|
||||
// 和保存、发布同类,属于工具栏。
|
||||
|
||||
/** 本机填的署名(设置 → 偏好设置),随 X-Actor 发给后端,写进审批留痕 */
|
||||
function localActor(): string {
|
||||
try { return (localStorage.getItem('agentlab_actor') ?? '').trim() } catch { return '' }
|
||||
}
|
||||
|
||||
/** 等了多久:「12 分钟」「5 小时」「8 天」。审批按天积压是常态,精确到秒没有意义 */
|
||||
function waited(ms: number): string {
|
||||
if (ms < 3_600_000) return `${Math.max(1, Math.round(ms / 60_000))} 分钟`
|
||||
if (ms < 48 * 3_600_000) return `${Math.floor(ms / 3_600_000)} 小时`
|
||||
return `${Math.floor(ms / 86_400_000)} 天`
|
||||
}
|
||||
|
||||
/**
|
||||
* 人工介入卡片。
|
||||
* 审批卡。
|
||||
*
|
||||
* 卡头交代上下文:哪个工作流、挂在哪个节点、什么时候发起、已经等了多久(超过
|
||||
* 一天用琥珀色);按钮下面常显"批了会怎样",以前藏在驳回按钮的 hover 里;
|
||||
* 底部写明"将以谁的名义签批"——审批留痕记的是设置里的署名,没署名时静默记空,
|
||||
* 事后审计才发现没有人名。
|
||||
*
|
||||
* onResolved 是给非画布场景用的:这个组件被对话页和运行页复用,而默认的
|
||||
* "恢复后重新接上事件流"走的是 studio store——在对话页里用就会同时开两条
|
||||
* 订阅(一条 chat 的、一条 studio 的),两边各收一份事件。谁用谁负责重新
|
||||
* 接流,是唯一不会打架的分工。
|
||||
*/
|
||||
export function ApprovalCard({ approval, onResolved }: {
|
||||
approval: any
|
||||
export function ApprovalCard({ approval, onResolved, showWorkflow = true }: {
|
||||
approval: Approval | any
|
||||
onResolved?: (runId: string) => void | Promise<void>
|
||||
/** 画布上工作流就是眼前这张,卡头不用再说一遍 */
|
||||
showWorkflow?: boolean
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const refreshApprovals = useCatalog((s) => s.refreshApprovals)
|
||||
@@ -33,6 +57,13 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const payload = approval.payload ?? {}
|
||||
const actor = localActor()
|
||||
// 等待时长一分钟级就够,不订阅 100ms 的时钟;卡片因别的原因重画时顺带更新
|
||||
const now = useRunClock(false)
|
||||
const created = parseServerTime(approval.created_at)
|
||||
const age = created ? now - created.getTime() : undefined
|
||||
const stale = age != null && age > 24 * 3_600_000
|
||||
const approveMode = approval.mode === 'approve'
|
||||
|
||||
const decide = async (approved: boolean) => {
|
||||
setBusy(true)
|
||||
@@ -40,7 +71,7 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
await api.approvals.decide(approval.id, {
|
||||
approved,
|
||||
note,
|
||||
...(approval.mode !== 'approve' ? { value } : {}),
|
||||
...(!approveMode ? { value } : {}),
|
||||
})
|
||||
await refreshApprovals()
|
||||
// 恢复后重新接上事件流:调用方给了 onResolved 就听它的
|
||||
@@ -51,22 +82,42 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
toast(
|
||||
approved
|
||||
? '已放行,运行继续'
|
||||
: approval.mode === 'approve'
|
||||
? '已驳回'
|
||||
: '已驳回,本次运行终止',
|
||||
: approveMode ? '已驳回,走驳回那条出口' : '已驳回,本次运行终止',
|
||||
'ok',
|
||||
)
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '操作失败', 'error')
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const where = approval.node_label || approval.node_id
|
||||
return (
|
||||
<div className="fade-up border-b p-3" style={{ background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
|
||||
<div className="mb-2 flex items-center gap-1.5 text-xs font-semibold" style={{ color: 'var(--warn)' }}>
|
||||
<Hand size={13} /> {approval.title || '需要你确认'}
|
||||
<div className="fade-up border-b p-3 last:border-b-0" data-approval={approval.id}
|
||||
style={{ background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
|
||||
<div className="mb-1 flex items-center gap-1.5 text-xs font-semibold" style={{ color: 'var(--warn)' }}>
|
||||
<Hand size={13} aria-hidden /> {approval.title || '需要你确认'}
|
||||
</div>
|
||||
<div className="tnum mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-2xs text-dim">
|
||||
<span>人工审批</span>
|
||||
{showWorkflow && approval.workflow_name && <><span aria-hidden>·</span><span>{approval.workflow_name}</span></>}
|
||||
{where && <><span aria-hidden>·</span><span>节点「{where}」</span></>}
|
||||
{approval.run_class && <><span aria-hidden>·</span><span>{runClassLabel(approval.run_class)}</span></>}
|
||||
{created && (
|
||||
<>
|
||||
<span aria-hidden>·</span>
|
||||
<span title={formatDateTime(created)}>{formatTime(created)} 发起</span>
|
||||
</>
|
||||
)}
|
||||
{age != null && age >= 60_000 && (
|
||||
<>
|
||||
<span aria-hidden>·</span>
|
||||
<span style={stale ? { color: 'var(--st-waiting)', fontWeight: 600 } : undefined}>
|
||||
已等待 {waited(age)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{payload.message && (
|
||||
@@ -79,26 +130,27 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
|
||||
{payload.tool && (
|
||||
<div className="mb-2 rounded border bg-bg p-2">
|
||||
<div className="mb-1 flex items-center gap-1.5 text-[11px]">
|
||||
<Wrench size={11} /> <code className="mono">{payload.tool}</code>
|
||||
<div className="mb-1 flex items-center gap-1.5 text-2xs">
|
||||
<Wrench size={11} aria-hidden /> <code className="mono">{payload.tool}</code>
|
||||
</div>
|
||||
<pre className="mono max-h-32 overflow-auto text-[10px] leading-relaxed text-dim">
|
||||
<pre className="mono max-h-32 overflow-auto text-2xs leading-relaxed text-dim">
|
||||
{JSON.stringify(payload.args ?? {}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payload.code && (
|
||||
<pre className="mono mb-2 max-h-40 overflow-auto rounded border bg-bg p-2 text-[10px] leading-relaxed">
|
||||
<pre className="mono mb-2 max-h-40 overflow-auto rounded border bg-bg p-2 text-2xs leading-relaxed">
|
||||
{payload.code}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{approval.mode !== 'approve' && (
|
||||
{!approveMode && (
|
||||
<textarea
|
||||
className="field mb-2"
|
||||
rows={4}
|
||||
value={value}
|
||||
aria-label={approval.mode === 'edit' ? '修改后的内容' : '你的输入'}
|
||||
placeholder={approval.mode === 'edit' ? '修改后的内容' : '你的输入'}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
@@ -106,6 +158,7 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
|
||||
<input
|
||||
className="field mb-2"
|
||||
aria-label="备注"
|
||||
placeholder="备注(会传给后续节点)"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
@@ -113,17 +166,30 @@ export function ApprovalCard({ approval, onResolved }: {
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button className="btn btn-primary flex-1 justify-center" disabled={busy} onClick={() => decide(true)}>
|
||||
<Check size={12} /> {approval.mode === 'approve' ? '通过' : '提交'}
|
||||
<Check size={12} aria-hidden /> {approveMode ? '通过' : '提交'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger flex-1 justify-center"
|
||||
disabled={busy}
|
||||
onClick={() => decide(false)}
|
||||
title={approval.mode === 'approve' ? '不放行,走 rejected 分支' : '驳回并终止这次运行'}
|
||||
>
|
||||
<Ban size={12} /> {approval.mode === 'approve' ? '驳回' : '驳回并终止'}
|
||||
<button className="btn btn-danger flex-1 justify-center" disabled={busy} onClick={() => decide(false)}>
|
||||
<Ban size={12} aria-hidden /> {approveMode ? '驳回' : '驳回并终止'}
|
||||
</button>
|
||||
</div>
|
||||
{/* 批了会怎样,常显而不是藏在 hover 里:审批人得在按下去之前知道 */}
|
||||
<div className="mt-1.5 text-2xs leading-relaxed text-dim">
|
||||
{approveMode
|
||||
? '通过 → 接着往下跑;驳回 → 走「驳回」那条出口'
|
||||
: '提交 → 用你填的内容接着跑;驳回 → 这次运行到此终止'}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-1 text-2xs leading-relaxed"
|
||||
style={actor ? { color: 'var(--text-dim)' } : { color: 'var(--st-waiting)' }}>
|
||||
<PenLine size={10} aria-hidden className="shrink-0" />
|
||||
{actor
|
||||
? <span>将以「{actor}」签批,写进审批留痕</span>
|
||||
: (
|
||||
<span>
|
||||
未署名:这次签批不会记录审批人 ·{' '}
|
||||
<Link to="/settings/prefs" className="underline underline-offset-2 hover:text-fg">去设置署名</Link>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { RunEvent } from '../../types'
|
||||
|
||||
/**
|
||||
* 合成的运行事件:fixtures.json 里是真实运行导出的,但有几类事件是新后端才发
|
||||
* 的(agent.route.*、带 agent 的 llm.end、node.started 的 iteration/resumed、
|
||||
* 签批人、出具 gaps),老库里没有;还有 1800 条的长运行,真实导出放进仓库太大。
|
||||
*
|
||||
* 形状照后端 emit 的字段逐一对齐(multi.py、compiler.py、io.py、runner.py),
|
||||
* 解码器检查(scripts/check-decode.mjs)和离线预览(dev/preview.tsx)共用。
|
||||
* 不依赖任何别的模块:检查脚本是把它单独转译后在 node 里 import 的。
|
||||
*/
|
||||
|
||||
const T0 = 1_790_000_000 // 事件 ts 是秒
|
||||
|
||||
function builder(runId: string) {
|
||||
const out: RunEvent[] = []
|
||||
let seq = 0
|
||||
let t = T0
|
||||
const ev = (type: string, node: string | null, data: Record<string, any> = {}, dt = 0.05): RunEvent => {
|
||||
seq += 1
|
||||
t += dt
|
||||
const e = { seq, type, node_id: node, ts: Number(t.toFixed(3)), data, run_id: runId } as RunEvent
|
||||
out.push(e)
|
||||
return e
|
||||
}
|
||||
return { out, ev, at: () => t }
|
||||
}
|
||||
|
||||
/**
|
||||
* 三人协作团队:新后端的 agent.route.start/end 与带 round 的 log 同时发;成员
|
||||
* 一完成就发自己的 step.end;成员和调度者的 llm.end 没有 llm.start 在前。
|
||||
* upto='routing' 停在第 2 轮调度者还在想;upto='members' 停在第 1 轮三人并行中。
|
||||
*/
|
||||
export function teamRun(upto: 'routing' | 'members' | 'done' = 'done'): RunEvent[] {
|
||||
const { out, ev } = builder('syn-team')
|
||||
ev('run.started', null, { nodes: 3, resumed: false, memory_scope: 'default', approval_default: 'dangerous' })
|
||||
ev('node.started', 'in', { node_type: 'input', label: '问题' })
|
||||
ev('node.finished', 'in', { duration_ms: 1, attempt: 1, preview: { q: '比较三家供应商的交期风险' } })
|
||||
ev('node.started', 'team', { node_type: 'supervisor', label: '供应链分析团队' })
|
||||
ev('agent.route.start', 'team', { round: 0 })
|
||||
ev('llm.end', 'team', { agent: '调度者', model: 'claude-sonnet-4', duration_ms: 2400, input_tokens: 820, output_tokens: 96, cost_usd: 0.0039 }, 2.4)
|
||||
ev('agent.route.end', 'team', { round: 0, duration_ms: 2400, agents: ['采购员', '质检员', '物流员'], parallel: 3, done: false, reason: '三方面数据互不依赖,可以同时查' })
|
||||
ev('log', 'team', { level: 'info', round: 0, parallel: 3, agents: ['采购员', '质检员', '物流员'], done: false, reason: '三方面数据互不依赖,可以同时查', message: '调度 → 采购员、质检员、物流员(三方面数据互不依赖,可以同时查) · 3 人同时进行' })
|
||||
for (const [name, task] of [['采购员', '查近 90 天各供应商的交期'], ['质检员', '查来料不良率'], ['物流员', '查在途延误']]) {
|
||||
ev('agent.step.start', 'team', { agent: name, instruction: task, round: 0, parallel: 3 }, 0.001)
|
||||
}
|
||||
if (upto === 'members') {
|
||||
// 物流员已经交回,另外两人还在跑
|
||||
ev('llm.end', 'team', { agent: '物流员', model: 'claude-sonnet-4', duration_ms: 3100, input_tokens: 640, output_tokens: 210, cost_usd: 0.0051 }, 3.1)
|
||||
ev('agent.step.end', 'team', { agent: '物流员', duration_ms: 3100, round: 0, parallel: 3, preview: '在途延误集中在华南线,平均 1.8 天' })
|
||||
return out
|
||||
}
|
||||
ev('llm.end', 'team', { agent: '物流员', model: 'claude-sonnet-4', duration_ms: 3100, input_tokens: 640, output_tokens: 210, cost_usd: 0.0051 }, 3.1)
|
||||
ev('agent.step.end', 'team', { agent: '物流员', duration_ms: 3100, round: 0, parallel: 3, preview: '在途延误集中在华南线,平均 1.8 天' })
|
||||
ev('llm.end', 'team', { agent: '质检员', model: 'claude-sonnet-4', duration_ms: 4200, input_tokens: 700, output_tokens: 260, cost_usd: 0.006 }, 1.1)
|
||||
ev('agent.step.end', 'team', { agent: '质检员', duration_ms: 4200, round: 0, parallel: 3, preview: 'B 供应商来料不良率 2.4%,高于均值' })
|
||||
ev('tool.start', 'team', { tool: 'db_query__erp', agent: '采购员', call_id: 'c1', args: { sql: 'SELECT supplier, AVG(lead_days) FROM po_lines WHERE created_at > now() - interval 90 day GROUP BY supplier' } }, 0.2)
|
||||
ev('tool.end', 'team', { tool: 'db_query__erp', agent: '采购员', call_id: 'c1', duration_ms: 640, preview: '{"columns":["supplier","avg_lead"],"rows":[["A",12.1],["B",15.4],["C",9.8]],"row_count":3}', artifact: '3aad64e0c3f1b2a9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a7b6c5' }, 0.64)
|
||||
ev('llm.end', 'team', { agent: '采购员', model: 'claude-sonnet-4', duration_ms: 5600, input_tokens: 910, output_tokens: 300, cost_usd: 0.0072 }, 0.6)
|
||||
ev('agent.step.end', 'team', { agent: '采购员', duration_ms: 5600, round: 0, parallel: 3, preview: 'C 交期最短(9.8 天),B 最长(15.4 天)' })
|
||||
ev('agent.route.start', 'team', { round: 1 }, 0.05)
|
||||
if (upto === 'routing') return out
|
||||
ev('llm.end', 'team', { agent: '调度者', model: 'claude-sonnet-4', duration_ms: 1900, input_tokens: 1400, output_tokens: 80, cost_usd: 0.005 }, 1.9)
|
||||
ev('agent.route.end', 'team', { round: 1, duration_ms: 1900, agents: [], parallel: 0, done: true, reason: '三方面都有结论,可以收尾' })
|
||||
ev('log', 'team', { level: 'info', round: 1, agents: [], done: true, message: '调度 → 结束协作(三方面都有结论,可以收尾)' })
|
||||
ev('node.finished', 'team', { duration_ms: 12100, attempt: 1, preview: { text: 'C 综合最优' } })
|
||||
ev('node.started', 'out', { node_type: 'output', label: '成果' })
|
||||
ev('node.finished', 'out', { duration_ms: 1, attempt: 1, preview: { 结论: 'C 综合最优' } })
|
||||
ev('run.finished', null, {
|
||||
output: { 结论: 'C 供应商交期最短、来料稳定,建议提高份额。' },
|
||||
usage: { input_tokens: 4470, output_tokens: 946, cost_usd: 0.0322 },
|
||||
duration_ms: 12300, timing: { wall_ms: 12300, active_ms: 12300, wait_ms: 0 },
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐拍控制的长运行:一个循环节点带着两个节点跑 n 拍,每拍一段 Python,超时那拍
|
||||
* 失败后被 on_error=continue 接住;每 10 拍一条「接近上限」的警告。
|
||||
* 真实库里 87daca70 就是这个形状(1860 条事件、145 拍)。
|
||||
*/
|
||||
export function longLoop(n = 145): RunEvent[] {
|
||||
const { out, ev } = builder('syn-long')
|
||||
ev('run.started', null, { nodes: 4, resumed: false })
|
||||
ev('node.started', 'in', { node_type: 'input', label: '批次参数' })
|
||||
ev('node.finished', 'in', { duration_ms: 1, attempt: 1, preview: { batch: 'B-0926' } })
|
||||
for (let i = 1; i <= n; i += 1) {
|
||||
ev('node.started', 'tick', { node_type: 'loop', label: '逐拍循环', iteration: i })
|
||||
ev('edge.taken', 'tick', { branch: 'body', iteration: i - 1, total: n, mode: 'while' })
|
||||
ev('node.finished', 'tick', { duration_ms: 1, attempt: 1, preview: { __decision__: 'body' } })
|
||||
ev('node.started', 'poll', { node_type: 'code', label: '读取传感器', iteration: i })
|
||||
ev('sandbox.start', 'poll', { language: 'python' })
|
||||
const ms = i === 37 ? 63 : 9 + ((i * 7) % 6)
|
||||
ev('sandbox.end', 'poll', { ok: true, exit_code: 0, duration_ms: ms, stdout: `tick ${i}: 42.${i % 10}℃` }, ms / 1000)
|
||||
ev('node.finished', 'poll', { duration_ms: ms + 2, attempt: 1, preview: { temp: 42 + (i % 10) / 10 } })
|
||||
if (i % 10 === 0) ev('log', 'poll', { level: 'warn', code: 'loop_limit', message: '循环接近上限,还剩 10 拍' })
|
||||
}
|
||||
ev('node.started', 'tick', { node_type: 'loop', label: '逐拍循环', iteration: n + 1 })
|
||||
ev('edge.taken', 'tick', { branch: 'done', iteration: n, total: n, mode: 'while' })
|
||||
ev('node.finished', 'tick', { duration_ms: 1, attempt: 1, preview: { __decision__: 'done' } })
|
||||
ev('node.started', 'out', { node_type: 'output', label: '成果' })
|
||||
ev('node.finished', 'out', { duration_ms: 1, attempt: 1, preview: { 结果: `${n} 拍全部完成` } })
|
||||
ev('run.finished', null, { output: { 结果: `${n} 拍全部完成,最高 42.9℃` }, duration_ms: 5100, usage: {},
|
||||
timing: { wall_ms: 5100, active_ms: 5100, wait_ms: 0 } })
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 一条什么都有一点的运行:skip_if 跳过的节点、带思考的 agent(模型调用、按表名
|
||||
* 汇总的查询、一次看十几张表的结构)、带原始异常的工具报错、签了名的审批、
|
||||
* 只有 gaps 的降档出具,最后以某个节点失败收场。
|
||||
*/
|
||||
export function mixedRun(): RunEvent[] {
|
||||
const { out, ev } = builder('syn-mixed')
|
||||
ev('run.started', null, { nodes: 6, resumed: false })
|
||||
ev('node.started', 'in', { node_type: 'input', label: '统计区间' })
|
||||
ev('node.finished', 'in', { duration_ms: 2, attempt: 1, preview: { day: '2026-09-19' } })
|
||||
ev('node.skipped', 'kb', { reason: 'skip_if 成立:{{ inputs.day }} 是单日,不需要背景检索', node_type: 'retrieve', label: '背景检索' })
|
||||
ev('node.started', 'agent', { node_type: 'agent', label: '出勤分析' })
|
||||
ev('llm.start', 'agent', { model: 'claude-sonnet-4', message_count: 2 })
|
||||
ev('llm.thinking', 'agent', { text: '先看一下考勤相关的表有哪些,再按班次汇总出勤率。' }, 1.2)
|
||||
ev('llm.end', 'agent', { agent: '出勤分析', model: 'claude-sonnet-4', duration_ms: 1400, input_tokens: 1200, output_tokens: 180, total_tokens: 1380, cost_usd: 0.0063, calls: 1 }, 0.2)
|
||||
ev('tool.start', 'agent', { tool: 'db_schema__warehouse', call_id: 's1', args: { table: 'hr_attendance,hr_shift,hr_employee,hr_department,hr_leave,hr_overtime,hr_holiday,hr_roster,hr_badge_log,hr_position,hr_contract,hr_site' } })
|
||||
ev('tool.end', 'agent', { tool: 'db_schema__warehouse', call_id: 's1', duration_ms: 210, preview: '12 张表的字段…' }, 0.21)
|
||||
ev('llm.start', 'agent', { model: 'claude-sonnet-4', message_count: 4 })
|
||||
ev('llm.end', 'agent', { agent: '出勤分析', model: 'claude-sonnet-4', duration_ms: 900, input_tokens: 2100, output_tokens: 120, total_tokens: 2220, cost_usd: 0.008, calls: 1 }, 0.9)
|
||||
ev('tool.start', 'agent', { tool: 'db_query__warehouse', call_id: 'q1', args: { sql: 'SELECT s.shift_name, COUNT(*) AS n, AVG(a.present) AS rate\nFROM v_device_kpi a JOIN hr_shift s ON a.shift_id = s.id\nWHERE a.day = \'2026-09-19\'\nGROUP BY s.shift_name\nORDER BY rate DESC' } })
|
||||
ev('tool.end', 'agent', { tool: 'db_query__warehouse', call_id: 'q1', duration_ms: 9500, preview: '{"columns":["shift_name","n","rate"],"rows":[["早班",52,0.9423],["晚班",26,0.7308]],"row_count":2}', artifact: '4790dbfc11aa22bb33cc44dd55ee66ff77889900aabbccddeeff001122334455' }, 9.5)
|
||||
ev('tool.start', 'agent', { tool: 'db_query__warehouse', call_id: 'q2', args: { sql: 'SELECT * FROM hr_overtime_detail WHERE day = \'2026-09-19\'' } })
|
||||
ev('tool.error', 'agent', { tool: 'db_query__warehouse', call_id: 'q2', error: '查询超时:数据库 90 秒没有返回', detail: 'sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (3024, \'Query execution was interrupted, maximum statement execution time exceeded\')' }, 90.6)
|
||||
ev('node.finished', 'agent', { duration_ms: 103000, attempt: 1, preview: { text: '早班出勤率 94.23%,晚班 73.08%。' } })
|
||||
ev('node.started', 'review', { node_type: 'human', label: '班长复核' })
|
||||
ev('human.requested', 'review', { kind: 'human_node', node_id: 'review', mode: 'approve', title: '出勤结论可以发出吗?', message: '早班 94.23%,晚班 73.08%' })
|
||||
ev('run.interrupted', 'review', { payload: { kind: 'human_node', node_id: 'review', mode: 'approve', title: '出勤结论可以发出吗?' } })
|
||||
ev('run.resumed', null, { response: { approved: true, note: '晚班偏低要跟进' }, actor: '张工' }, 180)
|
||||
ev('run.started', null, { nodes: 6, resumed: true })
|
||||
ev('node.started', 'review', { node_type: 'human', label: '班长复核', resumed: true })
|
||||
ev('human.requested', 'review', { kind: 'human_node', node_id: 'review', mode: 'approve', title: '出勤结论可以发出吗?' })
|
||||
ev('human.resolved', 'review', { response: { approved: true, note: '晚班偏低要跟进' }, actor: '张工' })
|
||||
ev('node.finished', 'review', { duration_ms: 0, attempt: 1, preview: { approved: true } })
|
||||
ev('node.started', 'report', { node_type: 'output', label: '日报出具' })
|
||||
ev('issuance', 'report', { tier: 'degraded', missing_required: [], missing_expected: [], unmatched: 0, calibers: [{ node: 'kpi', caliber: '出勤率口径', version: 'v3' }], gaps: ['叙述模板渲染为空(路径可能写错了)'], metrics_checked: 2, matched_numbers: 0 })
|
||||
ev('node.finished', 'report', { duration_ms: 3, attempt: 1, preview: {} })
|
||||
ev('node.started', 'notify', { node_type: 'tool', label: '推送企业微信' })
|
||||
ev('node.failed', 'notify', { error: '推送失败:企业微信机器人地址没配', duration_ms: 120, detail: 'httpx.ConnectError: [Errno 8] nodename nor servname provided, or not known' })
|
||||
ev('run.failed', null, { error: '推送失败:企业微信机器人地址没配', node_id: 'notify', label: '推送企业微信', detail: 'httpx.ConnectError: [Errno 8] nodename nor servname provided, or not known', timing: { wall_ms: 290000, active_ms: 110000, wait_ms: 180000 } })
|
||||
return out
|
||||
}
|
||||
|
||||
/** mixedRun 的出具成果:只有 gaps 的降档,外加一个无法回指的数字 */
|
||||
export const MIXED_OUTPUT = {
|
||||
answer: '9 月 19 日早班出勤率 **94.23%**,晚班 **73.08%**,晚班比上周低 6 个百分点。',
|
||||
_issuance: {
|
||||
tier: 'degraded',
|
||||
calibers: [{ node: 'kpi', caliber: '出勤率口径', version: 'v3' }],
|
||||
metrics_checked: 2,
|
||||
missing_required: [],
|
||||
missing_expected: [],
|
||||
unmatched_numbers: [{ token: '6', context: '晚班比上周低 6 个百分点' }],
|
||||
matched_numbers: 2,
|
||||
gaps: ['叙述模板渲染为空(路径可能写错了)'],
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* 一条一条往下走的取数流水线:n 个不同的节点,各查一张表。不折叠、不合并,
|
||||
* 行数随事件线性增长——用来验"只在贴底时跟随"
|
||||
*/
|
||||
export function pipelineRun(n = 30): RunEvent[] {
|
||||
const { out, ev } = builder('syn-pipe')
|
||||
ev('run.started', null, { nodes: n, resumed: false })
|
||||
for (let i = 1; i <= n; i += 1) {
|
||||
const id = `p${i}`
|
||||
ev('node.started', id, { node_type: 'tool', label: `第 ${i} 张报表` })
|
||||
ev('tool.start', id, { tool: 'db_query__warehouse', call_id: `c${i}`, args: { sql: `SELECT line, SUM(qty) FROM report_${i} GROUP BY line` } })
|
||||
ev('tool.end', id, { tool: 'db_query__warehouse', call_id: `c${i}`, duration_ms: 120 + i * 7, preview: `{"columns":["line","qty"],"rows":[["L1",${i}]],"row_count":1}` }, 0.12)
|
||||
ev('node.finished', id, { duration_ms: 130 + i * 7, attempt: 1, preview: { rows: 1 } })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 取消在半路的运行:节点下面的查询还没回来 */
|
||||
export function cancelledRun(): RunEvent[] {
|
||||
const { out, ev } = builder('syn-cancel')
|
||||
ev('run.started', null, { nodes: 3, resumed: false })
|
||||
ev('node.started', 'q', { node_type: 'tool', label: '全量取数' })
|
||||
ev('tool.start', 'q', { tool: 'db_query__warehouse', args: { sql: 'SELECT * FROM big_table' } })
|
||||
ev('run.cancelled', null, { timing: { wall_ms: 4200, active_ms: 4200, wait_ms: 0 } }, 4.2)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Copilot 操作流:思考被心跳打断、自查修一轮没修好、模型写了不存在的节点类型 */
|
||||
export const COPILOT_STUCK = [
|
||||
{ op: 'heartbeat', phase: 'planning', elapsed_ms: 3000 },
|
||||
{ op: 'thinking', delta: '先看一下有哪些表。' },
|
||||
{ op: 'heartbeat', phase: 'planning', elapsed_ms: 6000 },
|
||||
{ op: 'thinking', delta: '然后按班次聚合。' },
|
||||
{ op: 'heartbeat', phase: 'planning', elapsed_ms: 9000 },
|
||||
{ op: 'thinking', delta: '最后出一份日报。' },
|
||||
{ op: 'plan', summary: '取数 → 汇总 → 出具' },
|
||||
{ op: 'add_node', node: { id: 'q', type: 'tool', label: '取数' } },
|
||||
{ op: 'add_node', node: { id: 'lp', type: 'loop', label: '逐日循环' } },
|
||||
{ op: 'done', explanation: '三步走' },
|
||||
{ op: 'check', status: 'repairing', round: 1, issues: ['「lp」循环条件写错了:表达式里没有 | 过滤器'] },
|
||||
{ op: 'heartbeat', phase: 'repairing', elapsed_ms: 12000 },
|
||||
{ op: 'update_node', id: 'lp' },
|
||||
{ op: 'check', status: 'failed', issues: ['「lp」循环条件写错了:表达式里没有 | 过滤器', '「q」没有选数据源'] },
|
||||
{ op: 'final', graph: { nodes: [{ id: 'q' }, { id: 'lp' }] }, issues: [
|
||||
{ level: 'error', node_id: 'lp', message: '循环条件写错了' },
|
||||
{ level: 'warning', node_id: null, code: 'unknown_node_type', type: 'excel_export', message: '模型写了一个不存在的节点类型「excel_export」,这一步已跳过' },
|
||||
] },
|
||||
]
|
||||
+1020
-162
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,329 @@
|
||||
import type { NodeState, NodeTrace, Trace } from './trace'
|
||||
|
||||
/**
|
||||
* 图结构上的推导:拓扑序、哪些边真的走过、哪些节点在排队 / 被阻断 / 没走到。
|
||||
*
|
||||
* 和 trace.ts 分开:航迹只认事件,这里只认图。"没亮的那几个节点"光看事件分不
|
||||
* 出是还没轮到、被分支绕开了,还是因为上游失败被堵住了——它们都只是"没有事件"。
|
||||
* 三种情况要做的事完全不同,所以得对照图推出来。
|
||||
*
|
||||
* 规则跟后端编译器对齐(compiler.py):
|
||||
* - 回边从入口起 DFS 认,和 back_edges 一致。循环体连回循环节点的那条不算依赖。
|
||||
* - 路由节点(分支、循环、带通过/驳回出口的人工审批)只放行它选中的那个出口;
|
||||
* 选中的出口没连线时走 default。其余节点的出边全部放行。
|
||||
* - 有两个以上上游的节点是 defer 汇合:等其余任务都跑完再跑一次,没走的那路不等。
|
||||
*/
|
||||
|
||||
export interface GraphLike {
|
||||
nodes: { id: string; type?: string; data?: { nodeType?: string; config?: Record<string, any> } }[]
|
||||
edges: { id?: string; source: string; target: string; sourceHandle?: string | null }[]
|
||||
}
|
||||
|
||||
type GraphEdgeLike = GraphLike['edges'][number]
|
||||
|
||||
export interface Topology {
|
||||
/** 去掉回边后的拓扑序 */
|
||||
order: string[]
|
||||
/** 拓扑层级:入口是 0,往下每层 +1(取最长路径)。一次性时刻按它错开 */
|
||||
rank: Record<string, number>
|
||||
/** 回边的 edgeKey */
|
||||
back: Set<string>
|
||||
entries: string[]
|
||||
}
|
||||
|
||||
export const edgeKey = (e: GraphEdgeLike): string =>
|
||||
`${e.source}|${e.target}|${e.sourceHandle ?? ''}`
|
||||
|
||||
/** 画布上的边都有 id;GraphSpec 里的边可能没有,退到 edgeKey */
|
||||
export const edgeIdOf = (e: GraphEdgeLike): string => e.id ?? edgeKey(e)
|
||||
|
||||
/**
|
||||
* 节点类型。画布上的 FlowNode 的 type 是 React Flow 的渲染器键(一律 'card'),
|
||||
* 真正的类型在 data.nodeType;GraphSpec 的节点没有 data.nodeType,type 就是类型
|
||||
*/
|
||||
const typeOf = (n: GraphLike['nodes'][number]): string | undefined => n.data?.nodeType ?? n.type
|
||||
|
||||
const topoCache = new WeakMap<object, { nodes: object; topo: Topology }>()
|
||||
|
||||
/**
|
||||
* 拓扑序与回边。
|
||||
*
|
||||
* 缓存按边数组的引用:运行期间图不变,每条事件都重算一遍没有必要;
|
||||
* 改图会换数组,缓存自然失效。
|
||||
*/
|
||||
export function topology(graph: GraphLike): Topology {
|
||||
const hit = topoCache.get(graph.edges)
|
||||
if (hit && hit.nodes === graph.nodes) return hit.topo
|
||||
|
||||
const ids = graph.nodes.map((n) => n.id)
|
||||
const known = new Set(ids)
|
||||
const edges = graph.edges.filter((e) => known.has(e.source) && known.has(e.target))
|
||||
const hasIncoming = new Set(edges.map((e) => e.target))
|
||||
const inputs = graph.nodes.filter((n) => typeOf(n) === 'input').map((n) => n.id)
|
||||
const entries = inputs.length ? inputs : ids.filter((id) => !hasIncoming.has(id))
|
||||
|
||||
const adj = new Map<string, GraphEdgeLike[]>()
|
||||
for (const e of edges) {
|
||||
const list = adj.get(e.source)
|
||||
if (list) list.push(e)
|
||||
else adj.set(e.source, [e])
|
||||
}
|
||||
|
||||
// 迭代式 DFS(和后端 back_edges 同一个算法):几百个节点的图不该因为递归深度出事
|
||||
const WHITE = 0, GREY = 1, BLACK = 2
|
||||
const color = new Map(ids.map((id) => [id, WHITE]))
|
||||
const back = new Set<string>()
|
||||
for (const root of [...entries, ...ids]) {
|
||||
if (color.get(root) !== WHITE) continue
|
||||
const stack: [string, number][] = [[root, 0]]
|
||||
color.set(root, GREY)
|
||||
while (stack.length) {
|
||||
const top = stack[stack.length - 1]
|
||||
const out = adj.get(top[0]) ?? []
|
||||
if (top[1] >= out.length) {
|
||||
color.set(top[0], BLACK)
|
||||
stack.pop()
|
||||
continue
|
||||
}
|
||||
const e = out[top[1]]
|
||||
top[1] += 1
|
||||
const c = color.get(e.target)
|
||||
if (c === GREY) back.add(edgeKey(e))
|
||||
else if (c === WHITE) {
|
||||
color.set(e.target, GREY)
|
||||
stack.push([e.target, 0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const indeg = new Map(ids.map((id) => [id, 0]))
|
||||
for (const e of edges) if (!back.has(edgeKey(e))) indeg.set(e.target, (indeg.get(e.target) ?? 0) + 1)
|
||||
const rank: Record<string, number> = {}
|
||||
const queue = ids.filter((id) => !indeg.get(id))
|
||||
queue.forEach((id) => { rank[id] = 0 })
|
||||
const order: string[] = []
|
||||
while (queue.length) {
|
||||
const id = queue.shift()!
|
||||
order.push(id)
|
||||
for (const e of adj.get(id) ?? []) {
|
||||
if (back.has(edgeKey(e))) continue
|
||||
rank[e.target] = Math.max(rank[e.target] ?? 0, rank[id] + 1)
|
||||
const left = (indeg.get(e.target) ?? 0) - 1
|
||||
indeg.set(e.target, left)
|
||||
if (left === 0) queue.push(e.target)
|
||||
}
|
||||
}
|
||||
// 去掉回边后必然无环;万一有漏网的,按原顺序补在后面,不丢节点
|
||||
for (const id of ids) if (!order.includes(id)) { order.push(id); rank[id] ??= 0 }
|
||||
|
||||
const topo = { order, rank, back, entries }
|
||||
topoCache.set(graph.edges, { nodes: graph.nodes, topo })
|
||||
return topo
|
||||
}
|
||||
|
||||
const continueOnError = (n: GraphLike['nodes'][number] | undefined): boolean =>
|
||||
n?.data?.config?.on_error === 'continue'
|
||||
|
||||
/**
|
||||
* 这个节点是不是按出口路由的。和 compiler.py 的 needs_routing 一致:分支、循环,
|
||||
* 以及出口里有通过/驳回的人工审批。图里没带类型时,看它做过的决定能不能对上
|
||||
* 某个出口。
|
||||
*/
|
||||
function isRouting(node: GraphLike['nodes'][number] | undefined, outHandles: Set<string>,
|
||||
n: NodeTrace | undefined): boolean {
|
||||
const type = node ? typeOf(node) : undefined
|
||||
if (type === 'branch' || type === 'loop') return true
|
||||
if (type === 'human') return outHandles.has('approved') || outHandles.has('rejected')
|
||||
if (type) return false
|
||||
const decision = n?.takenHandle
|
||||
return decision != null && (outHandles.has(decision) || outHandles.has('default'))
|
||||
}
|
||||
|
||||
interface Ctx {
|
||||
byId: Map<string, GraphLike['nodes'][number]>
|
||||
out: Map<string, GraphEdgeLike[]>
|
||||
handles: Map<string, Set<string>>
|
||||
}
|
||||
|
||||
const ctxCache = new WeakMap<object, { nodes: object; ctx: Ctx }>()
|
||||
|
||||
function contextOf(graph: GraphLike): Ctx {
|
||||
const hit = ctxCache.get(graph.edges)
|
||||
if (hit && hit.nodes === graph.nodes) return hit.ctx
|
||||
const byId = new Map(graph.nodes.map((n) => [n.id, n]))
|
||||
const out = new Map<string, GraphEdgeLike[]>()
|
||||
const handles = new Map<string, Set<string>>()
|
||||
for (const e of graph.edges) {
|
||||
const list = out.get(e.source)
|
||||
if (list) list.push(e)
|
||||
else out.set(e.source, [e])
|
||||
const set = handles.get(e.source) ?? new Set<string>()
|
||||
set.add(e.sourceHandle || 'default')
|
||||
handles.set(e.source, set)
|
||||
}
|
||||
const ctx = { byId, out, handles }
|
||||
ctxCache.set(graph.edges, { nodes: graph.nodes, ctx })
|
||||
return ctx
|
||||
}
|
||||
|
||||
/** 出口 handle 是否放行:decision 是节点做的某一次决定(undefined = 没做决定) */
|
||||
function handleOpen(e: GraphEdgeLike, routing: boolean, decision: string | undefined,
|
||||
outHandles: Set<string>): boolean {
|
||||
if (!routing) return true
|
||||
const h = e.sourceHandle || 'default'
|
||||
// 路由节点没做出决定(被 skip_if 跳过):路由函数拿到 None,只走 default
|
||||
if (decision == null) return h === 'default'
|
||||
if (h === decision) return true
|
||||
return h === 'default' && !outHandles.has(decision)
|
||||
}
|
||||
|
||||
/** 源节点已经把数据送出来了:跑完、被跳过、容错失败,或者循环容器正放行 body */
|
||||
function sourcePassed(n: NodeTrace | undefined, node: GraphLike['nodes'][number] | undefined): boolean {
|
||||
if (!n) return false
|
||||
if (n.looping) return true
|
||||
return n.state === 'done' || n.state === 'skipped'
|
||||
|| (n.state === 'failed' && continueOnError(node))
|
||||
}
|
||||
|
||||
/** 这条边此刻是否"已送达":源已放行,且(路由节点的话)当前的决定选的就是它 */
|
||||
export function edgeFired(trace: Trace, graph: GraphLike, e: GraphEdgeLike): boolean {
|
||||
const ctx = contextOf(graph)
|
||||
const src = trace.nodes[e.source]
|
||||
const node = ctx.byId.get(e.source)
|
||||
if (!sourcePassed(src, node)) return false
|
||||
const hs = ctx.handles.get(e.source) ?? new Set<string>()
|
||||
return handleOpen(e, isRouting(node, hs, src), src?.takenHandle, hs)
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前正在流动的边:目标此刻真的在执行、这条边确实送达了。
|
||||
*
|
||||
* 只算执行中的目标——指向等待审批节点的边不算:流程是停住的,边上还有光点
|
||||
* 往里流,看着像"数据在流",和事实相反。循环容器在两轮之间也不算。
|
||||
*/
|
||||
export function activeEdgesOf(trace: Trace, graph: GraphLike): string[] {
|
||||
const out: string[] = []
|
||||
for (const e of graph.edges) {
|
||||
const target = trace.nodes[e.target]
|
||||
if (!target || target.state !== 'running' || target.looping) continue
|
||||
if (edgeFired(trace, graph, e)) out.push(edgeIdOf(e))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 停住的边:目标正停在审批上、这条边确实送达了。画布把它画成静止的闸门,
|
||||
* 和"正在流动"分开——流程在等人,不是在跑。
|
||||
*/
|
||||
export function heldEdgesOf(trace: Trace, graph: GraphLike): string[] {
|
||||
const out: string[] = []
|
||||
for (const e of graph.edges) {
|
||||
if (trace.nodes[e.target]?.state !== 'waiting') continue
|
||||
if (edgeFired(trace, graph, e)) out.push(edgeIdOf(e))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const STARTED = new Set<NodeState>(['running', 'waiting', 'done', 'failed', 'skipped', 'cancelled', 'suspended'])
|
||||
|
||||
/**
|
||||
* 这次运行实际走过的边:源放行过这条出口(循环里任何一轮都算),目标也确实开跑过。
|
||||
* 跑完之后用它留下执行路径,而不是只点亮分支出口那一条。
|
||||
*/
|
||||
export function walkedEdges(trace: Trace, graph: GraphLike): Set<string> {
|
||||
const ctx = contextOf(graph)
|
||||
const walked = new Set<string>()
|
||||
for (const e of graph.edges) {
|
||||
const src = trace.nodes[e.source]
|
||||
const dst = trace.nodes[e.target]
|
||||
if (!src?.count && src?.state !== 'skipped') continue
|
||||
if (!dst || !(dst.count > 0 || STARTED.has(dst.state))) continue
|
||||
const hs = ctx.handles.get(e.source) ?? new Set<string>()
|
||||
const node = ctx.byId.get(e.source)
|
||||
const routing = isRouting(node, hs, src)
|
||||
const decisions = src.taken?.length ? src.taken : [undefined]
|
||||
if (decisions.some((dec) => handleOpen(e, routing, dec, hs))) walked.add(edgeIdOf(e))
|
||||
}
|
||||
return walked
|
||||
}
|
||||
|
||||
const PENDING = new Set<NodeState>(['idle', 'queued', 'blocked', 'unreached'])
|
||||
|
||||
/**
|
||||
* 推导每个节点的状态,覆盖图上的全部节点(没有事件的也在)。
|
||||
*
|
||||
* - 终态(成功 / 失败 / 取消):没跑过的节点,在某个失败节点下游的是 blocked
|
||||
* (on_error=continue 的失败不往下传),其余是 unreached(分支落空、运行被
|
||||
* 停在半路)。
|
||||
* - 进行中:没跑过、但至少有一条入边已送达的是 queued——单入边的是马上要跑,
|
||||
* 汇合节点是在等另一路(defer:等其余任务跑完再跑一次)。
|
||||
* - 挂起 / 空闲:不推导。挂起的运行还能接着跑,这时候说"没走到"为时过早。
|
||||
*/
|
||||
export function deriveStates(trace: Trace, graph: GraphLike): Record<string, NodeState> {
|
||||
const ctx = contextOf(graph)
|
||||
const states: Record<string, NodeState> = {}
|
||||
for (const n of graph.nodes) states[n.id] = trace.nodes[n.id]?.state ?? 'idle'
|
||||
const phase = trace.phase
|
||||
|
||||
if (phase === 'succeeded' || phase === 'failed' || phase === 'cancelled') {
|
||||
const blocked = new Set<string>()
|
||||
const seeds = graph.nodes.filter((n) =>
|
||||
trace.nodes[n.id]?.state === 'failed' && !continueOnError(n)).map((n) => n.id)
|
||||
// 顺着出边一路往下(含回边:循环体里失败了,循环的 done 出口之后也走不到了)。
|
||||
// 跑过的节点保持原样,只标没跑过的
|
||||
const queue = [...seeds]
|
||||
const seen = new Set(queue)
|
||||
while (queue.length) {
|
||||
const id = queue.shift()!
|
||||
for (const e of ctx.out.get(id) ?? []) {
|
||||
if (seen.has(e.target) || !(e.target in states)) continue
|
||||
seen.add(e.target)
|
||||
if (PENDING.has(states[e.target])) blocked.add(e.target)
|
||||
queue.push(e.target)
|
||||
}
|
||||
}
|
||||
for (const id of Object.keys(states)) {
|
||||
if (PENDING.has(states[id])) states[id] = blocked.has(id) ? 'blocked' : 'unreached'
|
||||
}
|
||||
return states
|
||||
}
|
||||
|
||||
if (phase === 'queued' || phase === 'running' || phase === 'waiting') {
|
||||
const incoming = new Map<string, GraphEdgeLike[]>()
|
||||
for (const e of graph.edges) {
|
||||
const list = incoming.get(e.target)
|
||||
if (list) list.push(e)
|
||||
else incoming.set(e.target, [e])
|
||||
}
|
||||
for (const id of Object.keys(states)) {
|
||||
if (states[id] !== 'idle' && states[id] !== 'queued') continue
|
||||
const fired = (incoming.get(id) ?? []).some((e) => edgeFired(trace, graph, e))
|
||||
states[id] = fired ? 'queued' : 'idle'
|
||||
}
|
||||
return states
|
||||
}
|
||||
|
||||
for (const id of Object.keys(states)) if (states[id] === 'queued') states[id] = 'idle'
|
||||
return states
|
||||
}
|
||||
|
||||
/**
|
||||
* 把推导结果写回航迹。只动推导类状态(idle / queued / blocked / unreached)
|
||||
* 之间的切换,事件给出的状态原样不动;没有变化时返回同一个引用。
|
||||
*/
|
||||
export function applyDerived(trace: Trace, graph: GraphLike): Trace {
|
||||
const states = deriveStates(trace, graph)
|
||||
let nodes: Record<string, NodeTrace> | null = null
|
||||
for (const [id, state] of Object.entries(states)) {
|
||||
const cur = trace.nodes[id]
|
||||
const before = cur?.state ?? 'idle'
|
||||
if (before === state || !PENDING.has(before) || !PENDING.has(state)) continue
|
||||
if (!cur && state === 'idle') continue
|
||||
nodes ??= { ...trace.nodes }
|
||||
nodes[id] = cur
|
||||
? { ...cur, state }
|
||||
: { id, state, count: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, tools: 0, toolsRunning: 0,
|
||||
segments: [] }
|
||||
}
|
||||
return nodes ? { ...trace, nodes } : trace
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
import type { RunEvent, RunStatus } from '../types'
|
||||
import { endingOf, nextPhase, type Ending } from './decode'
|
||||
import { applyDerived, type GraphLike } from './derive'
|
||||
|
||||
/**
|
||||
* 运行航迹:事件 → 航迹 → 投影(t)。
|
||||
*
|
||||
* 画布卡片、运行胶囊、时间轴、右栏高亮、运行记录页都读这一份,不再各自解读
|
||||
* 事件。以前 studio 的 applyEvent 是覆盖式快照:durationMs、iteration 被下一轮
|
||||
* 覆盖,没有任何按时间索引的视图,于是"哪几个同时在跑、等了多久、时间花在
|
||||
* 哪"说不出来;终态也没人收尾,取消之后节点永远在转圈。
|
||||
*
|
||||
* 和 decode.ts 并列:decode 管"事件 → 人话",这里只管时间和状态。收尾规则
|
||||
* (终态时进行中的东西收成什么)两边共用 decode 里的 endingOf / nextPhase,
|
||||
* 同一次运行在画布和右栏不会讲出两种结局。
|
||||
*
|
||||
* 纯函数,不依赖 React 和 store:回放就是把同一份航迹投影到另一个时刻。
|
||||
* 时间一律是毫秒时间戳(事件的 ts 是秒)。
|
||||
*/
|
||||
|
||||
export type RunPhase =
|
||||
| 'idle' | 'queued' | 'running' | 'waiting' | 'succeeded' | 'failed' | 'cancelled' | 'suspended'
|
||||
|
||||
export type NodeState =
|
||||
| 'idle' | 'queued' | 'running' | 'waiting' | 'done' | 'failed' | 'skipped'
|
||||
| 'cancelled' | 'suspended' | 'blocked' | 'unreached'
|
||||
|
||||
export interface Segment {
|
||||
start: number
|
||||
/** null = 还开着 */
|
||||
end: number | null
|
||||
kind: 'run' | 'wait' | 'retry' | 'dispatch' | 'member'
|
||||
/** 开着时是 running / waiting;闭合后是这一段的结局 */
|
||||
status: NodeState
|
||||
/** 循环第几轮(从 1 数);成员段、调度段是协作的第几轮 */
|
||||
iteration?: number
|
||||
agent?: string
|
||||
/** 由事件间隙推算的(调度者在想的那段),不是测量值 */
|
||||
estimated?: boolean
|
||||
/** 这一段走的出口:分支命中的 case、循环的 body / done */
|
||||
handle?: string
|
||||
/** 审批恢复后接回的那一段。和中断前是同一次执行,不另算次数 */
|
||||
resumed?: boolean
|
||||
}
|
||||
|
||||
export interface NodeTrace {
|
||||
id: string
|
||||
state: NodeState
|
||||
/** 执行了几次(循环、重试后接着跑都会让它 > 1;审批恢复的重放不算) */
|
||||
count: number
|
||||
/** 循环节点:第几轮(从 1 数)。走 done 出口时不再变 */
|
||||
iteration?: number
|
||||
/** 循环节点:foreach 的总项数(edge.taken.total)。while 没有总数 */
|
||||
iterTotal?: number
|
||||
attempt?: number
|
||||
startedAt?: number
|
||||
endedAt?: number
|
||||
lastDurationMs?: number
|
||||
tokensIn: number
|
||||
tokensOut: number
|
||||
costUsd: number
|
||||
tools: number
|
||||
toolsRunning: number
|
||||
error?: string
|
||||
skippedReason?: string
|
||||
model?: string
|
||||
segments: Segment[]
|
||||
/** 循环节点一轮跑完、出口是 body:容器还在进行中,不是完成 */
|
||||
looping?: boolean
|
||||
/** 循环节点走了 done 出口 */
|
||||
loopDone?: boolean
|
||||
/** 最近一次走的出口;taken 是走过的全部出口(循环里会有好几个) */
|
||||
takenHandle?: string
|
||||
taken?: string[]
|
||||
/** 分支命中的理由 */
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface Trace {
|
||||
phase: RunPhase
|
||||
startedAt?: number
|
||||
/** 终态或挂起的时刻。续跑、恢复后清掉 */
|
||||
endedAt?: number
|
||||
/** 已结束的等人时长之和;正在等的那段看 waitingSince */
|
||||
waitMs: number
|
||||
waitingSince?: number
|
||||
nodes: Record<string, NodeTrace>
|
||||
tokensIn: number
|
||||
tokensOut: number
|
||||
costUsd: number
|
||||
failedNodeId?: string
|
||||
waitingNodeId?: string
|
||||
issuance?: {
|
||||
tier: string
|
||||
missing?: string[]
|
||||
unmatched?: string[]
|
||||
/** 必需指标缺了哪些(missing 里包含必需和期望两类) */
|
||||
missingRequired?: string[]
|
||||
/** 后端只给了数量时在这里 */
|
||||
unmatchedCount?: number
|
||||
}
|
||||
runClass?: 'formal' | 'exploratory'
|
||||
lastSeq: number
|
||||
/** [时刻, 此刻同时在跑的数量],只在数量变化时记一条 */
|
||||
parallelSeries: [number, number][]
|
||||
|
||||
/** false = 老数据没有 ts:段按顺序排、宽度只来自 duration_ms,墙钟和等人时长不可知 */
|
||||
timed: boolean
|
||||
/** run.started.nodes:图上一共几个节点 */
|
||||
nodesTotal?: number
|
||||
/** 每一段执行(run.started → 中断 / 终态)的起止。执行时长 = 各段之和 */
|
||||
drives: [number, number | null][]
|
||||
/** 每一段等人(run.interrupted → run.resumed)的起止 */
|
||||
waits: [number, number | null][]
|
||||
/** 相位变化记录,回放按它取某一刻的相位 */
|
||||
phases: [number, RunPhase][]
|
||||
/** 后端给的权威时长(终态事件的 timing)。有它就不用自己算的 */
|
||||
timing?: { wallMs: number; activeMs: number; waitMs: number }
|
||||
/** 最后一条事件是 WS 补发的历史(replay:true)。一次性时刻只由实时事件触发 */
|
||||
lastReplay: boolean
|
||||
/** 客户端时钟减服务端时钟(取实时事件里最小的那次),由 store 维护。见 liveAt */
|
||||
skewMs?: number
|
||||
/** 折叠用的簿记。消费方不要读 */
|
||||
book: TraceBook
|
||||
}
|
||||
|
||||
interface TraceBook {
|
||||
/** 最后一条事件的时刻。没有 ts 的老数据拿它当虚拟时钟往前推 */
|
||||
clock: number
|
||||
/** 有没有停在审批上(和 decodePhase 用同一个 nextPhase 推) */
|
||||
awaiting: boolean
|
||||
/** 最近一次失败、之后没有新节点开跑的节点:run.failed 时它就是失败的那个 */
|
||||
lastFailed?: string
|
||||
/** 最近一次循环 body 的轮次,给循环体节点的段标号 */
|
||||
loopIter?: number
|
||||
/** supervisor 节点:推算调度段的起点(节点开始或上一个成员交回的时刻) */
|
||||
dispatchFrom: Record<string, number>
|
||||
/** 发过 agent.route.* 的节点:调度段有精确值,不再推算 */
|
||||
exactDispatch: Record<string, true>
|
||||
/**
|
||||
* 还开着的审批配对(和 decodeRun 的 openInterrupts 同一套规则):开着就是同一次
|
||||
* 中断,恢复后 LangGraph 重放的那条 human.requested 不算新的一次
|
||||
*/
|
||||
asking: Record<string, true>
|
||||
}
|
||||
|
||||
export interface Projection {
|
||||
phase: RunPhase
|
||||
/** 墙钟:从第一次开始到结束(或此刻) */
|
||||
elapsedMs: number
|
||||
/** 执行:各段执行时长之和 */
|
||||
activeMs: number
|
||||
/** 等人 */
|
||||
waitMs: number
|
||||
nodesDone: number
|
||||
nodesTotal: number
|
||||
parallelNow: number
|
||||
nodes: Record<string, { state: NodeState; elapsedMs?: number; count: number; iteration?: number }>
|
||||
}
|
||||
|
||||
// 流式增量:后端不落库,刷新后也不会回来。航迹不能建立在它们之上
|
||||
const EPHEMERAL = new Set(['llm.token', 'llm.thinking.delta'])
|
||||
const TERMINAL = new Set<RunPhase>(['succeeded', 'failed', 'cancelled'])
|
||||
|
||||
export const isTerminal = (phase: RunPhase): boolean => TERMINAL.has(phase)
|
||||
/** 终态或挂起:这次运行眼下不会再自己动了 */
|
||||
export const isSettled = (phase: RunPhase): boolean => TERMINAL.has(phase) || phase === 'suspended'
|
||||
export const isActivePhase = (phase: RunPhase): boolean =>
|
||||
phase === 'queued' || phase === 'running' || phase === 'waiting'
|
||||
|
||||
/** 这个节点此刻真的在执行(循环容器在两轮之间不算,它只是"还没完") */
|
||||
export const isExecuting = (n: NodeTrace | undefined): boolean =>
|
||||
!!n && n.state === 'running' && !n.looping
|
||||
|
||||
/**
|
||||
* 相位写回 run.status 用的值。
|
||||
*
|
||||
* waiting 对应后端的 interrupted;suspended 后端也写 interrupted,前端单独叫它,
|
||||
* 因为"停在审批上"和"服务重启后挂着"要做的事完全不同。idle 没有对应值。
|
||||
*/
|
||||
export function runStatusOf(phase: RunPhase): RunStatus | null {
|
||||
switch (phase) {
|
||||
case 'idle': return null
|
||||
case 'waiting': return 'interrupted'
|
||||
default: return phase
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时投影用的时刻。
|
||||
*
|
||||
* ts 是服务端时钟,now 是客户端时钟。两边差几秒时直接拿 now 去投影,刚开跑的
|
||||
* 节点会因为"还没到开始时刻"显示成没开始、计时器是负数。同机部署时偏差是 0。
|
||||
*/
|
||||
export const liveAt = (t: Trace, now: number): number => now - (t.skewMs ?? 0)
|
||||
|
||||
export function emptyTrace(): Trace {
|
||||
return {
|
||||
phase: 'idle', waitMs: 0, nodes: {}, tokensIn: 0, tokensOut: 0, costUsd: 0,
|
||||
lastSeq: 0, parallelSeries: [], timed: true, drives: [], waits: [], phases: [],
|
||||
lastReplay: false,
|
||||
book: { clock: 0, awaiting: false, dispatchFrom: {}, exactDispatch: {}, asking: {} },
|
||||
}
|
||||
}
|
||||
|
||||
function blankNode(id: string, state: NodeState = 'idle'): NodeTrace {
|
||||
return {
|
||||
id, state, count: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, tools: 0, toolsRunning: 0,
|
||||
segments: [],
|
||||
}
|
||||
}
|
||||
|
||||
const num = (v: unknown): number | undefined =>
|
||||
typeof v === 'number' && Number.isFinite(v) ? v : undefined
|
||||
|
||||
/** 最后一段还开着的某类段的下标 */
|
||||
function openIndex(segs: Segment[], kind: Segment['kind'], agent?: string): number {
|
||||
for (let i = segs.length - 1; i >= 0; i -= 1) {
|
||||
const s = segs[i]
|
||||
if (s.kind === kind && s.end == null && (agent == null || s.agent === agent)) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/**
|
||||
* 此刻同时在跑的数量。
|
||||
*
|
||||
* 有成员在跑的协作节点按成员数算,容器本身不计——三个人同时在干活,说"并行 4"
|
||||
* 就把调度者的空等也算成了干活。循环容器在两轮之间没有开着的段,自然不计。
|
||||
*/
|
||||
function parallelOf(nodes: Record<string, NodeTrace>): number {
|
||||
let total = 0
|
||||
for (const n of Object.values(nodes)) {
|
||||
let inner = 0
|
||||
let run = 0
|
||||
for (const s of n.segments) {
|
||||
if (s.end != null) continue
|
||||
if (s.kind === 'member' || s.kind === 'dispatch') inner += 1
|
||||
else if (s.kind === 'run') run = 1
|
||||
}
|
||||
total += inner || run
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* 写时复制的草稿:只复制这一次碰到的节点和簿记,其余沿用原引用。
|
||||
*
|
||||
* 不可变是必须的:画布那份挂在 zustand 上,原地改的话引用不变,React 收不到更新。
|
||||
*/
|
||||
interface Draft {
|
||||
next: Trace
|
||||
at: number
|
||||
node: (id: string) => NodeTrace
|
||||
book: () => TraceBook
|
||||
patchSeg: (n: NodeTrace, i: number, patch: Partial<Segment>) => void
|
||||
setPhase: (phase: RunPhase) => void
|
||||
}
|
||||
|
||||
function draftOf(t: Trace, at: number): Draft {
|
||||
const next: Trace = { ...t }
|
||||
let nodesCopied = false
|
||||
const touched = new Set<string>()
|
||||
let bookCopied = false
|
||||
const dr: Draft = {
|
||||
next,
|
||||
at,
|
||||
node: (id) => {
|
||||
if (!nodesCopied) { next.nodes = { ...next.nodes }; nodesCopied = true }
|
||||
if (!touched.has(id)) {
|
||||
const prev = next.nodes[id]
|
||||
next.nodes[id] = prev ? { ...prev, segments: [...prev.segments] } : blankNode(id)
|
||||
touched.add(id)
|
||||
}
|
||||
return next.nodes[id]
|
||||
},
|
||||
book: () => {
|
||||
if (!bookCopied) {
|
||||
next.book = {
|
||||
...next.book,
|
||||
dispatchFrom: { ...next.book.dispatchFrom },
|
||||
exactDispatch: { ...next.book.exactDispatch },
|
||||
asking: { ...next.book.asking },
|
||||
}
|
||||
bookCopied = true
|
||||
}
|
||||
return next.book
|
||||
},
|
||||
patchSeg: (n, i, patch) => { n.segments[i] = { ...n.segments[i], ...patch } },
|
||||
setPhase: (phase) => {
|
||||
if (next.phase === phase) return
|
||||
next.phase = phase
|
||||
next.phases = [...next.phases, [dr.at, phase]]
|
||||
},
|
||||
}
|
||||
return dr
|
||||
}
|
||||
|
||||
function closeDrive(dr: Draft): void {
|
||||
const { next } = dr
|
||||
const last = next.drives[next.drives.length - 1]
|
||||
if (last && last[1] == null) next.drives = [...next.drives.slice(0, -1), [last[0], dr.at]]
|
||||
}
|
||||
|
||||
function closeWait(dr: Draft): void {
|
||||
const { next } = dr
|
||||
const last = next.waits[next.waits.length - 1]
|
||||
if (last && last[1] == null) {
|
||||
next.waits = [...next.waits.slice(0, -1), [last[0], dr.at]]
|
||||
next.waitMs += Math.max(0, dr.at - last[0])
|
||||
}
|
||||
next.waitingSince = undefined
|
||||
next.waitingNodeId = undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 终态 / 挂起时的收尾:还挂着"进行中"的东西各自收成 ending 指定的样子。
|
||||
*
|
||||
* 协作成员、调度段、开着的等待段一起收——只收节点的话,画布上协作团队的
|
||||
* 光弧和"进行中"会一直在,入边的光点也还在流,而运行其实早就停了。
|
||||
*/
|
||||
function settle(dr: Draft, ending: Ending): void {
|
||||
const { next, at } = dr
|
||||
for (const [id, cur] of Object.entries(next.nodes)) {
|
||||
const running = cur.state === 'running'
|
||||
const waiting = cur.state === 'waiting'
|
||||
const holdWait = waiting && ending.waiting === 'waiting'
|
||||
const openSegs = cur.segments.some((s) => s.end == null && !(s.kind === 'wait' && holdWait))
|
||||
if (!running && !(waiting && !holdWait) && !openSegs && cur.state !== 'queued') continue
|
||||
const n = dr.node(id)
|
||||
n.segments.forEach((s, i) => {
|
||||
if (s.end != null || (s.kind === 'wait' && holdWait)) return
|
||||
dr.patchSeg(n, i, { end: at, status: s.kind === 'wait' ? ending.waiting : ending.running })
|
||||
})
|
||||
if (running) {
|
||||
n.state = ending.running
|
||||
n.looping = false
|
||||
n.toolsRunning = 0
|
||||
n.endedAt = at
|
||||
} else if (waiting) {
|
||||
n.state = ending.waiting
|
||||
} else if (n.state === 'queued') {
|
||||
n.state = 'idle'
|
||||
}
|
||||
}
|
||||
closeDrive(dr)
|
||||
if (ending.phase !== 'waiting') {
|
||||
closeWait(dr)
|
||||
next.endedAt = at
|
||||
// 不再有人等着答复:之后同一个节点再来的请求是新的一次
|
||||
if (Object.keys(next.book.asking).length) dr.book().asking = {}
|
||||
}
|
||||
dr.setPhase(ending.phase)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一条事件折进航迹,返回新的航迹;和这条事件无关时原样返回同一个引用。
|
||||
*
|
||||
* llm.token / llm.thinking.delta 一律原样返回:它们不落库,刷新后不会回来,
|
||||
* 航迹不能建立在它们之上;而且一次运行有几千条,每条都换引用会让订阅航迹的
|
||||
* 组件跟着逐字重渲染。
|
||||
*
|
||||
* type 为 stream.end 的是客户端合成的对账事件(WS 结束标记、GET /runs/{id}
|
||||
* 对出来的状态),data 为 {status, pending?}:漏了终态事件(断线、服务被强杀)
|
||||
* 时靠它收尾。
|
||||
*/
|
||||
export function foldEvent(t: Trace, ev: RunEvent): Trace {
|
||||
const type = String(ev.type)
|
||||
if (EPHEMERAL.has(type)) return t
|
||||
const seq = num(ev.seq) ?? 0
|
||||
// 断线重连、审批恢复后重接都可能把已经收过的再推一遍:同一条不折两遍
|
||||
if (seq > 0 && seq <= t.lastSeq) return t
|
||||
|
||||
const d: Record<string, any> = ev.data ?? {}
|
||||
const synthetic = type === 'stream.end'
|
||||
if (synthetic) {
|
||||
// 对账只在"它其实已经停了"时才有话说;还在跑、或者早已收过同一个结局,原样返回
|
||||
const ending = endingOf(ev, t.book.awaiting)
|
||||
if (!ending || (ending.phase === t.phase && isSettled(t.phase))) return t
|
||||
}
|
||||
const tsOk = num(ev.ts) != null
|
||||
const dr = draftOf(t, tsOk ? ev.ts * 1000 : t.book.clock)
|
||||
const { next, node, book, patchSeg, setPhase } = dr
|
||||
let at = dr.at
|
||||
if (seq > next.lastSeq) next.lastSeq = seq
|
||||
if (!synthetic) next.lastReplay = !!ev.replay
|
||||
if (!tsOk && !synthetic) next.timed = false
|
||||
|
||||
const openDrive = () => {
|
||||
const last = next.drives[next.drives.length - 1]
|
||||
if (!last || last[1] != null) next.drives = [...next.drives, [dr.at, null]]
|
||||
}
|
||||
/** 续跑、恢复之后:上一回合的失败、推出来的"被阻断 / 没走到"都不再成立 */
|
||||
const reopen = () => {
|
||||
next.endedAt = undefined
|
||||
next.timing = undefined
|
||||
// 留着的话,接着跑成功了还会有人报"失败于 X"
|
||||
next.failedNodeId = undefined
|
||||
if (next.book.lastFailed) book().lastFailed = undefined
|
||||
for (const [id, n] of Object.entries(next.nodes)) {
|
||||
if (n.state === 'blocked' || n.state === 'unreached') node(id).state = 'idle'
|
||||
}
|
||||
}
|
||||
|
||||
const prevPhase = t.phase
|
||||
const phaseStep = nextPhase({ phase: t.phase, awaiting: t.book.awaiting }, ev)
|
||||
if (phaseStep.awaiting !== t.book.awaiting) book().awaiting = phaseStep.awaiting
|
||||
const nodeId = ev.node_id ?? undefined
|
||||
|
||||
switch (type) {
|
||||
case 'run.started':
|
||||
case 'run.resumed': {
|
||||
if (type === 'run.resumed') {
|
||||
// 人已经答过了:等人的那段闭合,等待节点回到"在跑"。紧接着 LangGraph 会
|
||||
// 对它重发 node.started——那是同一次执行接着走,这里先把段接上,
|
||||
// 那条重放进来时看到开着的段就不会再算一次
|
||||
closeWait(dr)
|
||||
for (const [id, cur] of Object.entries(next.nodes)) {
|
||||
if (cur.state !== 'waiting') continue
|
||||
const n = node(id)
|
||||
n.segments.forEach((s, i) => {
|
||||
if (s.kind === 'wait' && s.end == null) patchSeg(n, i, { end: at, status: 'done' })
|
||||
})
|
||||
n.segments.push({ start: at, end: null, kind: 'run', status: 'running', resumed: true })
|
||||
n.state = 'running'
|
||||
}
|
||||
}
|
||||
if (next.startedAt == null) next.startedAt = at
|
||||
if (prevPhase !== 'running' && prevPhase !== 'queued' && prevPhase !== 'idle') reopen()
|
||||
if (type === 'run.started') next.nodesTotal = num(d.nodes) ?? next.nodesTotal
|
||||
openDrive()
|
||||
setPhase(phaseStep.phase)
|
||||
break
|
||||
}
|
||||
|
||||
case 'run.interrupted': {
|
||||
const id = nodeId ?? (d.payload?.node_id ? String(d.payload.node_id) : undefined)
|
||||
const key = String(d.payload?.node_id ?? nodeId ?? '_')
|
||||
if (!next.book.asking[key]) book().asking[key] = true
|
||||
closeDrive(dr)
|
||||
const last = next.waits[next.waits.length - 1]
|
||||
if (!last || last[1] != null) {
|
||||
next.waits = [...next.waits, [at, null]]
|
||||
next.waitingSince = at
|
||||
}
|
||||
if (id) {
|
||||
next.waitingNodeId ??= id
|
||||
const n = node(id)
|
||||
const open = openIndex(n.segments, 'run')
|
||||
if (open >= 0) patchSeg(n, open, { end: at, status: 'waiting' })
|
||||
if (openIndex(n.segments, 'wait') < 0) {
|
||||
n.segments.push({ start: at, end: null, kind: 'wait', status: 'waiting' })
|
||||
}
|
||||
n.state = 'waiting'
|
||||
}
|
||||
setPhase(phaseStep.phase)
|
||||
break
|
||||
}
|
||||
|
||||
case 'node.started': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const open = openIndex(n.segments, 'run')
|
||||
const lastSeg = n.segments[n.segments.length - 1]
|
||||
if (open >= 0) {
|
||||
// 审批恢复后的重放:段在 run.resumed 时已经接上了
|
||||
} else if (d.resumed === true && lastSeg?.kind === 'wait') {
|
||||
// 后端标明是恢复重放、但前面漏了 run.resumed:一样接回去
|
||||
if (lastSeg.end == null) patchSeg(n, n.segments.length - 1, { end: at, status: 'done' })
|
||||
n.segments.push({ start: at, end: null, kind: 'run', status: 'running', resumed: true })
|
||||
} else {
|
||||
const iteration = num(d.iteration) ?? next.book.loopIter
|
||||
n.segments.push({
|
||||
start: at, end: null, kind: 'run', status: 'running',
|
||||
...(iteration != null ? { iteration } : {}),
|
||||
})
|
||||
n.count += 1
|
||||
n.startedAt = at
|
||||
n.endedAt = undefined
|
||||
n.lastDurationMs = undefined
|
||||
n.error = undefined
|
||||
n.toolsRunning = 0
|
||||
if (num(d.iteration) != null) n.iteration = num(d.iteration)
|
||||
book().dispatchFrom[nodeId] = at
|
||||
}
|
||||
n.state = 'running'
|
||||
if (next.book.lastFailed) book().lastFailed = undefined
|
||||
if (prevPhase === 'idle' || prevPhase === 'queued') {
|
||||
if (next.startedAt == null) next.startedAt = at
|
||||
openDrive()
|
||||
}
|
||||
setPhase(phaseStep.phase)
|
||||
break
|
||||
}
|
||||
|
||||
case 'human.requested': {
|
||||
// 右栏在这一刻就把宿主节点标成"等你",画布同一时刻变。并行时 run.interrupted
|
||||
// 要等同一超步里别的分支都跑完才来,只认它的话,右栏已经在说等你确认,
|
||||
// 画布上这个节点还在转、入边的光点还在往里流。相位不动:流水线还没停
|
||||
const key = String(d.node_id ?? nodeId ?? '_')
|
||||
if (next.book.asking[key]) break
|
||||
book().asking[key] = true
|
||||
if (!nodeId || next.nodes[nodeId]?.state !== 'running') break
|
||||
const n = node(nodeId)
|
||||
const open = openIndex(n.segments, 'run')
|
||||
if (open >= 0) patchSeg(n, open, { end: at, status: 'waiting' })
|
||||
if (openIndex(n.segments, 'wait') < 0) {
|
||||
n.segments.push({ start: at, end: null, kind: 'wait', status: 'waiting' })
|
||||
}
|
||||
n.state = 'waiting'
|
||||
break
|
||||
}
|
||||
|
||||
case 'human.resolved':
|
||||
if (next.book.asking[String(nodeId ?? '_')]) delete book().asking[String(nodeId ?? '_')]
|
||||
break
|
||||
|
||||
case 'node.finished':
|
||||
case 'node.failed': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const failed = type === 'node.failed'
|
||||
// 节点跑完了,决定已经生效(兜底 human.resolved 没发出来的老运行)
|
||||
if (!failed && next.book.asking[nodeId]) delete book().asking[nodeId]
|
||||
const ms = num(d.duration_ms)
|
||||
const open = openIndex(n.segments, 'run')
|
||||
const decision = !failed && d.preview && typeof d.preview === 'object'
|
||||
? d.preview.__decision__ : undefined
|
||||
// 人工审批的通过 / 驳回只在这里;分支、循环在 edge.taken 里已经记过同一个值
|
||||
if (decision != null) recordTaken(n, String(decision))
|
||||
// 循环一轮跑完、下一步回到 body:容器还没完,不能打勾
|
||||
const tickHandle = open >= 0 ? n.segments[open].handle : undefined
|
||||
const looping = !failed && tickHandle === 'body'
|
||||
let end = at
|
||||
if (open >= 0) {
|
||||
const seg = n.segments[open]
|
||||
if (!tsOk && ms != null) end = seg.start + ms
|
||||
patchSeg(n, open, { end, status: failed ? 'failed' : 'done' })
|
||||
}
|
||||
// 容器里还开着的成员、调度段:节点都结束了,它们不可能还在跑
|
||||
n.segments.forEach((s, i) => {
|
||||
if (s.end == null && (s.kind === 'member' || s.kind === 'dispatch')) {
|
||||
patchSeg(n, i, { end, status: failed ? 'cancelled' : 'done' })
|
||||
}
|
||||
})
|
||||
if (!tsOk) at = dr.at = Math.max(at, end)
|
||||
n.endedAt = end
|
||||
n.lastDurationMs = ms ?? (open >= 0 ? Math.max(0, end - n.segments[open].start) : undefined)
|
||||
n.toolsRunning = 0
|
||||
n.looping = looping
|
||||
n.state = failed ? 'failed' : looping ? 'running' : 'done'
|
||||
if (failed) {
|
||||
n.error = String(d.error ?? '')
|
||||
book().lastFailed = nodeId
|
||||
} else {
|
||||
n.attempt = num(d.attempt) ?? n.attempt
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'node.skipped': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
n.segments.push({ start: at, end: at, kind: 'run', status: 'skipped' })
|
||||
n.state = 'skipped'
|
||||
n.skippedReason = d.reason ? String(d.reason) : undefined
|
||||
break
|
||||
}
|
||||
|
||||
case 'edge.taken': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const handle = String(d.branch ?? '')
|
||||
recordTaken(n, handle)
|
||||
n.reason = d.reason ? String(d.reason) : undefined
|
||||
const open = openIndex(n.segments, 'run')
|
||||
const cursor = num(d.iteration)
|
||||
if (cursor != null) {
|
||||
// 循环。iteration 是后端的游标,从 0 数:走 body 时它是这一轮的序号,
|
||||
// 走 done 时它等于已经跑完的轮数——那一次不能再 +1,否则 5 项跑完显示第 6 轮
|
||||
const total = num(d.total)
|
||||
if (total != null) n.iterTotal = total
|
||||
if (handle === 'body') {
|
||||
n.iteration = cursor + 1
|
||||
n.loopDone = false
|
||||
book().loopIter = cursor + 1
|
||||
if (open >= 0) patchSeg(n, open, { handle, iteration: cursor + 1 })
|
||||
} else {
|
||||
n.loopDone = true
|
||||
// 循环之后开跑的节点不属于任何一轮,别给它们挂上最后那一轮的标号
|
||||
book().loopIter = undefined
|
||||
if (open >= 0) patchSeg(n, open, { handle })
|
||||
}
|
||||
} else if (open >= 0) {
|
||||
patchSeg(n, open, { handle })
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'tool.start':
|
||||
if (nodeId) {
|
||||
const n = node(nodeId)
|
||||
n.tools += 1
|
||||
n.toolsRunning += 1
|
||||
}
|
||||
break
|
||||
|
||||
case 'tool.end':
|
||||
case 'tool.error':
|
||||
if (nodeId && next.nodes[nodeId]?.toolsRunning) node(nodeId).toolsRunning -= 1
|
||||
break
|
||||
|
||||
case 'llm.start':
|
||||
if (nodeId && d.model) node(nodeId).model = String(d.model)
|
||||
break
|
||||
|
||||
case 'llm.end': {
|
||||
const inTok = num(d.input_tokens) ?? 0
|
||||
const outTok = num(d.output_tokens) ?? 0
|
||||
const cost = num(d.cost_usd) ?? 0
|
||||
next.tokensIn += inTok
|
||||
next.tokensOut += outTok
|
||||
next.costUsd += cost
|
||||
if (nodeId) {
|
||||
const n = node(nodeId)
|
||||
n.tokensIn += inTok
|
||||
n.tokensOut += outTok
|
||||
n.costUsd += cost
|
||||
if (d.model) n.model = String(d.model)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'agent.step.start': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const round = num(d.round)
|
||||
n.segments.push({
|
||||
start: at, end: null, kind: 'member', status: 'running', agent: String(d.agent ?? ''),
|
||||
...(round != null ? { iteration: round + 1 } : {}),
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'agent.step.end': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const i = openIndex(n.segments, 'member', String(d.agent ?? ''))
|
||||
if (i >= 0) {
|
||||
// 结束时刻用 duration 还原:成员交回和 end 事件发出之间可能隔着别人
|
||||
// (后端以前等整轮 gather 完才发 end),end 事件自己的 ts 会晚
|
||||
const ms = num(d.duration_ms)
|
||||
const start = n.segments[i].start
|
||||
patchSeg(n, i, {
|
||||
end: ms != null ? start + ms : at,
|
||||
status: d.error ? 'failed' : 'done',
|
||||
})
|
||||
}
|
||||
const b = book()
|
||||
b.dispatchFrom[nodeId] = Math.max(b.dispatchFrom[nodeId] ?? at, at)
|
||||
break
|
||||
}
|
||||
|
||||
case 'agent.route.start': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
book().exactDispatch[nodeId] = true
|
||||
const round = num(d.round)
|
||||
// 有了精确的调度段,之前推算的那几段作废
|
||||
n.segments = n.segments.filter((s) => !(s.kind === 'dispatch' && s.estimated))
|
||||
n.segments.push({
|
||||
start: at, end: null, kind: 'dispatch', status: 'running',
|
||||
...(round != null ? { iteration: round + 1 } : {}),
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'agent.route.end': {
|
||||
if (!nodeId) break
|
||||
const n = node(nodeId)
|
||||
const i = openIndex(n.segments, 'dispatch')
|
||||
if (i >= 0) {
|
||||
const ms = num(d.duration_ms)
|
||||
patchSeg(n, i, { end: ms != null && !tsOk ? n.segments[i].start + ms : at, status: 'done' })
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'log': {
|
||||
const ending = endingOf(ev, t.book.awaiting)
|
||||
if (ending) {
|
||||
settle(dr, ending)
|
||||
break
|
||||
}
|
||||
if (!nodeId) break
|
||||
if (d.code === 'node_retry') {
|
||||
const n = node(nodeId)
|
||||
n.segments.push({ start: at, end: at, kind: 'retry', status: 'running' })
|
||||
n.attempt = (n.attempt ?? 1) + 1
|
||||
break
|
||||
}
|
||||
// 带 round 的 info 日志是调度决策落地:从上一个时刻到这里是调度者在想。
|
||||
// 推算值,标 estimated;后端发了 agent.route.* 就用精确的
|
||||
if (String(d.level ?? 'info') === 'info' && d.round != null
|
||||
&& !next.book.exactDispatch[nodeId]) {
|
||||
const from = next.book.dispatchFrom[nodeId]
|
||||
const round = num(d.round)
|
||||
if (from != null && next.nodes[nodeId]?.state === 'running') {
|
||||
node(nodeId).segments.push({
|
||||
start: Math.min(from, at), end: at, kind: 'dispatch', status: 'done', estimated: true,
|
||||
...(round != null ? { iteration: round + 1 } : {}),
|
||||
})
|
||||
}
|
||||
book().dispatchFrom[nodeId] = at
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'issuance': {
|
||||
const strs = (v: unknown): string[] =>
|
||||
Array.isArray(v) ? v.map((x) => (typeof x === 'string' ? x
|
||||
: String((x as any)?.token ?? (x as any)?.raw ?? JSON.stringify(x)))) : []
|
||||
const required = strs(d.missing_required)
|
||||
const unmatched = Array.isArray(d.unmatched) ? strs(d.unmatched) : undefined
|
||||
next.issuance = {
|
||||
tier: String(d.tier ?? ''),
|
||||
missing: [...required, ...strs(d.missing_expected)],
|
||||
missingRequired: required,
|
||||
...(unmatched ? { unmatched } : {}),
|
||||
unmatchedCount: unmatched ? unmatched.length : num(d.unmatched) ?? 0,
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'run.finished':
|
||||
case 'run.failed':
|
||||
case 'run.cancelled':
|
||||
case 'stream.end': {
|
||||
const ending = endingOf(ev, t.book.awaiting)
|
||||
if (!ending) break
|
||||
if (type === 'run.failed' || (type === 'stream.end' && ending.phase === 'failed')) {
|
||||
// 失败的是哪个节点:后端给了就用后端的;没给就是最后一个报错、之后没有
|
||||
// 新节点开跑的那个。超时这类没有节点报错的失败,两样都没有
|
||||
const culprit = d.error_node_id ?? d.node_id ?? nodeId ?? next.book.lastFailed
|
||||
if (culprit) {
|
||||
next.failedNodeId = String(culprit)
|
||||
const n = next.nodes[next.failedNodeId]
|
||||
if (n && (n.state === 'running' || n.state === 'waiting')) {
|
||||
const m = node(next.failedNodeId)
|
||||
const open = openIndex(m.segments, 'run')
|
||||
if (open >= 0) patchSeg(m, open, { end: at, status: 'failed' })
|
||||
m.state = 'failed'
|
||||
m.error = m.error || String(d.error ?? '')
|
||||
m.endedAt = at
|
||||
}
|
||||
}
|
||||
}
|
||||
settle(dr, ending)
|
||||
if (type === 'run.finished') {
|
||||
// 权威总数以后端累计为准:agent / 协作的调用老后端不发 llm.end,实时累加会少
|
||||
const u = d.usage ?? {}
|
||||
next.tokensIn = num(u.input_tokens) ?? next.tokensIn
|
||||
next.tokensOut = num(u.output_tokens) ?? next.tokensOut
|
||||
next.costUsd = num(u.cost_usd) ?? next.costUsd
|
||||
}
|
||||
const timing = d.timing
|
||||
if (timing && num(timing.wall_ms) != null) {
|
||||
next.timing = {
|
||||
wallMs: num(timing.wall_ms)!,
|
||||
activeMs: num(timing.active_ms) ?? num(timing.wall_ms)!,
|
||||
waitMs: num(timing.wait_ms) ?? 0,
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// 相位只有一个来源:nextPhase(decodePhase 用的也是它)。上面各分支管的是节点和时长
|
||||
setPhase(phaseStep.phase)
|
||||
if (at > next.book.clock) book().clock = at
|
||||
|
||||
const parallel = parallelOf(next.nodes)
|
||||
const lastPar = next.parallelSeries[next.parallelSeries.length - 1]
|
||||
if ((lastPar ? lastPar[1] : 0) !== parallel) {
|
||||
next.parallelSeries = [...next.parallelSeries, [at, parallel]]
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
function recordTaken(n: NodeTrace, handle: string): void {
|
||||
n.takenHandle = handle
|
||||
if (!n.taken?.includes(handle)) n.taken = [...(n.taken ?? []), handle]
|
||||
}
|
||||
|
||||
/**
|
||||
* 终态收尾 + 推导 blocked / unreached。
|
||||
*
|
||||
* foldEvent 在终态事件到达时已经把进行中的收掉了;这里再兜一次底(终态事件
|
||||
* 之后又漏进来的段),然后对照图把"没有事件"的节点分成:因为上游失败被堵住的
|
||||
* (blocked)和压根没走到的(unreached,分支落空、运行被取消)。
|
||||
*
|
||||
* 没到终态时只做推导(排队中),不收尾——运行还在进行,没法替它下结论。
|
||||
*/
|
||||
export function finalizeTrace(t: Trace, graph?: GraphLike): Trace {
|
||||
let out = t
|
||||
if (isSettled(t.phase)) {
|
||||
const lingering = Object.values(t.nodes).some((n) =>
|
||||
n.state === 'running' || n.state === 'queued' || n.state === 'waiting'
|
||||
|| n.segments.some((s) => s.end == null))
|
||||
if (lingering) {
|
||||
const dr = draftOf(t, t.endedAt ?? t.book.clock)
|
||||
settle(dr, endingFor(t.phase))
|
||||
out = dr.next
|
||||
}
|
||||
}
|
||||
if (graph) {
|
||||
out = applyDerived(out, graph)
|
||||
if (out.nodesTotal == null && graph.nodes.length) out = { ...out, nodesTotal: graph.nodes.length }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 已经处在某个结局时,还没收干净的东西该收成什么(和 endingOf 同一套规则) */
|
||||
function endingFor(phase: RunPhase): Ending {
|
||||
return endingOf({ seq: 0, type: 'stream.end', node_id: null, ts: 0, data: { status: phase } }, false)
|
||||
?? { phase, running: 'cancelled', waiting: 'cancelled', drive: 'cancelled' }
|
||||
}
|
||||
|
||||
/** 这一段结束后节点处在什么状态。循环跑完一轮回到 body 时容器还在进行中 */
|
||||
function stateAfter(s: Segment): NodeState {
|
||||
if (s.kind === 'wait') return 'running'
|
||||
if (s.handle === 'body') return 'running'
|
||||
return s.status
|
||||
}
|
||||
|
||||
function phaseAt(t: Trace, at: number): RunPhase {
|
||||
let phase: RunPhase | null = null
|
||||
for (const [ts, p] of t.phases) {
|
||||
if (ts > at) break
|
||||
phase = p
|
||||
}
|
||||
if (phase) return phase
|
||||
return t.phases.length ? 'queued' : t.phase
|
||||
}
|
||||
|
||||
const clipped = (spans: [number, number | null][], at: number): number =>
|
||||
spans.reduce((acc, [s, e]) => (s > at ? acc : acc + Math.max(0, Math.min(e ?? at, at) - s)), 0)
|
||||
|
||||
/**
|
||||
* 把航迹投影到某一刻:实时时 at 取 liveAt(trace, now),回放时取游标。
|
||||
*
|
||||
* 只折算 at 之前的部分。at 不早于最后一条事件时就是实时状态,直接读节点的
|
||||
* 当前状态(含推导出的排队中 / 被阻断 / 没走到);早于它时按段重建。
|
||||
*/
|
||||
export function project(t: Trace, at: number): Projection {
|
||||
const live = at >= t.book.clock
|
||||
const phase = live ? t.phase : phaseAt(t, at)
|
||||
const authoritative = live && isTerminal(t.phase) && t.timing
|
||||
|
||||
const end = t.endedAt != null && t.endedAt <= at ? t.endedAt : t.timed ? at : t.book.clock
|
||||
const elapsedMs = authoritative ? t.timing!.wallMs
|
||||
: t.startedAt == null ? 0 : Math.max(0, end - t.startedAt)
|
||||
const waitMs = authoritative ? t.timing!.waitMs : t.timed ? clipped(t.waits, at) : 0
|
||||
const activeMs = authoritative ? t.timing!.activeMs
|
||||
: t.timed ? clipped(t.drives, Math.min(at, end)) : elapsedMs
|
||||
|
||||
const nodes: Projection['nodes'] = {}
|
||||
let nodesDone = 0
|
||||
for (const n of Object.values(t.nodes)) {
|
||||
let view: Projection['nodes'][string]
|
||||
if (live) {
|
||||
const open = n.segments[openIndex(n.segments, 'run')]
|
||||
view = {
|
||||
state: n.state,
|
||||
count: n.count,
|
||||
...(n.iteration != null ? { iteration: n.iteration } : {}),
|
||||
...(open && n.state === 'running'
|
||||
? { elapsedMs: Math.max(0, (t.timed ? at : t.book.clock) - open.start) }
|
||||
: n.lastDurationMs != null ? { elapsedMs: n.lastDurationMs } : {}),
|
||||
}
|
||||
} else {
|
||||
let state: NodeState = 'idle'
|
||||
let count = 0
|
||||
let iteration: number | undefined
|
||||
let elapsedMs: number | undefined
|
||||
for (const s of n.segments) {
|
||||
if (s.start > at || s.kind === 'member' || s.kind === 'dispatch' || s.kind === 'retry') continue
|
||||
if (s.kind === 'wait') {
|
||||
state = s.end == null || s.end > at ? 'waiting' : stateAfter(s)
|
||||
continue
|
||||
}
|
||||
if (s.status === 'skipped' && s.end === s.start) { state = 'skipped'; continue }
|
||||
if (!s.resumed) count += 1
|
||||
if (s.iteration != null) iteration = s.iteration
|
||||
if (s.end == null || s.end > at) {
|
||||
state = 'running'
|
||||
elapsedMs = at - s.start
|
||||
} else {
|
||||
state = stateAfter(s)
|
||||
elapsedMs = s.end - s.start
|
||||
}
|
||||
}
|
||||
view = { state, count, ...(iteration != null ? { iteration } : {}),
|
||||
...(elapsedMs != null ? { elapsedMs } : {}) }
|
||||
}
|
||||
if (view.state === 'done' || view.state === 'skipped') nodesDone += 1
|
||||
nodes[n.id] = view
|
||||
}
|
||||
|
||||
let parallelNow = 0
|
||||
if (!(live && isSettled(t.phase))) {
|
||||
for (const [ts, v] of t.parallelSeries) {
|
||||
if (ts > at) break
|
||||
parallelNow = v
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
phase, elapsedMs, activeMs, waitMs, nodesDone,
|
||||
nodesTotal: t.nodesTotal ?? Object.keys(t.nodes).length,
|
||||
parallelNow, nodes,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useStudio } from '../store/studio'
|
||||
import { applyDerived, type GraphLike } from './derive'
|
||||
import { project, type NodeState, type NodeTrace, type Projection, type Trace } from './trace'
|
||||
import type { NodeRuntime } from '../types'
|
||||
|
||||
/**
|
||||
* 节点卡取状态的唯一入口。
|
||||
*
|
||||
* 卡片以前直接读 runtime[id].status,于是推导出来的几种(排队、被阻断、没走到)
|
||||
* 永远显示成"未运行"——runtime 里它们一律是 idle,只有航迹知道;回放时拖到
|
||||
* 某一刻,卡片也还是停在最后的样子。这里统一成:实时看航迹(没有航迹记录的
|
||||
* 退回 runtime),回放看 project(trace, replayAt) 在那一刻的投影,再和实时一样
|
||||
* 按图推导一遍(见 replayTraceCached)。
|
||||
*
|
||||
* runtime 上的正文、工具调用、协作矩阵照样给出去:那些是"内容"不是"状态",
|
||||
* 航迹不存它们。回放时它们是最后的样子,卡片据此只在实时运行中显示流式正文。
|
||||
*/
|
||||
export interface NodeView {
|
||||
state: NodeState
|
||||
/** 在看回放(replayAt 不为 null):计时用投影给的定值,不走时钟 */
|
||||
replay: boolean
|
||||
runtime: NodeRuntime | undefined
|
||||
trace: NodeTrace | undefined
|
||||
/** 执行了几次(循环、接着跑都会 > 1)。回放时是那一刻之前的次数 */
|
||||
count: number
|
||||
iteration?: number
|
||||
/** 回放时这一刻的执行用时(进行中是已经用了多久,结束了是那一段的用时) */
|
||||
replayElapsedMs?: number
|
||||
/** 回放游标(毫秒时间戳);实时为 null。卡片据此把计时、协作矩阵截到那一刻 */
|
||||
at: number | null
|
||||
/**
|
||||
* 循环容器在两轮之间:状态是 running,真正在跑的是循环体。卡片不转圈、不挂光弧。
|
||||
* 回放时按游标那一刻算——航迹上的 looping 是最后的值,跑完了就是 false
|
||||
*/
|
||||
looping: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 同一个游标只投影一次。
|
||||
*
|
||||
* 几十张卡片各自 project 一遍整条航迹是 O(卡片数 × 事件数),拖时间轴时每一帧
|
||||
* 都要来一次。所有卡片共用最近一次的结果:航迹引用和游标都没变就直接拿。
|
||||
*/
|
||||
let last: { trace: Trace; at: number; proj: Projection } | null = null
|
||||
|
||||
export function projectCached(trace: Trace, at: number): Projection {
|
||||
if (last && last.trace === trace && last.at === at) return last.proj
|
||||
const proj = project(trace, at)
|
||||
last = { trace, at, proj }
|
||||
return proj
|
||||
}
|
||||
|
||||
/**
|
||||
* 回放游标那一刻的整份航迹:投影出的状态、那一刻为止走过的出口、循环容器是否
|
||||
* 在两轮之间,再按图推导排队 / 阻断 / 未到达。
|
||||
*
|
||||
* 卡片和画布(边、小地图)读同一份:只投影不推导的话,拖到半路时小地图上某个
|
||||
* 节点在排队、卡片却写着「未运行」。和 projectCached 一样只缓存最近一次,航迹、
|
||||
* 游标、图三样都没变就直接拿。
|
||||
*/
|
||||
let lastReplay: { trace: Trace; at: number; nodes: object; edges: object; out: Trace } | null = null
|
||||
|
||||
export function replayTraceCached(trace: Trace, at: number, graph: GraphLike): Trace {
|
||||
const hit = lastReplay
|
||||
if (hit && hit.trace === trace && hit.at === at && hit.nodes === graph.nodes && hit.edges === graph.edges) {
|
||||
return hit.out
|
||||
}
|
||||
const proj = projectCached(trace, at)
|
||||
const nodes: Record<string, NodeTrace> = {}
|
||||
for (const [id, n] of Object.entries(trace.nodes)) {
|
||||
const p = proj.nodes[id]
|
||||
const taken: string[] = []
|
||||
let looping = false
|
||||
for (const s of n.segments) {
|
||||
if (s.kind !== 'run' || s.start > at) continue
|
||||
if (s.handle && !taken.includes(s.handle)) taken.push(s.handle)
|
||||
looping = s.handle === 'body' && s.end != null && s.end <= at
|
||||
}
|
||||
const state = p?.state ?? 'idle'
|
||||
// 人工审批的通过 / 驳回只记在节点上,不在段上:它结束了就用节点上的
|
||||
const finished = state === 'done' || state === 'failed'
|
||||
const decided = taken.length ? taken : finished ? n.taken ?? [] : []
|
||||
nodes[id] = {
|
||||
...n, state, count: p?.count ?? 0, iteration: p?.iteration, taken: decided,
|
||||
takenHandle: decided[decided.length - 1], looping: state === 'running' && looping,
|
||||
}
|
||||
}
|
||||
const out = applyDerived({ ...trace, phase: proj.phase, nodes }, graph)
|
||||
lastReplay = { trace, at, nodes: graph.nodes, edges: graph.edges, out }
|
||||
return out
|
||||
}
|
||||
|
||||
export function useNodeView(id: string): NodeView {
|
||||
const runtime = useStudio((s) => s.runtime[id])
|
||||
const node = useStudio((s) => s.trace.nodes[id])
|
||||
// 拖时间轴时游标每帧都变,但投影本来就每帧重算、每张卡都会重渲染一次,
|
||||
// 多订阅这一个数不增加渲染次数
|
||||
const at = useStudio((s) => s.replayAt)
|
||||
// 投影里单个节点的那一项:同一份投影里引用稳定,别的卡片动了不会连带这张重渲染
|
||||
const projected = useStudio((s) => (s.replayAt == null ? undefined
|
||||
: projectCached(s.trace, s.replayAt).nodes[id]))
|
||||
const derived = useStudio((s) => (s.replayAt == null ? undefined
|
||||
: replayTraceCached(s.trace, s.replayAt, { nodes: s.nodes, edges: s.edges }).nodes[id]))
|
||||
|
||||
if (at != null) {
|
||||
return {
|
||||
state: derived?.state ?? projected?.state ?? 'idle',
|
||||
replay: true,
|
||||
runtime,
|
||||
trace: node,
|
||||
count: projected?.count ?? 0,
|
||||
iteration: projected?.iteration,
|
||||
replayElapsedMs: projected?.elapsedMs,
|
||||
at,
|
||||
looping: !!derived?.looping,
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: node?.state ?? runtime?.status ?? 'idle',
|
||||
replay: false,
|
||||
runtime,
|
||||
trace: node,
|
||||
count: node?.count ?? 0,
|
||||
iteration: node?.iteration ?? runtime?.iteration,
|
||||
at: null,
|
||||
looping: !!node?.looping,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 最后一段还开着的某类段从什么时候开始。实时计时从这里起算。
|
||||
* 给了回放游标就只看那一刻:那时已经开始、还没结束的段
|
||||
*/
|
||||
export function openSince(n: NodeTrace | undefined, kind: 'run' | 'wait', at?: number | null): number | undefined {
|
||||
if (!n) return undefined
|
||||
for (let i = n.segments.length - 1; i >= 0; i -= 1) {
|
||||
const s = n.segments[i]
|
||||
if (s.kind !== kind) continue
|
||||
if (at == null) {
|
||||
if (s.end == null) return s.start
|
||||
continue
|
||||
}
|
||||
if (s.start > at) continue
|
||||
return s.end == null || s.end > at ? s.start : undefined
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环容器这一次进入是从什么时候开始的。
|
||||
*
|
||||
* 循环节点每一轮都会重新 node.started,startedAt 只是这一轮的起点;容器的计时
|
||||
* 要从这一次进入的第一轮算起。往回找到上一次走 done 出口的那一段为止——嵌套
|
||||
* 在外层循环里时,外层每进来一次,内层都是新的一次。
|
||||
*/
|
||||
export function loopSince(n: NodeTrace | undefined, at?: number | null): number | undefined {
|
||||
if (!n) return undefined
|
||||
let since: number | undefined
|
||||
for (let i = n.segments.length - 1; i >= 0; i -= 1) {
|
||||
const s = n.segments[i]
|
||||
if (s.kind !== 'run' || (at != null && s.start > at)) continue
|
||||
if (s.handle === 'done' && since != null) break
|
||||
since = s.start
|
||||
}
|
||||
return since
|
||||
}
|
||||
|
||||
/** 循环容器这一次进入到走 done 出口一共用了多久(回放时截到游标那一刻) */
|
||||
export function loopSpan(n: NodeTrace | undefined, at?: number | null): number | undefined {
|
||||
const since = loopSince(n, at)
|
||||
if (!n || since == null) return undefined
|
||||
let end: number | undefined
|
||||
for (const s of n.segments) {
|
||||
if (s.kind !== 'run' || s.start < since || (at != null && s.start > at)) continue
|
||||
if (s.end != null && (at == null || s.end <= at)) end = s.end
|
||||
}
|
||||
return end != null ? end - since : undefined
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useReducer } from 'react'
|
||||
|
||||
/**
|
||||
* 运行计时用的时钟。全站只有一个 interval,所有在跑的计时器共用同一拍。
|
||||
*
|
||||
* 各自 setInterval 的话,胶囊、卡片、时间轴三处的秒数会差出几十毫秒,同一次
|
||||
* 运行在屏幕上显示三个不同的"已用时间";而且卡片一多就是几十个定时器。
|
||||
*
|
||||
* 节拍:有人在看运行中的计时时 100ms 一次(mm:ss.s 的最后一位要走起来);
|
||||
* 系统关了动效、或页面不可见时退到 1s 一次;没有订阅者就停掉。页面重新可见
|
||||
* 时立刻补一拍,不让人看到一个停在几分钟前的数字。
|
||||
*/
|
||||
|
||||
type Listener = () => void
|
||||
|
||||
const listeners = new Set<Listener>()
|
||||
let now = Date.now()
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let period = 0
|
||||
let watching = false
|
||||
|
||||
const reduceMotion = (): boolean =>
|
||||
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
const hidden = (): boolean =>
|
||||
typeof document !== 'undefined' && document.visibilityState === 'hidden'
|
||||
|
||||
function tick(): void {
|
||||
now = Date.now()
|
||||
listeners.forEach((l) => l())
|
||||
}
|
||||
|
||||
function reschedule(): void {
|
||||
const want = listeners.size ? (reduceMotion() || hidden() ? 1000 : 100) : 0
|
||||
if (want === period) return
|
||||
if (timer) clearInterval(timer)
|
||||
timer = null
|
||||
period = want
|
||||
if (want) timer = setInterval(tick, want)
|
||||
}
|
||||
|
||||
/** 可见性、动效偏好一变就换节拍。只挂一次,页面整个生命周期都在 */
|
||||
function watchEnvironment(): void {
|
||||
if (watching || typeof document === 'undefined') return
|
||||
watching = true
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
reschedule()
|
||||
if (!hidden() && listeners.size) tick()
|
||||
})
|
||||
if (typeof matchMedia === 'function') {
|
||||
matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change', reschedule)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前时间(毫秒)。active 为 false 时不订阅节拍,只在组件因为别的原因重渲染
|
||||
* 时给出当时的时间——终态的数字是定值,用不着每 100ms 重画一遍。
|
||||
*/
|
||||
export function useRunClock(active: boolean): number {
|
||||
const [, bump] = useReducer((x: number) => x + 1, 0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
watchEnvironment()
|
||||
listeners.add(bump)
|
||||
reschedule()
|
||||
// 停了一阵的时钟 now 是旧的,接上时立刻补一拍
|
||||
tick()
|
||||
return () => {
|
||||
listeners.delete(bump)
|
||||
reschedule()
|
||||
}
|
||||
}, [active])
|
||||
|
||||
// 没有节拍在走时 now 可能是很久以前的值,直接取当前时间
|
||||
if (!timer) now = Date.now()
|
||||
return active ? now : Date.now()
|
||||
}
|
||||
Reference in New Issue
Block a user