Files
AgentLab/frontend/src/canvas/NodeCard.tsx
T
ThearchyHelios f0fd63f0b9 UI 重构:Copilot 进侧栏,三个页面共用一条助手流
用户的原话是「copilot(包括问答)可以是侧边栏的效果」「显示他的简要思考节点,
使得用户知道他大致在想什么,以及用了哪些工具」。

画布右栏从「运行 / 属性 → 时间线 / 成果 / 事件」(两层嵌套 5 个视图)变成
「助手 / 属性」一层。助手栏里是一条流:你让它做什么、它做了什么、结果是什么。
Copilot 建图和跑图在协议上完全无关(SSE 操作流 vs 事件 WebSocket,不共享
seq 和 node_id),但对用户是一件事的两半,decode.ts 把两种流译成同一种 Step
之后才能排进同一条时间轴。

Copilot 不再是弹窗。弹窗的问题不是样式:每改一次图都要重开一次,关掉之后
需求文本就没了,想微调只能重打;而画布左下角那条浮条(z-30)和 Toast
(z-100)、Modal(z-50)三层各自为政,本身也是重复的一份 Copilot 状态渲染。
两个都删了,输入框就在栏里,说完一句接着说下一句。右栏没删——它是发起运行
和处理审批的唯一入口,RunLauncher 原样保留,只是跑起来会自动收起给执行过程
让位。tab 用 hidden 切换而不是卸载,不然点一下「属性」看个节点再切回来,
输入框草稿和展开状态全丢。

问数据页和运行页换成同一个 AssistantStream + 同一个 decode.ts。RunPanel 里
那套平行的 EVENT_META + describe() 删了:留着两套翻译,同一次运行在不同页面
会读出不同的故事,而用户没法判断哪个是真的。同理合并了两个耗时格式化函数
(画布节点显示"0ms",右边同一步什么都不显示,两块还并排放着)。运行页列表
加了内容摘要——原本每行只有"临时图 · 1.2s · 340 tok",十条长得一模一样,
要分清哪条是哪条只能挨个点开。

跑真实运行时发现两个缺陷:

1. 后端丢事件(app/core/bus.py)。WebSocket 先读历史、再订阅,两步之间图
   正好跑出来的事件既不在历史里也不在实时流里,永远丢了。而 subscribe() 是
   异步生成器,真正注册还要等到第一次迭代,窗口比看上去更大。实测一次跑图
   开头的 node.finished/node.started 消失,界面上表现为某个节点永远在转圈、
   它的子步骤跑到了顶层。改成先 attach 占位、再读历史,重叠部分按 seq 去重。
   tests/test_bus_attach.py 里有一条刻画旧行为的测试,说明这个窗口确实存在。

2. 循环里的多轮审批被算错。我在 S1 按内容去重,但三轮审批的 title 一模一样,
   和 LangGraph 的重放无法区分——结果第 2、3 次真实审批被当成重放吞掉,而
   三次"你驳回了/你放行了"各自成行。改成开/闭配对:开着就是同一次,闭了才是
   新一次;决定折进那条审批行而不是另起一行。真实运行(驳回 → 改写 → 再驳回
   → 改写 → 放行)已收进 fixtures。

验证:三层各守一件事,共 76 条断言全过。check-decode 守翻译(含新的多轮审批
和截断结果集),check-stream 守渲染,新增 check-ui 守"接起来还对不对"——真
浏览器真后端,包括「切走再切回来草稿还在」「唯一的运行入口还在」「原始事件
切得到也切得回」。另外真跑了一次带三轮审批的图和两次 Copilot 生成(60s,
deepseek-v4-pro),截图逐帧看过。后端 78 个测试全过。
2026-09-17 18:29:16 +08:00

193 lines
8.1 KiB
TypeScript

import { memo } from 'react'
import { Handle, Position, type NodeProps } from '@xyflow/react'
import { AlertTriangle, Check, Hand, Loader2, Sparkles, Wrench } from 'lucide-react'
import clsx from 'clsx'
import { NODE_DEFS, sourceHandles } from './nodeDefs'
import { formatDuration } from '../run/decode'
import { useStudio, type FlowNode } from '../store/studio'
import type { NodeType } from '../types'
/** 卡片正文的一行摘要:不用打开属性面板就能看懂这个节点在干什么。 */
function summarize(type: NodeType, config: Record<string, any>): string {
const first = (...vals: any[]) => vals.find((v) => typeof v === 'string' && v.trim())?.trim() ?? ''
switch (type) {
case 'input':
return (config.fields ?? []).map((f: any) => f.name).filter(Boolean).join(' · ') || '未定义输入'
case 'output': {
const names = (config.fields ?? []).map((f: any) => f.name).filter(Boolean).join(' · ')
return (config.contract ? '⚖ 出具契约 · ' : '') + (names || '未定义成果')
}
case 'llm':
return first(config.prompt, config.system) || '未填提示'
case 'agent': {
const tools = (config.tools ?? []).length
return `${first(config.prompt, config.system) || '未填任务'}${tools ? ` · ${tools} 个工具` : ''}`
}
case 'supervisor':
return `${(config.agents ?? []).map((a: any) => a.name).join(' / ') || '未配成员'}`
case 'tool':
return config.tool ? `${config.tool}()` : '未选择工具'
case 'code':
return `${config.language ?? 'python'} · ${(config.code ?? '').split('\n')[0].slice(0, 48) || '空'}`
case 'branch':
return (config.cases ?? []).map((c: any) => c.key).filter(Boolean).join(' / ') || '未配分支'
case 'loop':
return config.mode === 'while'
? `当 ${config.condition || '?'} 时重复`
: `遍历 ${config.items || '?'}`
case 'retrieve':
return `${config.collection || 'default'} · 取 ${config.limit ?? 5} 条`
case 'memory':
return `${{ recall: '回忆', write: '记住', clear: '清空' }[config.action as string] ?? ''} @ ${config.scope || 'default'}`
case 'human':
return first(config.title) || '等待人工'
case 'validate':
return 'JSON Schema 校验' + (config.repair_with_llm ? ' · 失败自动返工' : '')
case 'metrics':
return `${config.caliber || '口径'}@${config.caliber_version || 'v1'} · ${(config.metrics ?? []).length} 个指标`
case 'transform':
return first(config.expression, config.template) || '未配置'
case 'subgraph':
return config.workflow_id ? '嵌套工作流' : '未选择工作流'
default:
return ''
}
}
function NodeCardImpl({ id, data, selected }: NodeProps<FlowNode>) {
const def = NODE_DEFS[data.nodeType]
const runtime = useStudio((s) => s.runtime[id])
// selector 必须返回稳定引用:filter() 每次都造新数组,会触发无限重渲染
const hasError = useStudio((s) => s.issues.some((i) => i.node_id === id && i.level === 'error'))
const copilotNew = useStudio((s) => s.copilotNew.includes(id))
const Icon = def?.icon ?? Sparkles
const handles = sourceHandles(data.nodeType, data.config)
const status = runtime?.status ?? 'idle'
const streamed = runtime?.tokens || runtime?.thinking
const summary = summarize(data.nodeType, data.config)
return (
<div
className={clsx(
`nt-${data.nodeType} group relative rounded-lg border bg-elev transition-shadow`,
status === 'running' && 'node-running',
status === 'done' && 'node-done',
status === 'failed' && 'node-failed',
status === 'waiting' && 'node-waiting',
copilotNew && 'node-copilot-new',
selected && 'ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]',
)}
style={{ width: 238, borderColor: selected ? 'var(--accent)' : undefined }}
>
{def?.hasTarget && (
<Handle type="target" position={Position.Left} style={{ left: -5 }} />
)}
{/* 标题栏 */}
<div className="flex items-center gap-2 rounded-t-lg px-2.5 py-2"
style={{ background: 'color-mix(in srgb, var(--nt) 9%, transparent)' }}>
<div
className="flex h-5 w-5 shrink-0 items-center justify-center rounded"
style={{ background: 'color-mix(in srgb, var(--nt) 20%, transparent)', color: 'var(--nt)' }}
>
<Icon size={12} />
</div>
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium leading-tight">
{data.label || def?.label}
</div>
</div>
{status === 'running' && <Loader2 size={12} className="animate-spin" style={{ color: 'var(--nt)' }} />}
{status === 'done' && <Check size={12} className="text-[var(--ok)]" />}
{status === 'waiting' && <Hand size={12} className="text-[var(--warn)]" />}
{status === 'failed' && <AlertTriangle size={12} className="text-[var(--err)]" />}
{status === 'idle' && hasError && (
<AlertTriangle size={12} className="text-[var(--err)] opacity-70" />
)}
</div>
{/* 摘要 */}
{summary && (
<div className="px-2.5 pb-2 pt-1.5 text-[11px] leading-snug text-dim">
<div className="line-clamp-2 break-words">{summary}</div>
</div>
)}
{/* 运行态:实时流出来的内容 */}
{streamed && status !== 'idle' && (
<div className="mx-2 mb-2 max-h-20 overflow-hidden rounded border bg-bg px-2 py-1.5">
{runtime?.thinking && !runtime?.tokens && (
<div className="mb-1 text-[9.5px] uppercase tracking-wide text-faint">思考中</div>
)}
<div className="mono whitespace-pre-wrap break-words text-[10px] leading-relaxed text-dim">
{(runtime?.tokens || runtime?.thinking || '').slice(-180)}
</div>
</div>
)}
{/* 工具调用 */}
{!!runtime?.toolCalls?.length && (
<div className="mx-2 mb-2 flex flex-wrap gap-1">
{runtime.toolCalls.slice(-4).map((call, i) => (
<span
key={i}
className="chip"
style={{
borderColor: call.ok === false ? 'var(--err)' : undefined,
color: call.ok === undefined ? 'var(--accent)' : undefined,
}}
title={call.result?.slice(0, 300)}
>
<Wrench size={8} />
{call.tool}
</span>
))}
</div>
)}
{/* 底部状态条 */}
{(runtime?.durationMs != null || runtime?.error) && (
<div className="flex items-center gap-2 border-t px-2.5 py-1">
{runtime.durationMs != null && (
<span className="text-[10px] text-faint">{formatDuration(runtime.durationMs)}</span>
)}
{runtime.error && (
<span className="truncate text-[10px] text-[var(--err)]" title={runtime.error}>
{runtime.error}
</span>
)}
</div>
)}
{/* 出口:有名字的分支把标签显示出来,不用点开就知道哪条是哪条 */}
{handles.map((handle, i) => {
const top = handles.length === 1 ? '50%' : `${((i + 1) / (handles.length + 1)) * 100}%`
return (
<div key={handle.id}>
<Handle
id={handle.id}
type="source"
position={Position.Right}
style={{ top, right: -5, borderColor: handle.color }}
/>
{handle.label && (
<span
className="pointer-events-none absolute left-full ml-2 -translate-y-1/2 whitespace-nowrap text-[9.5px]"
style={{ top, color: handle.color ?? 'var(--text-faint)' }}
>
{handle.label}
</span>
)}
</div>
)
})}
</div>
)
}
// 耗时格式化原本在这里又写了一份(formatMs),和 decode.ts 的规则不一样:
// 画布节点上显示"0ms",右边助手栏里同一步什么都不显示。两块并排放着,
// 用户看到的是两套说法。统一用 decode.ts 那份。
export const NodeCard = memo(NodeCardImpl)