mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 08:13:03 +00:00
第三波前两批:六个「看着成功其实没干活」的平台漏洞堵上,记录页能回放,管理页与画布收尾
起因是一次探索运行:Copilot 改节点时把工具绑定整份抹掉,agent 没有工具只能写「假设调用」, 校验节点的自动修复编出 total_count=0 让 schema 通过,协作成员把工具调用标记当文字输出了四轮, 轮数用完后节点把原话当成功结果交出去——运行标成已完成,数据库一次都没查。 平台可信度(先写失败测试) - Copilot 修改节点改为合并:没写的字段保留,null 才删除;协作成员按名字合并。前后端同一套规则, 工具集合变小时自查报警、改图回执列出变化 - 新校验规则:提示词点名了某个工具而节点没有绑定它,判错误,Copilot 自查会交回去修 - 校验修复只许改格式:冒出原文没有的值就判修复无效;修复这次模型调用计入用量 - 识别模型把工具调用写成文字的情况(DSML、<tool_call> 等标记):纠正一次,仍然如此就判失败并说明原因 - 协作团队用完轮数不再按成功交付:默认失败,可选降档,点出一次都没派到的成员 - 审批恢复后,同一节点里已经执行过的工具调用复用结果,不再重复执行 后端 - 查询时限交给数据库执行(Oracle call_timeout、PG statement_timeout、MySQL max_execution_time、 SQLite progress handler),可按数据源配置;超时报错与实际耗时一致 - 等审批的运行可以真正取消;会话列表带最后一轮状态;测连接结果持久化;探查结构可只看不存; 自定义工具可草稿试跑、写坏的参数定义保存时拒绝;MCP 服务改动后作废旧工具缓存; 检索命中带贡献分解;重建索引在后台跑并报进度;报错统一收进 core/errors 前端 - 公共层:管理页共用件、失败说明(lib/explain)、健康状态进公共库;目录按表各自加载并有超时, 一张表卡住不再拖垮整站;上传显示真实字节进度;离线横幅只播报不变的句子 - 画布:卡片只说游标所在的那一次执行;等审批时可放弃运行;团队收尾判定与未完成说清楚; 回放用量取那一刻的值 - 编排页:Copilot 合并语义与工具变化回执;「用完轮数时」选项;正式运行期间锁住所有改图入口 - 回答流 / 问数据:新失败类型说人话并给下一步;画布与右栏互相定位;数据源范围、回收站、重新核对 - 记录页:「航迹」页签复用画布时间轴,可拖动回放、列出关键时刻;列表行带执行 / 等人 / 失败缩略条 - 外壳:统一的离开前确认(data router),导航、⌘K、快捷键、后退都会先问 验证(沙箱):tsc 干净,pytest 838 passed(两遍),14 个检查脚本中 13 个全绿; check-ui 余 1 项旧断言(按旧日期格式找运行行),3c 更新。
This commit is contained in:
@@ -1,27 +1,29 @@
|
||||
import './surface.css'
|
||||
import {
|
||||
createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState, type CSSProperties,
|
||||
createContext, memo, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, type CSSProperties,
|
||||
} from 'react'
|
||||
import {
|
||||
Background, BackgroundVariant, ControlButton, Controls, MiniMap, ReactFlow, ReactFlowProvider,
|
||||
useReactFlow, useStoreApi, type AriaLabelConfig, type Edge, type MiniMapNodeProps, type Viewport,
|
||||
useReactFlow, useStoreApi, ViewportPortal, type AriaLabelConfig, type Edge, type MiniMapNodeProps, type Viewport,
|
||||
} from '@xyflow/react'
|
||||
import { Crosshair, Lock, Route as RouteIcon } from 'lucide-react'
|
||||
import { Crosshair, Lock, PanelRightOpen, Route as RouteIcon, Search } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { FlowEdge, MomentContext, RoutingContext, type EdgeRunState, type EdgeView } from './FlowEdge'
|
||||
import { openInspector, stepsFirst, useSheet } from './InspectorSheet'
|
||||
import { NodeCard } from './NodeCard'
|
||||
import { NODE_CATEGORIES, NODE_DEFS, type NodeDef } from './nodeDefs'
|
||||
import { buildRoutes, NODE_WIDTH } from './routing'
|
||||
import { RunTimeline, useDock } from './RunTimeline'
|
||||
import { toast } from '../components/ui'
|
||||
import { isComposing, toast } from '../components/ui'
|
||||
import { runClassLabel } from '../lib/terms'
|
||||
import { shortId } from '../lib/format'
|
||||
import {
|
||||
activeEdgesOf, applyDerived, edgeIdOf, edgeKey, heldEdgesOf, topology, walkedEdges, type GraphLike,
|
||||
activeEdgesOf, edgeIdOf, edgeKey, heldEdgesOf, topology, walkedEdges, type GraphLike,
|
||||
} from '../run/derive'
|
||||
import {
|
||||
isActivePhase, isTerminal, type NodeState, type NodeTrace, type RunPhase, type Trace,
|
||||
} from '../run/trace'
|
||||
import { projectCached } from '../run/useNodeView'
|
||||
import { replayTraceCached } from '../run/useNodeView'
|
||||
import { useStudio, type FlowNode } from '../store/studio'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
@@ -30,6 +32,11 @@ const edgeTypes = { flow: FlowEdge }
|
||||
|
||||
/** 读得清卡片字的最低缩放。低于它,12px 的标题落到 7px 以下,光弧也细到看不见 */
|
||||
const READABLE_ZOOM = 0.6
|
||||
/**
|
||||
* 精简档里标题换成放大的字(见 NodeCard 的 .nc-lod),0.4 倍时屏幕上仍有 11px 以上。
|
||||
* 整张图在可读缩放下放不下、在这里放得下时,打开就看全图的形状,而不是只看前两列
|
||||
*/
|
||||
const COMPACT_ZOOM = 0.4
|
||||
/** 语义缩放三档的门槛,上下各留 0.02 的回滞,免得停在门槛上来回跳 */
|
||||
const LOD_FULL = 0.6
|
||||
const LOD_SIGNAL = 0.35
|
||||
@@ -105,31 +112,43 @@ let lastFocus: object | null = null
|
||||
const setStudio = useStudio.setState as (patch: Record<string, unknown>) => void
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 回放:把航迹投影到游标那一刻,边和小地图按那一刻的样子画
|
||||
// 回放:航迹投影到游标那一刻(run/useNodeView 的 replayTraceCached,卡片读同一份),
|
||||
// 边、小地图、回边的圈数都按那一刻画
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function replayTrace(t: Trace, at: number, graph: GraphLike): Trace {
|
||||
const proj = projectCached(t, at)
|
||||
const nodes: Record<string, NodeTrace> = {}
|
||||
for (const [id, n] of Object.entries(t.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, taken: decided, takenHandle: decided[decided.length - 1],
|
||||
looping: state === 'running' && looping,
|
||||
}
|
||||
/**
|
||||
* 回边兜回去了几次:目标这一次进入以来开跑的次数减一。回放截到游标。
|
||||
* 走过 done 出口的那一段是上一次进入的收尾——嵌套在外层循环里时,内层每次进来
|
||||
* 重新数,和循环卡片上「第几轮」同一个口径。审批恢复的重放不算又跑了一次
|
||||
*/
|
||||
function loopsOf(n: NodeTrace | undefined, at: number | null): number {
|
||||
if (!n) return 0
|
||||
let runs = 0
|
||||
for (let i = n.segments.length - 1; i >= 0; i -= 1) {
|
||||
const s = n.segments[i]
|
||||
if (s.kind !== 'run' || s.resumed || (at != null && s.start > at)) continue
|
||||
if (s.handle === 'done' && runs > 0) break
|
||||
runs += 1
|
||||
}
|
||||
return applyDerived({ ...t, phase: proj.phase, nodes }, graph)
|
||||
return Math.max(0, runs - 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行中点了一个跑过的节点:右栏滚到它的步骤。右栏归助手面板,它接这个事件
|
||||
* (在对话层时先切到运行层),接了就 preventDefault;没人接时自己找步骤行描一圈
|
||||
*/
|
||||
function revealStep(nodeId: string): void {
|
||||
const runId = useStudio.getState().run?.id
|
||||
const handled = !window.dispatchEvent(new CustomEvent('agentlab:reveal-step', {
|
||||
detail: { runId, nodeId }, cancelable: true,
|
||||
}))
|
||||
if (handled) return
|
||||
const rows = document.querySelectorAll<HTMLElement>(`[data-step-status][data-node-id="${CSS.escape(nodeId)}"]`)
|
||||
const row = rows[rows.length - 1]
|
||||
if (!row) return
|
||||
row.scrollIntoView({ block: 'center', behavior: reducedMotion() ? 'auto' : 'smooth' })
|
||||
row.dataset.flash = 'focus'
|
||||
setTimeout(() => { if (row.dataset.flash === 'focus') delete row.dataset.flash }, 1800)
|
||||
}
|
||||
|
||||
/** 每条边此刻的运行态 */
|
||||
@@ -211,6 +230,160 @@ const typeColor = (n: { data?: unknown }): string => {
|
||||
return type ? `var(--nt-${type})` : 'var(--text-faint)'
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Copilot 这一轮删掉的节点:原地留一道虚线框,停一下再淡出
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** 虚线框停留的总时长,和 surface.css 里 sf-ghost-out 的时长一致 */
|
||||
const GHOST_MS = 2400
|
||||
|
||||
interface Ghost {
|
||||
id: string
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
label: string
|
||||
type: NodeType
|
||||
}
|
||||
|
||||
const ghostOf = (n: FlowNode): Ghost => ({
|
||||
id: n.id, x: n.position.x, y: n.position.y,
|
||||
w: n.measured?.width ?? NODE_WIDTH, h: n.measured?.height ?? 80,
|
||||
label: n.data.label || NODE_DEFS[n.data.nodeType]?.label || n.id, type: n.data.nodeType,
|
||||
})
|
||||
|
||||
/**
|
||||
* 助手改完图,新加的节点有入场、改过的有标记,删掉的却是一声不响就没了——回执写着
|
||||
* 「删除 1」,画布上看不出删的是哪一个、原来在哪。在它原来的位置画一道虚线框、
|
||||
* 写上名字,停两秒淡出。只由这一轮落定触发、只播一次;关了动效就不画(回执里照样写着)
|
||||
*/
|
||||
function useRemovedGhosts(): { seq: number; items: Ghost[] } | null {
|
||||
const [ghosts, setGhosts] = useState<{ seq: number; items: Ghost[] } | null>(null)
|
||||
useEffect(() => {
|
||||
// 这一轮开始前的样子:删掉的节点可能在流式途中就没了,落定时 store 里已经找不到
|
||||
let before = new Map<string, Ghost>()
|
||||
let timer = 0
|
||||
const unsub = useStudio.subscribe((s, prev) => {
|
||||
if (s.copilot.active && !prev.copilot.active) before = new Map(prev.nodes.map((n) => [n.id, ghostOf(n)]))
|
||||
if (s.copilotTurns === prev.copilotTurns) return
|
||||
const turn = s.copilotTurns[s.copilotTurns.length - 1]
|
||||
if (!turn || turn.phase !== 'done' || turn.outcome !== 'applied') return
|
||||
if (prev.copilotTurns.find((t) => t.id === turn.id)?.phase === 'done') return
|
||||
const items = (turn.diff?.removed ?? []).flatMap((id) => before.get(id) ?? [])
|
||||
before = new Map()
|
||||
if (!items.length || reducedMotion()) return
|
||||
clearTimeout(timer)
|
||||
setGhosts((g) => ({ seq: (g?.seq ?? 0) + 1, items }))
|
||||
timer = window.setTimeout(() => setGhosts(null), GHOST_MS)
|
||||
})
|
||||
return () => {
|
||||
unsub()
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [])
|
||||
return ghosts
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 双击空白处快速添加:在光标处搜类型、回车放下。和节点库读同一份节点定义
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
const QUICK_W = 248
|
||||
const QUICK_H = 312
|
||||
|
||||
function QuickAdd({ x, y, bounds, onPick, onClose }: {
|
||||
/** 双击处,相对画布容器的像素 */
|
||||
x: number
|
||||
y: number
|
||||
bounds: { w: number; h: number }
|
||||
onPick: (type: NodeType) => void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [cur, setCur] = useState(0)
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
const defs = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
// 按节点库的分组顺序排;搜的时候名字里有的排在只是说明里提到的前面——搜「分」
|
||||
// 要的是「条件分支」,不是说明里写着「分派」的协作节点
|
||||
const all = NODE_CATEGORIES.flatMap((c) => Object.values(NODE_DEFS).filter((d) => d.category === c))
|
||||
if (!q) return all
|
||||
const named = (d: NodeDef) => d.label.toLowerCase().includes(q) || d.type.includes(q)
|
||||
return [...all.filter(named), ...all.filter((d) => !named(d) && d.description.toLowerCase().includes(q))]
|
||||
}, [query])
|
||||
const at = Math.min(cur, Math.max(0, defs.length - 1))
|
||||
const listId = useId()
|
||||
|
||||
// 点到外面就收起;它是个一次性的小面板,不该留在那儿挡画布
|
||||
useEffect(() => {
|
||||
const onDown = (e: PointerEvent) => { if (!box.current?.contains(e.target as Node)) onClose() }
|
||||
document.addEventListener('pointerdown', onDown, true)
|
||||
return () => document.removeEventListener('pointerdown', onDown, true)
|
||||
}, [onClose])
|
||||
useEffect(() => {
|
||||
list.current?.querySelector<HTMLElement>(`[data-i="${at}"]`)?.scrollIntoView({ block: 'nearest' })
|
||||
}, [at])
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (isComposing(e)) return
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setCur(Math.max(0, Math.min(defs.length - 1, at + (e.key === 'ArrowDown' ? 1 : -1))))
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (defs[at]) onPick(defs[at].type)
|
||||
} else if (e.key === 'Escape') {
|
||||
// 用掉这一下:别再让它去关属性面板、清运行结果
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
// 贴着光标放,放不下就往回收,不伸出画布
|
||||
const left = Math.max(8, Math.min(x, bounds.w - QUICK_W - 8))
|
||||
const top = Math.max(8, Math.min(y, bounds.h - QUICK_H - 8))
|
||||
const optId = (i: number) => `${listId}-${i}`
|
||||
return (
|
||||
<div ref={box} className="sf-quick sheet-in nodrag nopan nowheel" style={{ left, top, width: QUICK_W }}
|
||||
role="dialog" aria-label="快速添加节点" data-esc-layer onKeyDown={onKeyDown}>
|
||||
<label className="sf-quick-search">
|
||||
<Search size={12} aria-hidden />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
placeholder="添加节点:搜名字或用途"
|
||||
role="combobox"
|
||||
aria-expanded
|
||||
aria-controls={listId}
|
||||
aria-activedescendant={defs[at] ? optId(at) : undefined}
|
||||
aria-autocomplete="list"
|
||||
onChange={(e) => { setQuery(e.target.value); setCur(0) }}
|
||||
/>
|
||||
</label>
|
||||
<div className="sf-quick-list" role="listbox" id={listId} ref={list} aria-label="节点类型">
|
||||
{defs.map((d, i) => {
|
||||
const Icon = d.icon
|
||||
return (
|
||||
<div key={d.type} id={optId(i)} data-i={i} role="option" aria-selected={i === at}
|
||||
className={clsx('sf-quick-item', `nt-${d.type}`, i === at && 'is-active')}
|
||||
title={d.description}
|
||||
onPointerEnter={() => setCur(i)}
|
||||
onClick={() => onPick(d.type)}>
|
||||
<span className="sf-quick-icon"><Icon size={12} aria-hidden /></span>
|
||||
<span className="min-w-0 flex-1 truncate">{d.label}</span>
|
||||
<span className="sf-dim">{d.category}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{!defs.length && <div className="sf-quick-empty">没有叫「{query.trim()}」的节点</div>}
|
||||
</div>
|
||||
<div className="sf-quick-foot">↑↓ 选择 · ↵ 放在这里 · Esc 关闭</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function CanvasInner() {
|
||||
@@ -231,6 +404,7 @@ function CanvasInner() {
|
||||
const selectedId = useStudio((s) => s.selectedId)
|
||||
const follow = useStudio((s) => s.follow)
|
||||
const pathOnly = useDock((s) => s.pathOnly)
|
||||
const sheetOpen = useSheet((s) => s.open)
|
||||
// 动作从 getState 取:整个 useStudio() 解构会订阅全部字段,每个 token 都让画布重渲染一次
|
||||
const actions = useStudio.getState()
|
||||
|
||||
@@ -248,9 +422,10 @@ function CanvasInner() {
|
||||
const routes = useMemo(() => buildRoutes(nodes, edges), [nodes, edges])
|
||||
|
||||
// ---- 此刻(实时或回放游标那一刻)的航迹 ----
|
||||
// graph 直接用 store 里的 nodes / edges 数组:卡片那边按同样的引用取,缓存才对得上
|
||||
const view = useMemo(() => {
|
||||
if (replayAt == null) return { trace, phase: runPhase, flowing: activeEdges }
|
||||
const t = replayTrace(trace, replayAt, graph)
|
||||
const t = replayTraceCached(trace, replayAt, graph)
|
||||
return { trace: t, phase: t.phase, flowing: activeEdgesOf(t, graph) }
|
||||
}, [trace, runPhase, activeEdges, replayAt, graph])
|
||||
|
||||
@@ -307,10 +482,9 @@ function CanvasInner() {
|
||||
return edges.map((e) => {
|
||||
const state = edgeStates.get(e.id) ?? 'idle'
|
||||
const back = topo.back.has(edgeKey(e))
|
||||
const target = view.trace.nodes[e.target]
|
||||
const sf: EdgeView = {
|
||||
state, back, rank: topo.rank[e.target] ?? 0,
|
||||
loops: back ? Math.max(0, target?.iteration ?? (target?.count ?? 1) - 1) : 0,
|
||||
loops: back ? loopsOf(view.trace.nodes[e.target], replayAt) : 0,
|
||||
}
|
||||
const className = clsx(
|
||||
`sf-e-${state}`,
|
||||
@@ -321,7 +495,7 @@ function CanvasInner() {
|
||||
// animated 一律关掉:React Flow 的 animated 是一条永远在走的虚线,方向和"是否真在流"都说不清
|
||||
return { ...e, type: 'flow', className, animated: false, data: { ...e.data, sf } }
|
||||
})
|
||||
}, [edges, edgeStates, topo, view.trace, hasRun, selectedId, pathView])
|
||||
}, [edges, edgeStates, topo, view.trace, replayAt, hasRun, selectedId, pathView])
|
||||
|
||||
// ---- 节点:注入拓扑层级(一次性时刻按它错开),只看执行路径时压暗没走的 ----
|
||||
// 按原节点对象缓存:拖一个节点只换那一个的副本,其余卡片的 data 引用不变,memo 生效
|
||||
@@ -385,6 +559,15 @@ function CanvasInner() {
|
||||
})
|
||||
}, [rfStore, applyZoom])
|
||||
|
||||
// ---- 取景 ----
|
||||
/**
|
||||
* 正在飞的那一次程序取景(跟随、点名定位、Copilot 跟镜头)。画布尺寸恰好在
|
||||
* 半路变了(运行一开始航迹坞就升起来)时,下面的保持中心会打断它;这里记着
|
||||
* 目标,打断之后重新飞一次,不然镜头停在半路、要看的节点还在视口外
|
||||
*/
|
||||
const flight = useRef<{ ids: string[]; zoomAtLeast?: number; until: number } | null>(null)
|
||||
const retarget = useRef<(() => void) | null>(null)
|
||||
|
||||
// 画布尺寸变了(航迹坞出现、变量抽屉挤进来)时保持视口中心不动。React Flow
|
||||
// 默认钉住左上角,坞一升起来,画面下半截的节点就被它盖住了
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
@@ -398,6 +581,7 @@ function CanvasInner() {
|
||||
if (last.w && last.h && (w !== last.w || h !== last.h)) {
|
||||
const { x, y, zoom } = getViewport()
|
||||
void setViewport({ x: x + (w - last.w) / 2, y: y + (h - last.h) / 2, zoom })
|
||||
if (flight.current && Date.now() < flight.current.until) requestAnimationFrame(() => retarget.current?.())
|
||||
}
|
||||
last = { w, h }
|
||||
})
|
||||
@@ -405,7 +589,6 @@ function CanvasInner() {
|
||||
return () => ro.disconnect()
|
||||
}, [getViewport, setViewport])
|
||||
|
||||
// ---- 取景 ----
|
||||
const pausedUntil = useRef(0)
|
||||
/**
|
||||
* 人手动平移、缩放的那一下:开始时记下视口,结束时真的动过才让跟随让路。
|
||||
@@ -426,7 +609,7 @@ function CanvasInner() {
|
||||
/**
|
||||
* 打开一张图时的取景。整图放得下、缩放不低于可读下限就整图居中;放不下就
|
||||
* 不再硬塞——以入口为左锚、按可读缩放只取前几列,其余交给小地图。以前一律
|
||||
* 整图塞进来,12 节点的图缩到 0.2,标题只剩 3px。
|
||||
* 整图塞进来,12 节点的图缩到 0.2,标题只剩 3px。窄画布另有一档,见下面 narrow。
|
||||
*/
|
||||
const frame = useCallback((duration: number) => {
|
||||
const el = rf.current
|
||||
@@ -442,16 +625,26 @@ function CanvasInner() {
|
||||
void fitView({ padding: 0.12, maxZoom: 1.1, minZoom: READABLE_ZOOM, duration, interpolate: LINEAR })
|
||||
return
|
||||
}
|
||||
// 按列聚类,取前四列的跨度定缩放
|
||||
// 按列聚类
|
||||
const xs = [...new Set(all.map((n) => Math.round(n.position.x)))].sort((a, b) => a - b)
|
||||
const cols: number[] = []
|
||||
for (const x of xs) if (!cols.length || x - cols[cols.length - 1] > 60) cols.push(x)
|
||||
const firstCols = cols.slice(0, 4)
|
||||
const span = (firstCols[firstCols.length - 1] ?? bounds.x) + NODE_WIDTH - bounds.x
|
||||
let zoom = Math.min(1, Math.max(READABLE_ZOOM, (W - 2 * PAD) / Math.max(span, NODE_WIDTH)))
|
||||
const spanOf = (k: number) => (cols[Math.min(k, cols.length) - 1] ?? bounds.x) + NODE_WIDTH - bounds.x
|
||||
// 窄画布(1024 宽、两边栏都开着时只剩五百来 px):可读缩放下连前三列都放不下,
|
||||
// 打开只看得见两张半卡片。这时退到精简档:整张图放得下就看全图,放不下就多看几列。
|
||||
// 宽画布照旧按可读缩放——精简卡没有摘要和遥测,能看清就不该让人先放大一次
|
||||
const narrow = cols.length >= 3 && spanOf(3) * READABLE_ZOOM > W - 2 * PAD
|
||||
if (narrow && fit >= COMPACT_ZOOM) {
|
||||
void fitView({ padding: 0.12, maxZoom: READABLE_ZOOM, minZoom: COMPACT_ZOOM, duration, interpolate: LINEAR })
|
||||
return
|
||||
}
|
||||
// 取前四列的跨度定缩放
|
||||
let zoom = narrow
|
||||
? Math.max(COMPACT_ZOOM, Math.min(READABLE_ZOOM, (W - 2 * PAD) / spanOf(4)))
|
||||
: Math.min(1, Math.max(READABLE_ZOOM, (W - 2 * PAD) / Math.max(spanOf(4), NODE_WIDTH)))
|
||||
// 竖直方向放得下就别再放大:宁可多看几列
|
||||
const vfit = (H - 2 * PAD) / bounds.height
|
||||
if (vfit >= READABLE_ZOOM) zoom = Math.min(zoom, vfit)
|
||||
if (vfit >= (narrow ? COMPACT_ZOOM : READABLE_ZOOM)) zoom = Math.min(zoom, vfit)
|
||||
const entries = all.filter((n) => (n.data as FlowNode['data']).nodeType === 'input')
|
||||
const anchor = entries[0] ?? all.reduce((a, b) => (a.position.x <= b.position.x ? a : b))
|
||||
const anchorH = anchor.measured?.height ?? 80
|
||||
@@ -511,9 +704,15 @@ function CanvasInner() {
|
||||
const fits = (maxX - minX) * z <= el.clientWidth - 2 * M && (maxY - minY) * z <= el.clientHeight - 2 * M
|
||||
const target = fits ? { cx: (minX + maxX) / 2, cy: (minY + maxY) / 2 }
|
||||
: { cx: rects[0].x + rects[0].w / 2, cy: rects[0].y + rects[0].h / 2 }
|
||||
void setCenter(target.cx, target.cy, { zoom: z, duration: reducedMotion() ? 0 : 320, interpolate: LINEAR })
|
||||
const duration = reducedMotion() ? 0 : 320
|
||||
flight.current = { ids, zoomAtLeast: opts.zoomAtLeast, until: Date.now() + duration + 80 }
|
||||
void setCenter(target.cx, target.cy, { zoom: z, duration, interpolate: LINEAR })
|
||||
return true
|
||||
}, [getInternalNode, getViewport, setCenter])
|
||||
retarget.current = () => {
|
||||
const f = flight.current
|
||||
if (f) bringIntoView(f.ids, { force: true, zoomAtLeast: f.zoomAtLeast })
|
||||
}
|
||||
|
||||
// 跟随执行:有节点实时开跑、而它在视口外时平移过去。只由 node.started 驱动,
|
||||
// 不新增任何动画循环;同一帧里一起开跑的并成一次
|
||||
@@ -541,6 +740,31 @@ function CanvasInner() {
|
||||
}
|
||||
}, [bringIntoView])
|
||||
|
||||
// Copilot 搭图时镜头跟着它刚动过的节点:落在视口外就平移过去,不改缩放(新节点
|
||||
// 本来就落在上游旁边或视口中心附近的空地上)。人一旦手动平移、缩放,这一轮就不再跟;
|
||||
// 节点还在滑向落点时每帧都会变,飞行途中不重新起飞,免得镜头追着它抖
|
||||
const copilotOff = useRef(false)
|
||||
useEffect(() => {
|
||||
let raf = 0
|
||||
const unsub = useStudio.subscribe((s, prev) => {
|
||||
if (s.copilot.active && !prev.copilot.active) copilotOff.current = false
|
||||
if (!s.copilot.active || !s.copilotCursor || copilotOff.current) return
|
||||
if (s.copilotCursor === prev.copilotCursor && s.nodes === prev.nodes) return
|
||||
if (raf) return
|
||||
raf = requestAnimationFrame(() => {
|
||||
raf = 0
|
||||
const st = useStudio.getState()
|
||||
if (!st.copilot.active || !st.copilotCursor || copilotOff.current || userMove.current) return
|
||||
if (flight.current && Date.now() < flight.current.until) return
|
||||
bringIntoView([st.copilotCursor])
|
||||
})
|
||||
})
|
||||
return () => {
|
||||
unsub()
|
||||
cancelAnimationFrame(raf)
|
||||
}
|
||||
}, [bringIntoView])
|
||||
|
||||
// 右栏、时间轴、胶囊请求取景:点名要看它,就算已在视口里也居中一下。
|
||||
// focusRequest 每次请求都是新对象(seq +1),同一个节点连点两次也会再取景
|
||||
useEffect(() => {
|
||||
@@ -585,6 +809,41 @@ function CanvasInner() {
|
||||
[actions, screenToFlowPosition, formalLock],
|
||||
)
|
||||
|
||||
const ghosts = useRemovedGhosts()
|
||||
|
||||
// ---- 双击空白处快速添加 ----
|
||||
const [quick, setQuick] = useState<{ x: number; y: number; flow: { x: number; y: number } } | null>(null)
|
||||
const closeQuick = useCallback(() => setQuick(null), [])
|
||||
const onPaneDoubleClick = (e: React.MouseEvent) => {
|
||||
if (!(e.target as Element).classList?.contains('react-flow__pane')) return
|
||||
if (formalLock) {
|
||||
toast.warn('正式运行进行中,画布只读。等它结束再改')
|
||||
return
|
||||
}
|
||||
if (useStudio.getState().copilot.active) {
|
||||
toast.info('助手正在改这张图,等这一轮结束再加节点')
|
||||
return
|
||||
}
|
||||
const r = box.current?.getBoundingClientRect()
|
||||
if (!r) return
|
||||
setQuick({ x: e.clientX - r.left, y: e.clientY - r.top, flow: screenToFlowPosition({ x: e.clientX, y: e.clientY }) })
|
||||
}
|
||||
const pickQuick = (type: NodeType) => {
|
||||
const at = quick?.flow
|
||||
setQuick(null)
|
||||
// 双击处是卡片的中心,不是左上角
|
||||
if (at) actions.addNode(type, { x: at.x - NODE_WIDTH / 2, y: at.y - 40 })
|
||||
}
|
||||
|
||||
// ---- 运行中点节点:先看它的步骤,属性面板是次级入口 ----
|
||||
// 看运行(进行中或回放)时点了跑过的节点,属性面板不自动盖上右栏(见 InspectorSheet);
|
||||
// 这里给一个明确的入口,双击节点也能开
|
||||
// 选中了却没开面板,只会是「先看步骤」那条路。运行结束后它照样留着:不然节点选中着、
|
||||
// 面板没开、入口也没了
|
||||
const peekId = selectedId && sheetOpen !== selectedId ? selectedId : null
|
||||
const peekNode = peekId ? nodes.find((n) => n.id === peekId) : undefined
|
||||
const peekLabel = peekNode ? peekNode.data.label || NODE_DEFS[peekNode.data.nodeType]?.label || peekNode.id : ''
|
||||
|
||||
const rootStyle = useMemo(
|
||||
() => (moment?.kind === 'failed' ? { '--moment-origin': moment.origin } as CSSProperties : undefined),
|
||||
[moment],
|
||||
@@ -619,22 +878,42 @@ function CanvasInner() {
|
||||
onNodesChange={actions.onNodesChange}
|
||||
onEdgesChange={actions.onEdgesChange}
|
||||
onConnect={actions.onConnect}
|
||||
onNodeClick={(_, node) => actions.select(node.id)}
|
||||
onNodeClick={(_, node) => {
|
||||
if (!stepsFirst(node.id)) {
|
||||
// 点的是已经选中、面板却没开的节点(先看过步骤、运行随后结束了):
|
||||
// 选中不变就不会触发面板的订阅,这里直接点名打开
|
||||
openInspector(node.id)
|
||||
return
|
||||
}
|
||||
actions.select(node.id)
|
||||
revealStep(node.id)
|
||||
}}
|
||||
onNodeDoubleClick={(_, node) => openInspector(node.id)}
|
||||
onPaneClick={() => actions.select(null)}
|
||||
onDoubleClick={onPaneDoubleClick}
|
||||
zoomOnDoubleClick={false}
|
||||
onNodeMouseEnter={(_, node) => { if (hasRun) useDock.getState().set({ canvasHover: node.id }) }}
|
||||
onNodeMouseLeave={() => { if (hasRun) useDock.getState().set({ canvasHover: null }) }}
|
||||
onMoveStart={(event, vp) => {
|
||||
// 程序取景(跟随、聚焦)没有 event;有 event 的是人在拖、在滚轮
|
||||
if (event) userMove.current = vp
|
||||
}}
|
||||
onMoveEnd={(_, vp) => {
|
||||
onMoveEnd={(event, vp) => {
|
||||
applyZoom(vp.zoom, true)
|
||||
// 只认人手的那一下收尾。程序取景飞到一半被人抓住时,d3 先收掉那段动画,
|
||||
// React Flow 却把它的收尾推迟到下一拍才报——那时人的拖动已经开始,这条
|
||||
// 不带 event 的收尾要是也来结账,就把人的起点吃掉了,拖完跟随照样不暂停
|
||||
if (!event) return
|
||||
const from = userMove.current
|
||||
if (!from) return
|
||||
userMove.current = null
|
||||
const moved = Math.abs(vp.x - from.x) > 2 || Math.abs(vp.y - from.y) > 2
|
||||
|| Math.abs(vp.zoom - from.zoom) > 1e-3
|
||||
if (moved && active) pauseFollow()
|
||||
if (!moved) return
|
||||
// 人接过了镜头:程序取景不再续飞,Copilot 这一轮也不再跟
|
||||
flight.current = null
|
||||
if (useStudio.getState().copilot.active) copilotOff.current = true
|
||||
if (active) pauseFollow()
|
||||
}}
|
||||
onDrop={onDrop}
|
||||
onDragOver={(e) => {
|
||||
@@ -674,6 +953,16 @@ function CanvasInner() {
|
||||
style={{ width: 150, height: 100 }}
|
||||
ariaLabel={hasRun ? '小地图(按运行状态着色)' : '小地图'}
|
||||
/>
|
||||
{ghosts && (
|
||||
<ViewportPortal>
|
||||
{ghosts.items.map((g) => (
|
||||
<div key={`${ghosts.seq}:${g.id}`} className={clsx('sf-ghost', `nt-${g.type}`)} data-ghost={g.id}
|
||||
style={{ transform: `translate(${g.x}px, ${g.y}px)`, width: g.w, height: g.h }} aria-hidden>
|
||||
<span className="sf-ghost-tag">已删除 · {g.label}</span>
|
||||
</div>
|
||||
))}
|
||||
</ViewportPortal>
|
||||
)}
|
||||
</ReactFlow>
|
||||
</MiniStates.Provider>
|
||||
</MomentContext.Provider>
|
||||
@@ -681,7 +970,7 @@ function CanvasInner() {
|
||||
|
||||
{/* 画布顶上的浮条排成一行:跟随在左,只读横幅居中;放不下时横幅折到下一行、
|
||||
再不够就截掉说明文字。各自绝对定位的话,笔记本宽度下横幅会盖住「恢复」 */}
|
||||
{(formalLock || showFollow) && (
|
||||
{(formalLock || showFollow || peekId) && (
|
||||
<div className="sf-float">
|
||||
{showFollow && (
|
||||
<div className={clsx('sf-follow', followPaused && 'is-paused')}>
|
||||
@@ -698,6 +987,14 @@ function CanvasInner() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{peekId && (
|
||||
<button type="button" className="sf-peek" onClick={() => openInspector(peekId)}
|
||||
title="属性面板会盖住右栏的运行视图,底部那一条点一下就回来。双击节点也能打开">
|
||||
<PanelRightOpen size={11} aria-hidden />
|
||||
<span className="sf-peek-name">{peekLabel}</span>
|
||||
<span>的配置</span>
|
||||
</button>
|
||||
)}
|
||||
{formalLock && (
|
||||
<div className="sf-banner" role="status">
|
||||
<Lock size={12} />
|
||||
@@ -707,6 +1004,11 @@ function CanvasInner() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{quick && box.current && (
|
||||
<QuickAdd x={quick.x} y={quick.y} bounds={{ w: box.current.clientWidth, h: box.current.clientHeight }}
|
||||
onPick={pickQuick} onClose={closeQuick} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface EdgeView {
|
||||
back: boolean
|
||||
/** 目标节点的拓扑层级,一次性时刻按它错开 */
|
||||
rank: number
|
||||
/** 回边已经兜回去几次(循环第几轮)。0 不显示 */
|
||||
/** 回边已经兜回去几次:这一次进入循环以来,回放截到游标。0 不显示 */
|
||||
loops?: number
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { AlertTriangle, ChevronLeft, Copy, Maximize2, Plus, Trash2, X, XCircle } from 'lucide-react'
|
||||
import { AlertTriangle, ChevronLeft, Copy, Lock, Maximize2, Plus, Trash2, X, XCircle } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS, syntaxOf, type FieldDef, type FieldSyntax } from './nodeDefs'
|
||||
import { fieldOfIssue, type FieldRef } from './issues'
|
||||
import { fieldOfIssue, unboundToolOf, withToolBound, type FieldRef } from './issues'
|
||||
import { hintOf } from './shortcuts'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { isActivePhase } from '../run/trace'
|
||||
import { EDIT_LOCK_TEXT, useEditLock, useStudio } from '../store/studio'
|
||||
import { useCatalog, modelOptions } from '../store/catalog'
|
||||
import { api } from '../api/client'
|
||||
import { IconButton, JsonInput, Modal, isComposing } from '../components/ui'
|
||||
@@ -35,12 +36,61 @@ function useRunDefaults() {
|
||||
return value
|
||||
}
|
||||
|
||||
interface ToolOption { value: string; label: string; hint?: string; danger?: boolean; group?: string }
|
||||
|
||||
/**
|
||||
* 数据源的查询工具(db_query__<源> / db_schema__<源>)。/tools 的列表只有内置、自定义和 MCP,
|
||||
* 以前检查器里挑不到它们:校验说「提示词要求用 db_query__x,把它加进工具里」,界面上却做不到。
|
||||
* 30 秒内复用上一次的结果:每点一个节点都去问一遍没必要,可刚在数据页加的源也不能一直看不见
|
||||
*/
|
||||
let sourceTools: { at: number; list: Promise<ToolOption[]> } | null = null
|
||||
function useSourceTools(): ToolOption[] {
|
||||
const [value, setValue] = useState<ToolOption[]>([])
|
||||
useEffect(() => {
|
||||
if (!sourceTools || Date.now() - sourceTools.at > 30_000) {
|
||||
sourceTools = {
|
||||
at: Date.now(),
|
||||
list: api.datasources.list().then((rows) => rows
|
||||
.filter((r) => r && r.enabled !== false)
|
||||
.flatMap((r) => (Array.isArray(r.tools) ? r.tools as string[] : []).map((t) => ({
|
||||
value: t, label: t, group: '数据源',
|
||||
hint: `${t.startsWith('db_schema__') ? '查表结构' : '执行 SQL'} · 数据源「${r.name}」`,
|
||||
// 可写的源上,写语句要人确认(运行时的审批关卡认它)
|
||||
danger: t.startsWith('db_query__') && r.readonly === false,
|
||||
}))))
|
||||
.catch(() => { sourceTools = null; return [] }),
|
||||
}
|
||||
}
|
||||
let alive = true
|
||||
void sourceTools?.list.then((v) => { if (alive) setValue(v) })
|
||||
return () => { alive = false }
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
|
||||
/** 节点能绑的全部工具:目录里的,加上数据源的 */
|
||||
function useToolOptions(): ToolOption[] {
|
||||
const tools = useCatalog((s) => s.tools)
|
||||
const sources = useSourceTools()
|
||||
return useMemo(() => {
|
||||
const known = new Set(tools.map((t) => t.id))
|
||||
return [
|
||||
...tools.map((t) => ({ value: t.id, label: t.name, hint: t.description, danger: t.dangerous, group: t.category })),
|
||||
...sources.filter((o) => !known.has(o.value)),
|
||||
]
|
||||
}, [tools, sources])
|
||||
}
|
||||
|
||||
/** 属性面板。所有字段都由 nodeDefs 的声明驱动渲染,加节点类型不用改这里。 */
|
||||
export function Inspector() {
|
||||
const selectedId = useStudio((s) => s.selectedId)
|
||||
const node = useStudio((s) => s.nodes.find((n) => n.id === s.selectedId))
|
||||
const allIssues = useStudio((s) => s.issues)
|
||||
const locked = useStudio((s) => s.copilot.active)
|
||||
// 助手在改、正式运行在跑:整块只读,说清为什么
|
||||
const lock = useEditLock()
|
||||
const locked = lock != null
|
||||
// 运行中(探索运行也算)不删节点:画布那边同样关了删除键,事件会对到一个已经不在的节点上
|
||||
const running = useStudio((s) => isActivePhase(s.runPhase))
|
||||
const runtime = useStudio((s) => (selectedId ? s.runtime[selectedId] : undefined))
|
||||
// 动作逐个取:不带选择器的 useStudio() 订阅整个 store,运行时每来一个 token 这块面板都要重渲染
|
||||
const updateNode = useStudio((s) => s.updateNode)
|
||||
@@ -96,12 +146,24 @@ export function Inspector() {
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-semibold">{def.label}</span>
|
||||
<IconButton label="复制节点" title={hintOf('复制一份', 'duplicate')} disabled={locked}
|
||||
onClick={() => duplicateNode(node.id)} icon={<Copy size={12} />} />
|
||||
<IconButton label="删除节点" title={`${hintOf('删除节点', 'delete')} · 可撤销`} disabled={locked}
|
||||
<IconButton label="删除节点" disabled={locked || running}
|
||||
title={running && !locked ? '运行中不能删节点:等它结束或者先停下' : `${hintOf('删除节点', 'delete')} · 可撤销`}
|
||||
onClick={() => removeNode(node.id)} icon={<Trash2 size={12} className="text-[var(--err)]" />} />
|
||||
</Header>
|
||||
|
||||
{/* 助手改图期间整块只读:这时候改的东西会被它的最终结果悄悄覆盖 */}
|
||||
{/* 助手改图、正式运行期间整块只读:前者改的东西会被它的最终结果悄悄覆盖,后者跑的是
|
||||
已发布的不可变版本 */}
|
||||
<fieldset disabled={locked} className="min-h-0 min-w-0 flex-1 overflow-y-auto p-3">
|
||||
{lock && (
|
||||
<div className="mb-3 flex items-start gap-1.5 rounded border px-2 py-1.5 text-2xs leading-snug"
|
||||
role="note" style={{ borderColor: 'var(--border-strong)', background: 'var(--bg-hover)' }}>
|
||||
<Lock size={11} className="mt-px shrink-0 text-dim" aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="font-medium">只能看,不能改</span>
|
||||
<span className="text-dim"> · {EDIT_LOCK_TEXT[lock]}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-3 text-2xs leading-relaxed text-faint">{def.description}</div>
|
||||
|
||||
{!!loose.length && (
|
||||
@@ -182,8 +244,10 @@ function Header({ onBack, children }: { onBack: () => void; children?: React.Rea
|
||||
)
|
||||
}
|
||||
|
||||
/** 一条问题。字段下面用行内版,面板顶部用带框的版本 */
|
||||
function IssueLine({ issue, boxed }: { issue: Pick<ValidationIssue, 'level' | 'message'>; boxed?: boolean }) {
|
||||
/** 一条问题。字段下面用行内版,面板顶部用带框的版本。action 是就地修好它的那个按钮 */
|
||||
function IssueLine({ issue, boxed, action }: {
|
||||
issue: Pick<ValidationIssue, 'level' | 'message'>; boxed?: boolean; action?: React.ReactNode
|
||||
}) {
|
||||
const err = issue.level === 'error'
|
||||
const Icon = err ? XCircle : AlertTriangle
|
||||
return (
|
||||
@@ -196,11 +260,30 @@ function IssueLine({ issue, boxed }: { issue: Pick<ValidationIssue, 'level' | 'm
|
||||
role={err ? 'alert' : undefined}
|
||||
>
|
||||
<Icon size={11} className="mt-px shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1">{issue.message}</span>
|
||||
{/* 修法放在话的下面:检查器只有三百来像素宽,并排的话这句要折成七八行 */}
|
||||
<span className="min-w-0 flex-1">
|
||||
{issue.message}
|
||||
{action && <span className="mt-1 flex">{action}</span>}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 「提示词要求用 X,但没绑定」的就地修法:把 X 加进这一栏。返回新 config,已经绑了就是 null
|
||||
* (按钮不出现)。修法和问题面板那一行的「绑定」是同一个 withToolBound
|
||||
*/
|
||||
function bindFix(issue: FieldIssue, config: Record<string, any>, apply: (next: Record<string, any>) => void) {
|
||||
const tool = unboundToolOf(issue.message)
|
||||
const next = tool ? withToolBound(config, issue.at, tool) : null
|
||||
if (!tool || !next) return null
|
||||
return (
|
||||
<button type="button" className="btn btn-xs shrink-0" onClick={() => apply(next)}>
|
||||
<Plus size={10} aria-hidden /> 绑定 {tool}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -268,7 +351,7 @@ function Field({ field, nodeId, value, config, issues, onChange }: {
|
||||
)}
|
||||
{!!own.length && (
|
||||
<div id={errorId} className="mt-1 space-y-0.5">
|
||||
{own.map((i, k) => <IssueLine key={k} issue={i} />)}
|
||||
{own.map((i, k) => <IssueLine key={k} issue={i} action={bindFix(i, config, (c) => onChange(c[field.key]))} />)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -282,6 +365,7 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
|
||||
}) {
|
||||
const catalog = useCatalog()
|
||||
const defaults = useRunDefaults()
|
||||
const toolOptions = useToolOptions()
|
||||
const aria = { 'aria-invalid': invalid || undefined, 'aria-describedby': describedBy }
|
||||
|
||||
switch (field.type) {
|
||||
@@ -401,9 +485,7 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
|
||||
)
|
||||
|
||||
case 'tools': {
|
||||
const options = catalog.tools.map((t) => ({
|
||||
value: t.id, label: t.name, hint: t.description, danger: t.dangerous, group: t.category,
|
||||
}))
|
||||
const options = toolOptions
|
||||
// tool 节点只选一个,agent 节点可以多选
|
||||
if (field.help?.includes('只能选一个')) {
|
||||
return (
|
||||
@@ -437,7 +519,7 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
|
||||
return <MetricList nodeId={nodeId} value={value ?? []} issues={issues} onChange={onChange} />
|
||||
|
||||
case 'agents':
|
||||
return <AgentList value={value ?? []} onChange={onChange} />
|
||||
return <AgentList value={value ?? []} issues={issues} config={config} onChange={onChange} />
|
||||
|
||||
default:
|
||||
return <input id={id} className="field" value={value ?? ''} onChange={(e) => onChange(e.target.value)} />
|
||||
@@ -608,12 +690,14 @@ function MultiPick({ options, value, onChange, empty }: {
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ children, onRemove, removeLabel, tone }: {
|
||||
function Row({ children, onRemove, removeLabel, tone, item }: {
|
||||
children: React.ReactNode; onRemove: () => void; removeLabel: string
|
||||
tone?: 'error' | 'warning'
|
||||
/** 第几项。问题面板定位时按 [data-field] [data-item] 滚到这一项 */
|
||||
item?: number
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-1.5 rounded border bg-bg p-2"
|
||||
<div className="mb-1.5 rounded border bg-bg p-2" data-item={item}
|
||||
style={tone ? { borderColor: tone === 'error' ? 'var(--err)' : 'var(--warn)' } : undefined}>
|
||||
<div className="flex items-start gap-1.5">
|
||||
<div className="min-w-0 flex-1 space-y-1.5">{children}</div>
|
||||
@@ -653,7 +737,7 @@ function IoFieldList({ nodeId, value, issues, onChange }: {
|
||||
{value.map((field, i) => {
|
||||
const own = issues.filter((x) => x.at?.index === i)
|
||||
return (
|
||||
<Row key={i} removeLabel={`删除字段 ${field.name || i + 1}`}
|
||||
<Row key={i} item={i} removeLabel={`删除字段 ${field.name || i + 1}`}
|
||||
tone={own.some((x) => x.level === 'error') ? 'error' : own.length ? 'warning' : undefined}
|
||||
onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<Sub label="字段名" htmlFor={`${uid}-${i}-name`}>
|
||||
@@ -775,7 +859,7 @@ function CaseList({ nodeId, mode, value, issues, onChange }: {
|
||||
: keyIssue || own.length ? 'warning' : undefined
|
||||
const condBad = own.some((x) => x.at?.sub === 'condition' && x.level === 'error')
|
||||
return (
|
||||
<Row key={i} removeLabel={`删除分支 ${c.label || c.key || i + 1}`} tone={tone}
|
||||
<Row key={i} item={i} removeLabel={`删除分支 ${c.label || c.key || i + 1}`} tone={tone}
|
||||
onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<div className="flex gap-1.5">
|
||||
<Sub label="标识(连线出口)" htmlFor={`${uid}-${i}-key`} className="w-[42%] shrink-0">
|
||||
@@ -848,7 +932,7 @@ function MetricList({ nodeId, value, issues, onChange }: {
|
||||
{value.map((m, i) => {
|
||||
const own = issues.filter((x) => x.at?.index === i)
|
||||
return (
|
||||
<Row key={i} removeLabel={`删除指标 ${m.id || i + 1}`}
|
||||
<Row key={i} item={i} removeLabel={`删除指标 ${m.id || i + 1}`}
|
||||
tone={own.some((x) => x.level === 'error') ? 'error' : own.length ? 'warning' : undefined}
|
||||
onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<div className="flex gap-1.5">
|
||||
@@ -886,45 +970,65 @@ function MetricList({ nodeId, value, issues, onChange }: {
|
||||
)
|
||||
}
|
||||
|
||||
function AgentList({ value, onChange }: { value: any[]; onChange: (v: any[]) => void }) {
|
||||
const catalog = useCatalog()
|
||||
/**
|
||||
* 协作成员。成员自己的问题(提示词点名的工具没绑、角色设定写得不对)落在那个成员的那一栏下面:
|
||||
* 以前它们既不在成员行里、也不在面板顶上,问题面板说有错,点过来却什么都看不见
|
||||
*/
|
||||
function AgentList({ value, issues, config, onChange }: {
|
||||
value: any[]; issues: FieldIssue[]; config: Record<string, any>; onChange: (v: any[]) => void
|
||||
}) {
|
||||
const options = useToolOptions()
|
||||
const uid = useId()
|
||||
const update = (i: number, patch: any) =>
|
||||
onChange(value.map((a, idx) => (idx === i ? { ...a, ...patch } : a)))
|
||||
const fix = (x: FieldIssue) => bindFix(x, config, (c) => onChange(c.agents))
|
||||
return (
|
||||
<div>
|
||||
{value.map((agent, i) => (
|
||||
<Row key={i} removeLabel={`删除成员 ${agent.name || i + 1}`}
|
||||
onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<div className="flex gap-1.5">
|
||||
<Sub label="成员名(英文)" htmlFor={`${uid}-${i}-name`} className="min-w-0 flex-1">
|
||||
<input id={`${uid}-${i}-name`} className="field mono text-xs" placeholder="researcher"
|
||||
value={agent.name ?? ''} onChange={(e) => update(i, { name: e.target.value })} />
|
||||
{value.map((agent, i) => {
|
||||
const own = issues.filter((x) => x.at?.index === i)
|
||||
const at = (sub: string) => own.filter((x) => x.at?.sub === sub)
|
||||
const rest = own.filter((x) => x.at?.sub !== 'system' && x.at?.sub !== 'tools')
|
||||
return (
|
||||
<Row key={i} item={i} removeLabel={`删除成员 ${agent.name || i + 1}`}
|
||||
tone={own.some((x) => x.level === 'error') ? 'error' : own.length ? 'warning' : undefined}
|
||||
onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<div className="flex gap-1.5">
|
||||
<Sub label="成员名(英文)" htmlFor={`${uid}-${i}-name`} className="min-w-0 flex-1">
|
||||
<input id={`${uid}-${i}-name`} className="field mono text-xs" placeholder="researcher"
|
||||
value={agent.name ?? ''} onChange={(e) => update(i, { name: e.target.value })} />
|
||||
</Sub>
|
||||
<Sub label="最多几步" htmlFor={`${uid}-${i}-steps`} className="w-20 shrink-0">
|
||||
<input id={`${uid}-${i}-steps`} className="field tnum" type="number" min={1} max={30} placeholder="4"
|
||||
value={agent.max_steps ?? ''}
|
||||
onChange={(e) => update(i, { max_steps: e.target.value === '' ? undefined : Number(e.target.value) })} />
|
||||
</Sub>
|
||||
</div>
|
||||
<Sub label="职责(调度者据此分派)" htmlFor={`${uid}-${i}-desc`}>
|
||||
<input id={`${uid}-${i}-desc`} className="field" value={agent.description ?? ''}
|
||||
onChange={(e) => update(i, { description: e.target.value })} />
|
||||
</Sub>
|
||||
<Sub label="最多几步" htmlFor={`${uid}-${i}-steps`} className="w-20 shrink-0">
|
||||
<input id={`${uid}-${i}-steps`} className="field tnum" type="number" min={1} max={30} placeholder="4"
|
||||
value={agent.max_steps ?? ''}
|
||||
onChange={(e) => update(i, { max_steps: e.target.value === '' ? undefined : Number(e.target.value) })} />
|
||||
</Sub>
|
||||
</div>
|
||||
<Sub label="职责(调度者据此分派)" htmlFor={`${uid}-${i}-desc`}>
|
||||
<input id={`${uid}-${i}-desc`} className="field" value={agent.description ?? ''}
|
||||
onChange={(e) => update(i, { description: e.target.value })} />
|
||||
</Sub>
|
||||
{/* 成员的 system 后端直接取值、不过模板渲染:这里不挂补全,免得教人写 {{ }} */}
|
||||
<Sub label="角色设定(system,原样发给模型)" htmlFor={`${uid}-${i}-sys`}>
|
||||
<textarea id={`${uid}-${i}-sys`} className="field" rows={2}
|
||||
value={agent.system ?? ''} onChange={(e) => update(i, { system: e.target.value })} />
|
||||
</Sub>
|
||||
<div>
|
||||
<div className="mb-0.5 text-2xs text-faint">可用工具</div>
|
||||
<MultiPick
|
||||
options={catalog.tools.map((t) => ({ value: t.id, label: t.name, hint: t.description, group: t.category }))}
|
||||
value={agent.tools ?? []} onChange={(v) => update(i, { tools: v })} empty="没有可用工具"
|
||||
/>
|
||||
</div>
|
||||
</Row>
|
||||
))}
|
||||
{/* 成员的 system 后端直接取值、不过模板渲染:这里不挂补全,免得教人写 {{ }} */}
|
||||
<div data-sub="system">
|
||||
<Sub label="角色设定(system,原样发给模型)" htmlFor={`${uid}-${i}-sys`}>
|
||||
<textarea id={`${uid}-${i}-sys`} className="field" rows={2}
|
||||
value={agent.system ?? ''} onChange={(e) => update(i, { system: e.target.value })} />
|
||||
</Sub>
|
||||
{at('system').map((x, k) => <IssueLine key={k} issue={x} />)}
|
||||
</div>
|
||||
<div data-sub="tools">
|
||||
<div className="mb-0.5 text-2xs text-faint">可用工具</div>
|
||||
<MultiPick options={options} value={agent.tools ?? []} onChange={(v) => update(i, { tools: v })}
|
||||
empty="没有可用工具" />
|
||||
{!!at('tools').length && (
|
||||
<div className="mt-1 space-y-0.5">
|
||||
{at('tools').map((x, k) => <IssueLine key={k} issue={x} action={fix(x)} />)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{rest.map((x, k) => <IssueLine key={k} issue={x} />)}
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
<button type="button" className="btn btn-sm w-full justify-center"
|
||||
onClick={() => onChange([...value, { name: '', description: '', system: '', tools: [] }])}>
|
||||
<Plus size={11} /> 添加成员
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect } from 'react'
|
||||
import { ChevronLeft } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { create } from 'zustand'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { StatusBadge } from '../components/ui'
|
||||
import { formatClock } from '../lib/format'
|
||||
@@ -10,6 +11,45 @@ import { useRunGlance } from '../run/RunHud'
|
||||
import { isActivePhase } from '../run/trace'
|
||||
import { Inspector } from './Inspector'
|
||||
|
||||
type StudioSnapshot = ReturnType<typeof useStudio.getState>
|
||||
|
||||
/**
|
||||
* 属性面板此刻为哪个节点开着。选中节点不再一律等于打开:看运行时点了跑过的节点,
|
||||
* 右栏要留给那个节点的步骤(runfx-11),面板等人明确要了才盖上来。
|
||||
*/
|
||||
export const useSheet = create<{ open: string | null }>(() => ({ open: null }))
|
||||
|
||||
/**
|
||||
* 点这个节点是不是应该先看它的步骤:在看运行(进行中,或者在回放),而它这次
|
||||
* 跑过——没跑过的节点在右栏里没有步骤可看,那就照常打开属性面板
|
||||
*/
|
||||
export function stepsFirst(id: string, s: StudioSnapshot = useStudio.getState()): boolean {
|
||||
if (!isActivePhase(s.runPhase) && s.replayAt == null) return false
|
||||
const n = s.trace.nodes[id]
|
||||
return !!n && (n.count > 0 || n.state !== 'idle')
|
||||
}
|
||||
|
||||
/** 明确要看配置(双击节点、画布上的「…的配置」):运行中也打开 */
|
||||
export function openInspector(id: string): void {
|
||||
// 先记下再选中:选中触发的订阅看到它已经点名要开,就不再按「先看步骤」收回去
|
||||
useSheet.setState({ open: id })
|
||||
useStudio.getState().select(id)
|
||||
}
|
||||
|
||||
// 选中 → 面板开不开。放在模块级:选中可能来自别处(问题面板定位、发布弹窗、快捷键),
|
||||
// 规则只写这一份
|
||||
useStudio.subscribe((s, prev) => {
|
||||
if (s.selectedId === prev.selectedId) return
|
||||
const id = s.selectedId
|
||||
const cur = useSheet.getState().open
|
||||
if (!id) {
|
||||
if (cur) useSheet.setState({ open: null })
|
||||
return
|
||||
}
|
||||
if (cur === id) return
|
||||
useSheet.setState({ open: stepsFirst(id, s) ? null : id })
|
||||
})
|
||||
|
||||
/**
|
||||
* 属性面板:盖在助手栏上的一层,不是和它并列的 tab。
|
||||
*
|
||||
@@ -19,10 +59,12 @@ import { Inspector } from './Inspector'
|
||||
*
|
||||
* 改成"盖上去"之后:助手一直在下面活着,属性是临时造访者,关掉就回到原处。
|
||||
* 选中节点即滑入,Esc 或点画布空白处即滑出——不需要专门去找一个 tab。
|
||||
* 例外是看运行时点了跑过的节点:那时要看的是它的步骤,面板不自动盖上来(见 useSheet)。
|
||||
*/
|
||||
export function InspectorSheet() {
|
||||
const selectedId = useStudio((s) => s.selectedId)
|
||||
const select = useStudio((s) => s.select)
|
||||
const open = useSheet((s) => s.open)
|
||||
|
||||
// Esc 关闭。这是"覆盖层"这种东西的通用约定,没有它就只能去找那个 ×
|
||||
useEffect(() => {
|
||||
@@ -39,12 +81,12 @@ export function InspectorSheet() {
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [selectedId, select])
|
||||
|
||||
if (!selectedId) return null
|
||||
if (!selectedId || open !== selectedId) return null
|
||||
|
||||
return (
|
||||
// key 带上 selectedId:换一个节点时重播一次滑入,让人知道内容换了。
|
||||
// 不重播的话,点另一个节点看起来像什么都没发生
|
||||
<div key={selectedId}
|
||||
<div key={selectedId} data-inspector-sheet
|
||||
className="sheet-in absolute inset-0 z-20 flex flex-col overflow-hidden bg-panel"
|
||||
style={{ boxShadow: '-10px 0 28px -14px rgba(0,0,0,.5)' }}>
|
||||
<div className="min-h-0 flex-1">
|
||||
|
||||
@@ -8,16 +8,21 @@ import { Sparkles, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS, sourceHandles } from './nodeDefs'
|
||||
import { NODE_WIDTH } from './routing'
|
||||
import { LiveClock, stillClock, TeamMatrix, teamBrief } from './TeamMatrix'
|
||||
import { LiveClock, stillClock, TeamMatrix, teamBrief, type TeamEnding } from './TeamMatrix'
|
||||
import { edgeKey, topology } from '../run/derive'
|
||||
import { api } from '../api/client'
|
||||
import { isComposing, StatusBadge } from '../components/ui'
|
||||
import { isComposing, StatusBadge, toast } from '../components/ui'
|
||||
import { explainRunError } from '../lib/explain'
|
||||
import { formatClock, formatDuration, formatNumber, formatTokens, NONE } from '../lib/format'
|
||||
import { statusMeta } from '../lib/status'
|
||||
import { issuanceLabel, RUN_CLASS_LABEL } from '../lib/terms'
|
||||
import { ApprovalCard } from '../run/RunPanel'
|
||||
import type { NodeState, NodeTrace } from '../run/trace'
|
||||
import { loopSince, loopSpan, openSince, useNodeView, type NodeView } from '../run/useNodeView'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
import {
|
||||
execStart, lastIn, loopSince, loopSpan, openCall, openSince, repairsOf, useNodeFacts, useNodeView, within,
|
||||
type NodeFacts, type NodeUsage, type NodeView, type ToolSpan,
|
||||
} from '../run/useNodeView'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { configSig, useStudio, type FlowNode } from '../store/studio'
|
||||
import type { Approval, NodeType, RunEvent, ValidationIssue } from '../types'
|
||||
@@ -96,15 +101,21 @@ function issueKey(issues: ValidationIssue[], id: string): string {
|
||||
* 出具判定挂在哪个成果节点上、什么时候落下的(毫秒,和航迹同一条时间轴,回放时
|
||||
* 游标没走到这一刻就不盖章)。按事件数组缓存:一张图里通常只有一两个成果节点在问
|
||||
*/
|
||||
const issuanceCache = new WeakMap<RunEvent[], { id: string | null; at: number | null }>()
|
||||
function issuanceOf(events: RunEvent[]): { id: string | null; at: number | null } {
|
||||
interface IssuanceAt {
|
||||
id: string | null
|
||||
at: number | null
|
||||
/** 事件原样的 data:运行还没结束时 run.output 里还没有 _issuance,悬停说明从这里取 */
|
||||
data?: Record<string, any>
|
||||
}
|
||||
const issuanceCache = new WeakMap<RunEvent[], IssuanceAt>()
|
||||
function issuanceOf(events: RunEvent[]): IssuanceAt {
|
||||
const hit = issuanceCache.get(events)
|
||||
if (hit) return hit
|
||||
let found = { id: null as string | null, at: null as number | null }
|
||||
let found: IssuanceAt = { id: null, at: null }
|
||||
for (let i = events.length - 1; i >= 0; i -= 1) {
|
||||
const e = events[i]
|
||||
if (e.type === 'issuance') {
|
||||
found = { id: e.node_id ?? null, at: typeof e.ts === 'number' ? e.ts * 1000 : null }
|
||||
found = { id: e.node_id ?? null, at: typeof e.ts === 'number' ? e.ts * 1000 : null, data: e.data ?? undefined }
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -112,6 +123,55 @@ function issuanceOf(events: RunEvent[]): { id: string | null; at: number | null
|
||||
return found
|
||||
}
|
||||
|
||||
/** 点印章够不够得着出具横幅:横幅或右栏(助手面板)看得见就行,右栏在对话层时会自己切过去 */
|
||||
function issuanceReachable(): boolean {
|
||||
return ['[data-issuance-banner]', '[data-assistant-panel]'].some((sel) => {
|
||||
const el = document.querySelector<HTMLElement>(sel)
|
||||
return !!el && el.offsetWidth > 0 && getComputedStyle(el).visibility === 'visible'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 印章 → 右栏运行视图里的出具横幅。和「去审批」同一个约定:先广播,右栏在对话层时
|
||||
* 自己切过去;接手了就 preventDefault。没人接手时这里等几帧找横幅滚过去,还是找不到
|
||||
* 就说一声,不让印章像是点坏了
|
||||
*/
|
||||
function gotoIssuance(runId: string | undefined): void {
|
||||
const handled = !window.dispatchEvent(new CustomEvent('agentlab:goto-issuance', {
|
||||
detail: { runId }, cancelable: true,
|
||||
}))
|
||||
if (handled) return
|
||||
let tries = 0
|
||||
const find = () => {
|
||||
const banner = document.querySelector<HTMLElement>('[data-issuance-banner]')
|
||||
if (banner && banner.offsetWidth > 0 && getComputedStyle(banner).visibility === 'visible') {
|
||||
const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
banner.scrollIntoView({ behavior: reduced ? 'auto' : 'smooth', block: 'center' })
|
||||
return
|
||||
}
|
||||
if (tries++ < 12) requestAnimationFrame(find)
|
||||
else toast.info('右栏收起来了:展开助手栏,在运行视图的成果区看完整判定', { key: 'card:issuance' })
|
||||
}
|
||||
requestAnimationFrame(find)
|
||||
}
|
||||
|
||||
/**
|
||||
* 回指上了哪些数字、各按哪个口径核的:「12.4% → 毛利率(月度口径 @ v2)」。
|
||||
* 口径带版本,同一个指标换过口径时一眼看得出这次按的是哪一版。悬停里只放前几条
|
||||
*/
|
||||
function matchedLines(matched: unknown): string {
|
||||
if (!Array.isArray(matched) || !matched.length) return ''
|
||||
const lines = matched.slice(0, 5).map((m: any) => {
|
||||
const token = String(m?.token ?? '').trim()
|
||||
const metric = String(m?.metric ?? '').trim()
|
||||
const caliber = typeof m?.caliber === 'string' && m.caliber.trim() ? `(${m.caliber.trim()})` : ''
|
||||
return token ? ` ${token}${metric ? ` → ${metric}` : ''}${caliber}` : ''
|
||||
}).filter(Boolean)
|
||||
if (!lines.length) return ''
|
||||
const more = matched.length > lines.length ? `\n …另有 ${matched.length - lines.length} 个` : ''
|
||||
return `回指明细:\n${lines.join('\n')}${more}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个节点有几路上游(不算循环的回边)。排队中的节点据此说清在等什么:
|
||||
* 汇合点是「等其余上游」,单入口的只是轮到它之前那一拍。按拓扑缓存
|
||||
@@ -149,9 +209,42 @@ function takenAt(n: NodeTrace | undefined, at: number): string | undefined {
|
||||
return handle
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败摘要。「模型没真调工具」「团队用完轮数」「修复想凑数」「提示词点名的工具没绑」
|
||||
* 这几类是图本身有缺口,后端的原话很长、槽里只截得下半句:换成 lib/explain 的短标题,
|
||||
* 原因和下一步放悬停。别的失败照原话的第一句——它们本来就是写给人看的,
|
||||
* 再归一次类会把「工艺员 30 秒没有回应」这种具体的话抹成「等待超时」
|
||||
*/
|
||||
function failureOf(error: string): { note: string; title: string } {
|
||||
if (!error) return { note: '没有给出原因', title: '' }
|
||||
const ex = explainRunError(error)
|
||||
if (ex.continuable || ex.fix !== 'canvas') return { note: firstSentence(error), title: error }
|
||||
return {
|
||||
note: ex.title,
|
||||
title: [ex.title, ex.reason, ex.action ? `怎么办:${ex.action}` : ''].filter(Boolean).join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
/** 协作团队是不是因为轮数用完而失败的(后端的报错首句「协作团队用完 N 轮仍未完成」) */
|
||||
const EXHAUSTED_ERROR = /用完\s*\d+\s*轮(?:仍|还)?未完成/
|
||||
|
||||
/**
|
||||
* 「协作团队用完 N 轮仍未完成:<理由>。一次都没被派到的成员:A、B。…」里的轮数、理由
|
||||
* 和没派到的人。判失败的报错和降档的那条日志是同一个开头;产出里的 never_dispatched
|
||||
* 进事件时被缩成了「[1 项]」,成员名只能从这句话里认。只认这一次执行的那句话——
|
||||
* 右栏泳道那份结局是整次运行攒下来的,接着跑成功之后还留着上一次的
|
||||
*/
|
||||
function exhaustedText(text: string): { rounds?: number; reason?: string; never: string[] } | undefined {
|
||||
const m = text.match(/用完\s*(\d+)\s*轮(?:仍|还)?未完成[::]\s*([\s\S]*?)(?:。一次都没被派到的成员|。先看成员|。按降档交付|$)/)
|
||||
if (!m) return undefined
|
||||
const never = text.match(/一次都没被派到的成员[::]\s*([^。]+)/)?.[1]
|
||||
.split('、').map((s) => s.trim()).filter(Boolean) ?? []
|
||||
return { rounds: Number(m[1]) || undefined, reason: m[2].trim() || undefined, never }
|
||||
}
|
||||
|
||||
/** 完成之后的产出量:模型出了多少 token、查到几行、取回几条 */
|
||||
function outputOf(n: NodeTrace | undefined, preview: any): string {
|
||||
if (n && n.tokensOut > 0) return formatTokens(n.tokensOut, { compact: true })
|
||||
function outputOf(u: NodeUsage, preview: any): string {
|
||||
if (u.tokensOut > 0) return formatTokens(u.tokensOut, { compact: true })
|
||||
if (Array.isArray(preview)) return `${formatNumber(preview.length)} 条`
|
||||
if (preview && typeof preview === 'object') {
|
||||
if (typeof preview.row_count === 'number') return `${formatNumber(preview.row_count)} 行`
|
||||
@@ -172,6 +265,8 @@ interface Reading {
|
||||
/** 主读数之后的补充:理由、错误摘要、产出量 */
|
||||
note?: ReactNode
|
||||
noteTitle?: string
|
||||
/** 跑完了但有要留意的事(降档交付、收尾时还想调工具):note 用琥珀色 */
|
||||
noteWarn?: boolean
|
||||
/** 靠右的一组小读数:token、工具 */
|
||||
side?: ReactNode
|
||||
}
|
||||
@@ -185,6 +280,12 @@ interface ReadingInput {
|
||||
timed: boolean
|
||||
/** 上游有几路:排队时说清在等什么 */
|
||||
fanIn: number
|
||||
facts?: NodeFacts
|
||||
/** 卡片在说的那一次执行的起点(execStart):事件里捞的事只算这之后的 */
|
||||
since: number
|
||||
/** 这一次执行的报错 */
|
||||
error: string
|
||||
ending?: TeamEnding
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -229,10 +330,104 @@ function LoopProgress({ n, iteration = 0, config, phase }: {
|
||||
)
|
||||
}
|
||||
|
||||
function readingOf({ state, view, type, config, skewMs, timed, fanIn }: ReadingInput): Reading {
|
||||
/**
|
||||
* 在跑的那次工具调用。后端声明了时限(tool.start.timeout_s)的,超出之后直说
|
||||
* 「已超出 30s 上限」,不再写一个看不出等了多久的「⋯」。没超出时照常安静
|
||||
*/
|
||||
function ToolTag({ call, at, skewMs }: { call: ToolSpan; at: number | null; skewMs: number }) {
|
||||
// 老事件没有时间戳时起点是 0,算不出等了多久,就不判超没超
|
||||
if (!call.limitS || !call.start) return <ToolName tool={call.tool} />
|
||||
if (at != null) return <ToolTagText call={call} elapsed={at - call.start} />
|
||||
return <LiveToolTag call={call} skewMs={skewMs} />
|
||||
}
|
||||
|
||||
function LiveToolTag({ call, skewMs }: { call: ToolSpan; skewMs: number }) {
|
||||
const now = useRunClock(true)
|
||||
return <ToolTagText call={call} elapsed={now - skewMs - call.start} />
|
||||
}
|
||||
|
||||
/**
|
||||
* 超出之后槽里只放得下一件事:说超时,不再写工具名(扳手已经说了是工具,名字在悬停里)。
|
||||
* db_query__shop 这种名字加上「已超出 30s 上限」,比卡片还宽
|
||||
*/
|
||||
function ToolTagText({ call, elapsed }: { call: ToolSpan; elapsed: number }) {
|
||||
if (elapsed <= call.limitS! * 1000) return <ToolName tool={call.tool} />
|
||||
return <span className="nc-over">已超出 {call.limitS}s 上限</span>
|
||||
}
|
||||
|
||||
/** 在跑的工具名:名字长时截掉,省略号前后都留着「⋯」这个在跑的记号 */
|
||||
const ToolName = ({ tool }: { tool: string }) => <><span className="nc-tool-name">{tool}</span> ⋯</>
|
||||
|
||||
/** 工具明细(放悬停):谁调的(成员首字)、调了什么、成没成、有没有超时 */
|
||||
function toolLines(calls: { tool: string; agent?: string; ok?: boolean; timedOut?: boolean; limitS?: number }[]): string {
|
||||
return calls.slice(-8).map((c) => `${c.agent ? `[${c.agent.slice(0, 1)}] ` : ''}${c.tool} ${
|
||||
c.timedOut ? `⏱ 超时${c.limitS ? `(上限 ${c.limitS}s)` : ''}`
|
||||
: c.ok === false ? '✗ 失败' : c.ok ? '✓' : `⋯ 进行中${c.limitS ? `(上限 ${c.limitS}s)` : ''}`}`).join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* 跑完之后那半句:平常是产出量;有要留意的事时换成那件事——降档交付、
|
||||
* 收尾时还想调工具、纠正过工具调用、校验靠修复才过。正常态安静,只在这些时候上琥珀色。
|
||||
* 只看这一次执行(since 之后):上一轮循环、接着跑之前的事不挂到这一次的结果上
|
||||
*/
|
||||
function doneNote(type: NodeType, u: NodeUsage, preview: any, facts: NodeFacts | undefined,
|
||||
ending: TeamEnding | undefined, at: number | null, since: number, maxRounds: number,
|
||||
): Pick<Reading, 'note' | 'noteTitle' | 'noteWarn'> {
|
||||
if (ending?.exhausted === 'degrade') {
|
||||
const rounds = ending.rounds ?? (maxRounds || '全部')
|
||||
return {
|
||||
note: `用完 ${rounds} 轮未完成 · 降档交付`,
|
||||
noteTitle: [
|
||||
`协作团队用完 ${rounds} 轮,调度者始终没有判定完成`,
|
||||
ending.reason ? `理由:${ending.reason}` : '',
|
||||
'按降档交付:成果是成员最后的原话,不是调度者认可的结论。下游的复核、出具会跟着降档',
|
||||
].filter(Boolean).join('\n'),
|
||||
noteWarn: true,
|
||||
}
|
||||
}
|
||||
const marks = within(facts?.markups, at, since)
|
||||
const settle = marks.filter((m) => m.settle).pop()
|
||||
if (settle) {
|
||||
return {
|
||||
note: '收尾时仍想调用工具',
|
||||
noteTitle: `${settle.message}\n步数用完之后模型还在要工具:交出来的是它前面写的内容,可能不完整`,
|
||||
noteWarn: true,
|
||||
}
|
||||
}
|
||||
// 写成文字、被提醒之后重答了:成果是重答的那一次,不是不完整。复核仍按降档算,所以还是琥珀。
|
||||
// 协作成员提醒之后还这样的,这一步记失败(矩阵里那一格是红的),不能说成重答了
|
||||
const fails = type === 'supervisor' ? within(facts?.memberErrors, at, since) : []
|
||||
const nudged = marks.filter((m) => !m.settle && !fails.some((f) => f.at >= m.at && m.message.startsWith(f.agent)))
|
||||
if (nudged.length) {
|
||||
return {
|
||||
note: nudged.length > 1 ? `纠正过 ${nudged.length} 次工具调用` : '纠正过一次工具调用',
|
||||
noteTitle: [
|
||||
...nudged.slice(-3).map((m) => m.message),
|
||||
`${type === 'supervisor' ? '成员' : '模型'}把工具调用写成了文字,提醒之后重答了,成果是重答的那一次;复核按降档算`,
|
||||
].join('\n'),
|
||||
noteWarn: true,
|
||||
}
|
||||
}
|
||||
const repairs = type === 'validate' ? repairsOf(facts, at, since) : 0
|
||||
if (repairs) {
|
||||
// 有一次修复想拿原文没有的值凑数、被作废了:最后虽然过了,复核照样按降档算
|
||||
const invented = lastIn(facts?.inventions, at, since)
|
||||
return {
|
||||
note: `修复 ${repairs} 次后通过`,
|
||||
noteTitle: invented
|
||||
? `第一次没过校验。其中一次修复出现了原文没有的值,已作废:${invented.message}\n最后通过的那次只调整了格式,复核按降档算`
|
||||
: '第一次没过校验,模型只调整了格式,没有补数据',
|
||||
noteWarn: !!invented,
|
||||
}
|
||||
}
|
||||
return { note: outputOf(u, preview) }
|
||||
}
|
||||
|
||||
function readingOf({ state, view, type, config, skewMs, timed, fanIn, facts, since, error, ending }: ReadingInput): Reading {
|
||||
const n = view.trace
|
||||
const runtime = view.runtime
|
||||
const at = view.at
|
||||
const u = view.usage
|
||||
// 回放时计时是定值:游标减去那一段的起点。实时的交给 LiveClock 自己走
|
||||
const clock = (from: number | undefined, coarse = false): ReactNode => {
|
||||
if (at != null) return stillClock(from != null ? at - from : undefined)
|
||||
@@ -241,42 +436,49 @@ function readingOf({ state, view, type, config, skewMs, timed, fanIn }: ReadingI
|
||||
const loop = (phase: 'live' | 'done' | 'stopped') => (
|
||||
<LoopProgress n={n} iteration={view.iteration} config={config} phase={phase} />
|
||||
)
|
||||
const tokens = (n?.tokensIn ?? 0) + (n?.tokensOut ?? 0)
|
||||
const failedTools = (runtime?.toolCalls ?? []).filter((c) => c.ok === false).length
|
||||
const runningTool = n?.toolsRunning
|
||||
? [...(runtime?.toolCalls ?? [])].reverse().find((c) => c.ok === undefined)?.tool
|
||||
const tokens = u.tokensIn + u.tokensOut
|
||||
// 工具调用:事件里捞出来的那份带起止和时限,回放能按游标截;没有时退回 runtime。
|
||||
// 只数这一次执行的:上一轮失败的调用不能让这一轮的扳手变红
|
||||
const calls = facts
|
||||
? facts.calls.filter((c) => c.start >= since && (at == null || c.start <= at))
|
||||
.map((c) => (at != null && c.end != null && c.end > at ? { ...c, ok: undefined, timedOut: false } : c))
|
||||
: runtime?.toolCalls ?? []
|
||||
const failedTools = calls.filter((c) => c.ok === false).length
|
||||
const open = u.toolsRunning ? openCall(facts, at, since) : undefined
|
||||
const runningTool = u.toolsRunning
|
||||
? open?.tool ?? [...(runtime?.toolCalls ?? [])].reverse().find((c) => c.ok === undefined)?.tool
|
||||
: undefined
|
||||
// 工具明细放悬停:谁调的(成员首字)、调了什么、成没成
|
||||
const toolTitle = (runtime?.toolCalls ?? []).slice(-8).map((c) =>
|
||||
`${c.agent ? `[${c.agent.slice(0, 1)}] ` : ''}${c.tool} ${c.ok === false ? '✗ 失败' : c.ok ? '✓' : '⋯ 进行中'}`).join('\n')
|
||||
const toolTitle = toolLines(calls)
|
||||
const side = (
|
||||
<>
|
||||
{tokens > 0 && (
|
||||
<span className="tnum" title={`输入 ${formatNumber(n?.tokensIn)} · 输出 ${formatNumber(n?.tokensOut)} tokens`}>
|
||||
<span className="tnum" title={`输入 ${formatNumber(u.tokensIn)} · 输出 ${formatNumber(u.tokensOut)} tokens`}>
|
||||
{formatTokens(tokens, { compact: true })}
|
||||
</span>
|
||||
)}
|
||||
{!!n?.tools && (
|
||||
{!!u.tools && (
|
||||
<span
|
||||
className={clsx('nc-tools tnum', runningTool && 'is-live', failedTools && 'is-bad')}
|
||||
title={toolTitle}
|
||||
>
|
||||
<Wrench size={9} aria-hidden />
|
||||
{runningTool ? `${runningTool} ⋯` : n.tools}
|
||||
{open ? <ToolTag call={open} at={at} skewMs={skewMs} /> : runningTool ? <ToolName tool={runningTool} /> : u.tools}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
// 航迹里的 token、工具是整次运行的累计,回放到半路时它们还没发生:不拿终值冒充那一刻
|
||||
const final = at == null || view.count === (n?.count ?? 0)
|
||||
// 预览(查到几行、取回几条)只有最后一次执行的:回放到更早的一次执行时不拿它冒充那一刻。
|
||||
// token、工具次数不受这个限制,投影给的就是那一刻的读数
|
||||
const lastExec = at == null || view.count === (n?.count ?? 0)
|
||||
const preview = lastExec ? runtime?.preview : undefined
|
||||
|
||||
switch (state) {
|
||||
case 'running':
|
||||
if (type === 'loop') {
|
||||
return { main: loop('live'), side: clock(loopSince(n, at), true) }
|
||||
}
|
||||
return { main: clock(openSince(n, 'run', at)), side: at == null ? side : undefined }
|
||||
return { main: clock(openSince(n, 'run', at)), side }
|
||||
case 'waiting':
|
||||
return { main: <>已等 {clock(openSince(n, 'wait', at), true)}</> }
|
||||
case 'done':
|
||||
@@ -285,23 +487,23 @@ function readingOf({ state, view, type, config, skewMs, timed, fanIn }: ReadingI
|
||||
}
|
||||
return {
|
||||
main: formatDuration(at != null ? view.replayElapsedMs : n?.lastDurationMs ?? runtime?.durationMs),
|
||||
note: final ? outputOf(n, runtime?.preview) : '',
|
||||
...doneNote(type, u, preview, facts, ending, at, since, Number(config.max_rounds) || 0),
|
||||
// 跑完了只留工具次数:token 已经在产出量里说过(输出多少),再挂一个总数是两套数
|
||||
side: n?.tools && final ? (
|
||||
side: u.tools ? (
|
||||
<span className={clsx('nc-tools tnum', failedTools && 'is-bad')} title={toolTitle}>
|
||||
<Wrench size={9} aria-hidden />{n.tools}
|
||||
<Wrench size={9} aria-hidden />{u.tools}
|
||||
</span>
|
||||
) : undefined,
|
||||
}
|
||||
case 'failed': {
|
||||
const error = n?.error || runtime?.error || ''
|
||||
const why = failureOf(error)
|
||||
if (type === 'loop') {
|
||||
return { main: loop('stopped'), note: firstSentence(error), noteTitle: error }
|
||||
return { main: loop('stopped'), note: error ? why.note : '', noteTitle: why.title }
|
||||
}
|
||||
return {
|
||||
main: formatDuration(n?.lastDurationMs ?? runtime?.durationMs),
|
||||
note: firstSentence(error) || '没有给出原因',
|
||||
noteTitle: error,
|
||||
note: why.note,
|
||||
noteTitle: why.title,
|
||||
}
|
||||
}
|
||||
case 'queued':
|
||||
@@ -484,6 +686,7 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
const def = NODE_DEFS[data.nodeType]
|
||||
const type = data.nodeType
|
||||
const view = useNodeView(id)
|
||||
const facts = useNodeFacts(id)
|
||||
const { state, runtime, trace: nt } = view
|
||||
|
||||
const runActive = useStudio((s) => s.runPhase !== 'idle')
|
||||
@@ -504,7 +707,8 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
(type === 'output' && issuanceOf(s.events).id === id ? s.trace.issuance : undefined))
|
||||
const issuedAt = useStudio((s) => (type === 'output' ? issuanceOf(s.events).at : null))
|
||||
const issuanceDetail = useStudio((s) =>
|
||||
(type === 'output' ? (s.run?.output as any)?._issuance as Record<string, any> | undefined : undefined))
|
||||
(type === 'output' ? (s.run?.output as any)?._issuance as Record<string, any> | undefined
|
||||
?? (issuanceOf(s.events).id === id ? issuanceOf(s.events).data : undefined) : undefined))
|
||||
// 只有排队中的卡片要知道自己有几路上游,别的卡片不必为改图重跑这一趟
|
||||
const fanIn = useStudio((s) => (state === 'queued' ? fanInOf(s.nodes, s.edges)[id] ?? 0 : 0))
|
||||
|
||||
@@ -563,7 +767,53 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
const streamText = executing && !view.replay ? (runtime?.tokens || runtime?.thinking || '') : ''
|
||||
const thinkingOnly = !!streamText && !runtime?.tokens
|
||||
|
||||
const reading = readingOf({ state, view, type, config: data.config, skewMs, timed, fanIn })
|
||||
// 这张卡在说哪一次执行:循环的下一轮、失败后接着跑都是新的一次,事件里捞的事只算
|
||||
// 这一次的。不截的话,调大轮数接着跑成功了,表头还挂着上一次的「判定未完成」
|
||||
const since = execStart(nt, view.at, facts)
|
||||
const lastExec = view.at == null || view.count === (nt?.count ?? 0)
|
||||
// 报错:航迹、runtime 上的是最后一次执行的;回放到更早的一次失败时取那一次的原话
|
||||
const failure = view.at != null ? lastIn(facts?.failures, view.at, since) : undefined
|
||||
const error = failure?.message || (lastExec ? nt?.error || runtime?.error || '' : '')
|
||||
const preview = lastExec ? runtime?.preview : undefined
|
||||
|
||||
// 协作团队怎么收场:收尾判定、用完轮数之后是失败还是降档。卡片和矩阵说同一件事
|
||||
const verdictMark = type === 'supervisor' ? lastIn(facts?.closings, view.at, since) : undefined
|
||||
// 判定开始了、结论还没到(回放时按游标:那一刻结论还没出来也算在判)
|
||||
const verdictOpen = !!verdictMark && (verdictMark.end == null || (view.at != null && verdictMark.end > view.at))
|
||||
const exhaustedLog = type === 'supervisor' ? lastIn(facts?.exhausts, view.at, since) : undefined
|
||||
const failedOut = type === 'supervisor' && state === 'failed' && EXHAUSTED_ERROR.test(error)
|
||||
const degraded = type === 'supervisor' && state === 'done' && (preview?.exhausted === true || !!exhaustedLog)
|
||||
const told = failedOut ? exhaustedText(error) : degraded && exhaustedLog ? exhaustedText(exhaustedLog.message) : undefined
|
||||
const exhaustedReason = typeof preview?.exhausted_reason === 'string' ? preview.exhausted_reason : told?.reason ?? ''
|
||||
// 产出进事件时数组会被缩成「[1 项]」,是数组才用;否则用报错、日志原话里认出来的
|
||||
const neverSig = failedOut || degraded
|
||||
? (Array.isArray(preview?.never_dispatched) ? preview.never_dispatched.map(String) : told?.never ?? []).join('\u0000')
|
||||
: ''
|
||||
const exhaustedRounds = told?.rounds
|
||||
const ending = useMemo<TeamEnding | undefined>(() => {
|
||||
if (!verdictMark && !failedOut && !degraded) return undefined
|
||||
const verdict = verdictMark && {
|
||||
at: verdictMark.at,
|
||||
done: !verdictOpen && verdictMark.done,
|
||||
reason: verdictOpen ? '' : verdictMark.reason,
|
||||
open: verdictOpen,
|
||||
}
|
||||
return {
|
||||
verdict,
|
||||
exhausted: failedOut ? 'fail' : degraded ? 'degrade' : undefined,
|
||||
reason: verdict?.reason || exhaustedReason,
|
||||
never: neverSig ? neverSig.split('\u0000') : undefined,
|
||||
rounds: exhaustedRounds,
|
||||
}
|
||||
}, [verdictMark, verdictOpen, failedOut, degraded, exhaustedReason, neverSig, exhaustedRounds])
|
||||
// 成员失败的原因也只要这一次执行的
|
||||
const memberErrors = useMemo(() => {
|
||||
const out: Record<string, string> = {}
|
||||
for (const f of within(facts?.memberErrors, view.at, since)) out[f.agent] = f.error
|
||||
return out
|
||||
}, [facts?.memberErrors, view.at, since])
|
||||
|
||||
const reading = readingOf({ state, view, type, config: data.config, skewMs, timed, fanIn, facts, since, error, ending })
|
||||
|
||||
// 编辑态(没有运行)槽里放校验问题,有运行时放遥测
|
||||
const [errCount, warnCount, firstIssue] = issues ? issues.split('\u0000') : ['0', '0', '']
|
||||
@@ -581,7 +831,8 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
// 模型名放悬停:槽里放不下 claude-sonnet-4-5 这么长的名字,也不是一眼要看的东西
|
||||
const teleTitle = !editing && nt ? [
|
||||
nt.model ? `模型 ${nt.model}` : '',
|
||||
nt.tokensIn + nt.tokensOut > 0 ? `输入 ${formatNumber(nt.tokensIn)} · 输出 ${formatNumber(nt.tokensOut)} tokens` : '',
|
||||
view.usage.tokensIn + view.usage.tokensOut > 0
|
||||
? `输入 ${formatNumber(view.usage.tokensIn)} · 输出 ${formatNumber(view.usage.tokensOut)} tokens` : '',
|
||||
retries > 0 ? `失败后重试了 ${retries} 次` : '',
|
||||
].filter(Boolean).join('\n') || undefined : undefined
|
||||
|
||||
@@ -602,6 +853,7 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
? `无法回指的数字:${(detail?.unmatched_numbers ?? issuance?.unmatched).map((u: any) => u?.token ?? u).join('、')}`
|
||||
: issuance?.unmatchedCount ? `无法回指的数字 ${issuance.unmatchedCount} 个` : '',
|
||||
(detail?.missing_expected ?? []).length ? `缺数据声明:${detail!.missing_expected.join('、')} 本期缺失` : '',
|
||||
matchedLines(detail?.matched),
|
||||
runClass === 'exploratory' ? '探索运行的结论不进正式归档' : '',
|
||||
'完整判定在右栏运行视图的成果区',
|
||||
].filter(Boolean).join('\n') : ''
|
||||
@@ -666,6 +918,9 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
{retries > 0 && (
|
||||
<span className="nc-chip nc-chip-warn tnum" title={`失败后重试了 ${retries} 次`}>↻{retries}</span>
|
||||
)}
|
||||
{ending?.exhausted === 'degrade' && (
|
||||
<span className="nc-chip nc-chip-warn" title="轮数用完仍未完成,按降档交付">降档</span>
|
||||
)}
|
||||
{(runActive || state !== 'idle') && (
|
||||
<StatusBadge status={state} size={14} animate={executing} className="nc-badge" />
|
||||
)}
|
||||
@@ -682,6 +937,8 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
maxRounds={Number(data.config.max_rounds) || 0}
|
||||
maxParallel={Number(data.config.max_parallel) || 0}
|
||||
skewMs={skewMs}
|
||||
ending={ending}
|
||||
memberErrors={memberErrors}
|
||||
/>
|
||||
) : (
|
||||
<div className={clsx('nc-body', streamText && 'is-stream')}>
|
||||
@@ -711,7 +968,9 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
<span className="nc-tele-state" style={{ color: meta.color }}>{meta.short}</span>
|
||||
{reading.main !== '' && <span className="nc-tele-main tnum">{reading.main}</span>}
|
||||
{reading.note && (
|
||||
<span className="nc-tele-note" title={reading.noteTitle}>{reading.note}</span>
|
||||
<span className={clsx('nc-tele-note', reading.noteWarn && 'is-warn')} title={reading.noteTitle}>
|
||||
{reading.note}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex-1" />
|
||||
{reading.side && <span className="nc-tele-side">{reading.side}</span>}
|
||||
@@ -744,7 +1003,7 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
这里不再写状态字,把位置让给计时、进度;没有读数的状态才写状态字 */}
|
||||
<div className="nc-lod-read tnum" style={{ color: state === 'idle' ? undefined : meta.color }}>
|
||||
{isTeam && state === 'running'
|
||||
? teamBrief(runtime?.team, nt, true, view.at)
|
||||
? teamBrief(runtime?.team, nt, true, view.at, ending?.verdict)
|
||||
: state === 'idle' ? (runActive ? NONE : '') : reading.main !== '' ? reading.main : meta.short}
|
||||
</div>
|
||||
</div>
|
||||
@@ -774,21 +1033,20 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps<FlowNode>
|
||||
)}
|
||||
|
||||
{/* 出具印章:成果节点上,跟着 issuance 事件落下。它是一枚章不是按钮:
|
||||
只有右栏的出具横幅在页面上时,点它才滚过去(悬停时看一眼,届时才有
|
||||
手形光标);没有横幅就是一张带悬停说明的图,不装作能点 */}
|
||||
点它是去右栏看完整判定的捷径(悬停时看一眼够不够得着,届时才有手形光标),
|
||||
够不着就是一张带悬停说明的图,不装作能点。右栏停在对话层时横幅不在页面上,
|
||||
由右栏听 agentlab:goto-issuance 自己切到运行层 */}
|
||||
{tier && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={stampTitle}
|
||||
className={clsx('nc-stamp', tierClass, stampLive.current && 'nc-stamp-in', stampLink && 'is-link nodrag')}
|
||||
title={stampTitle}
|
||||
onPointerEnter={() => setStampLink(!!document.querySelector('[data-issuance-banner]'))}
|
||||
onPointerEnter={() => setStampLink(issuanceReachable())}
|
||||
onPointerDown={stampLink ? (e) => e.stopPropagation() : undefined}
|
||||
onClick={stampLink ? (e) => {
|
||||
const banner = document.querySelector('[data-issuance-banner]')
|
||||
if (!banner) return
|
||||
e.stopPropagation()
|
||||
banner.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
gotoIssuance(useStudio.getState().run?.id)
|
||||
} : undefined}
|
||||
>
|
||||
<StatusBadge status={tier === 'formal' ? 'done' : tier === 'withheld' ? 'failed' : 'waiting'} size={11} animate={false} decorative />
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { PanelLeftClose, PanelLeftOpen } from 'lucide-react'
|
||||
import { Lock, PanelLeftClose, PanelLeftOpen } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_CATEGORIES, NODE_DEFS, type NodeDef } from './nodeDefs'
|
||||
import { hintOf } from './shortcuts'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { EDIT_LOCK_TEXT, useEditLock, useStudio } from '../store/studio'
|
||||
import { IconButton } from '../components/ui'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
@@ -25,9 +25,11 @@ const startDrag = (e: React.DragEvent, def: NodeDef) => {
|
||||
export function Palette({ collapsed, onToggle }: { collapsed: boolean; onToggle: () => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const addNode = useStudio((s) => s.addNode)
|
||||
const locked = useStudio((s) => s.copilot.active)
|
||||
// 助手在改、正式运行在跑:点了、拖了都落不下来,整块置灰并说清为什么
|
||||
const lock = useEditLock()
|
||||
const locked = lock != null
|
||||
|
||||
if (collapsed) return <Rail onToggle={onToggle} onAdd={(t) => addNode(t)} locked={locked} />
|
||||
if (collapsed) return <Rail onToggle={onToggle} onAdd={(t) => addNode(t)} lock={lock} />
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const defs = Object.values(NODE_DEFS).filter(
|
||||
@@ -98,10 +100,17 @@ export function Palette({ collapsed, onToggle }: { collapsed: boolean; onToggle:
|
||||
<div className="px-2 py-6 text-center text-2xs text-faint">没有匹配的节点</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t px-3 py-2 text-2xs leading-relaxed text-faint">
|
||||
拖到画布,或点击放在视野中间。<br />
|
||||
从节点右侧圆点拖到另一个节点左侧即可连线。
|
||||
</div>
|
||||
{lock ? (
|
||||
<div className="flex items-start gap-1.5 border-t px-3 py-2 text-2xs leading-relaxed text-dim" role="note">
|
||||
<Lock size={11} className="mt-0.5 shrink-0" aria-hidden />
|
||||
<span>{EDIT_LOCK_TEXT[lock]}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border-t px-3 py-2 text-2xs leading-relaxed text-faint">
|
||||
拖到画布,或点击放在视野中间。<br />
|
||||
从节点右侧圆点拖到另一个节点左侧即可连线。
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -125,22 +134,26 @@ function TypeIcon({ def, size = 20 }: { def: NodeDef; size?: number }) {
|
||||
* 收起后的图标轨。说明不用原生 title:原生提示要停一秒多才出来,而且只能一行灰字;
|
||||
* 这里悬停即浮出名字和一句话说明。浮层挂到 body 上,不被这一栏的滚动裁掉
|
||||
*/
|
||||
function Rail({ onToggle, onAdd, locked }: {
|
||||
onToggle: () => void; onAdd: (t: NodeType) => void; locked: boolean
|
||||
function Rail({ onToggle, onAdd, lock }: {
|
||||
onToggle: () => void; onAdd: (t: NodeType) => void; lock: ReturnType<typeof useEditLock>
|
||||
}) {
|
||||
const locked = lock != null
|
||||
const [tip, setTip] = useState<{ def: NodeDef; top: number; left: number } | null>(null)
|
||||
const show = (def: NodeDef, el: HTMLElement) => {
|
||||
const r = el.getBoundingClientRect()
|
||||
setTip({ def, top: r.top + r.height / 2, left: r.right + 8 })
|
||||
}
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center" aria-label="节点库(已收起)">
|
||||
<div className="flex h-full flex-col items-center" aria-label="节点库(已收起)"
|
||||
title={lock ? EDIT_LOCK_TEXT[lock] : undefined}>
|
||||
<div className="flex w-full justify-center border-b py-2">
|
||||
<IconButton label="展开节点库" title={hintOf('展开节点库', 'palette')} onClick={onToggle}
|
||||
icon={<PanelLeftOpen size={13} />} />
|
||||
</div>
|
||||
{/* 置灰的图标轨接不到悬停,也就没有说明可看:原因挂在外面那一层的 title 上 */}
|
||||
<div className={clsx('flex w-full flex-1 flex-col items-center gap-0.5 overflow-y-auto py-1.5',
|
||||
locked && 'pointer-events-none opacity-50')}
|
||||
aria-disabled={locked || undefined}
|
||||
onMouseLeave={() => setTip(null)}>
|
||||
{NODE_CATEGORIES.map((category, ci) => (
|
||||
<div key={category} className="flex w-full flex-col items-center gap-0.5">
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { AlertTriangle, CheckCircle2, CornerDownRight, RotateCw, Trash2, Unlink, Workflow, XCircle } from 'lucide-react'
|
||||
import { AlertTriangle, CheckCircle2, CornerDownRight, Plus, RotateCw, Trash2, Unlink, Workflow, XCircle } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS } from './nodeDefs'
|
||||
import type { FieldRef, Problem } from './issues'
|
||||
import { unboundToolOf, withToolBound, type FieldRef, type Problem } from './issues'
|
||||
import { formatShortcut } from '../lib/keys'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { useEditLock, useStudio } from '../store/studio'
|
||||
import { Spinner } from '../components/ui'
|
||||
|
||||
/**
|
||||
@@ -129,10 +129,15 @@ function ProblemRow({ problem: p, active, onLocate, onDeleteEdge }: {
|
||||
problem: Problem; active: boolean; onLocate: () => void; onDeleteEdge: (id: string) => void
|
||||
}) {
|
||||
const node = useStudio((s) => (p.nodeId ? s.nodes.find((n) => n.id === p.nodeId) : undefined))
|
||||
const updateNode = useStudio((s) => s.updateNode)
|
||||
const locked = useEditLock() != null
|
||||
const err = p.level === 'error'
|
||||
const Icon = err ? XCircle : AlertTriangle
|
||||
const where = fieldLabel(p.field, node?.data.nodeType)
|
||||
const where = fieldLabel(p.field, node?.data.nodeType, node?.data.config)
|
||||
const locatable = p.scope === 'node' && !!node
|
||||
// 提示词点了名的工具没绑:就地绑上,和检查器里那个按钮是同一个修法
|
||||
const tool = unboundToolOf(p.message)
|
||||
const bound = node && tool ? withToolBound(node.data.config ?? {}, p.field, tool) : null
|
||||
return (
|
||||
<div role="listitem" data-problem={p.id}
|
||||
className={clsx('group flex items-start gap-2 pl-6 pr-2', active && 'bg-hover')}>
|
||||
@@ -153,6 +158,13 @@ function ProblemRow({ problem: p, active, onLocate, onDeleteEdge }: {
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{bound && tool && (
|
||||
<button type="button" className="btn btn-xs my-0.5 shrink-0" disabled={locked}
|
||||
title={`把 ${tool} 加进${where || '这个节点的工具'}`}
|
||||
onClick={() => updateNode(node!.id, { config: bound })}>
|
||||
<Plus size={10} aria-hidden /> 绑定 {tool}
|
||||
</button>
|
||||
)}
|
||||
{/* 悬空边(指向不存在的节点):React Flow 不画它,画布上看不见、点不到,只能在这儿删 */}
|
||||
{p.scope === 'edge' && p.edgeId && (
|
||||
<button type="button" className="btn btn-xs my-0.5 shrink-0" onClick={() => onDeleteEdge(p.edgeId!)}>
|
||||
@@ -163,13 +175,18 @@ function ProblemRow({ problem: p, active, onLocate, onDeleteEdge }: {
|
||||
)
|
||||
}
|
||||
|
||||
function fieldLabel(field: FieldRef | null | undefined, type?: string): string {
|
||||
const SUB_LABEL: Record<string, string> = { condition: '的条件', key: '的标识', tools: '的工具', system: '的角色设定' }
|
||||
|
||||
function fieldLabel(field: FieldRef | null | undefined, type?: string, config?: Record<string, any>): string {
|
||||
if (!field) return ''
|
||||
if (field.key === 'label') return '节点名称'
|
||||
const def = type ? NODE_DEFS[type as keyof typeof NODE_DEFS] : undefined
|
||||
const base = def?.fields.find((f) => f.key === field.key)?.label ?? field.key
|
||||
if (field.index == null) return base
|
||||
const sub = (field.sub && SUB_LABEL[field.sub]) || ''
|
||||
// 成员有名字就叫名字:「第 2 个成员」还得数,「成员 writer」一眼就知道是谁
|
||||
const name = field.key === 'agents' ? config?.agents?.[field.index]?.name : undefined
|
||||
if (name) return `成员「${name}」${sub}`
|
||||
const item = ({ cases: '分支', fields: '字段', metrics: '指标', agents: '成员' } as Record<string, string>)[field.key]
|
||||
const sub = field.sub === 'condition' ? '的条件' : field.sub === 'key' ? '的标识' : ''
|
||||
return item ? `第 ${field.index + 1} 个${item}${sub}` : `${base} · 第 ${field.index + 1} 项`
|
||||
}
|
||||
|
||||
@@ -31,8 +31,7 @@ const readActor = () => {
|
||||
* 门禁拦下的问题一条一行、前置节点名,点一下关掉弹窗、定位到那个节点。
|
||||
*/
|
||||
export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
|
||||
// published_by 后端已经给了,types.ts 还没跟上
|
||||
workflow: Workflow & { published_by?: string | null }
|
||||
workflow: Workflow
|
||||
onClose: () => void
|
||||
onDone: () => void
|
||||
onLocate: (nodeId: string) => void
|
||||
|
||||
@@ -7,8 +7,8 @@ import { formatClock, formatDuration, formatTokens, NONE } from '../lib/format'
|
||||
import { statusMeta } from '../lib/status'
|
||||
import { topology, type GraphLike } from '../run/derive'
|
||||
import {
|
||||
isActivePhase, isTerminal, liveAt, project, type NodeState, type NodeTrace, type Projection, type Segment,
|
||||
type Trace,
|
||||
isActivePhase, isTerminal, lastEventAt, liveAt, project, type NodeState, type NodeTrace, type Projection,
|
||||
type Segment, type Trace,
|
||||
} from '../run/trace'
|
||||
import { projectCached } from '../run/useNodeView'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
@@ -277,8 +277,11 @@ function measuredOf(n: NodeTrace | undefined, at: number): number | undefined {
|
||||
return runs.length === 1 && runs[0].end != null && runs[0].end <= at ? n.lastDurationMs : undefined
|
||||
}
|
||||
|
||||
/** 一条泳道右侧的摘要:执行了几次、一共多久、等了多久、用了多少 token */
|
||||
function summarize(n: NodeTrace | undefined, state: NodeState, at: number): string {
|
||||
/**
|
||||
* 一条泳道右侧的摘要:执行了几次、一共多久、等了多久、用了多少 token。
|
||||
* tokens 回放时是游标那一刻的读数(投影给的),实时是累计
|
||||
*/
|
||||
function summarize(n: NodeTrace | undefined, state: NodeState, at: number, tokens?: number): string {
|
||||
if (!n || state === 'idle' || state === 'queued') return state === 'queued' ? '排队' : NONE
|
||||
if (state === 'blocked') return '阻断'
|
||||
if (state === 'unreached') return '未到达'
|
||||
@@ -296,7 +299,7 @@ function summarize(n: NodeTrace | undefined, state: NodeState, at: number): stri
|
||||
const measured = measuredOf(n, at)
|
||||
if (run > 0 || state === 'done') parts.push(formatDuration(measured ?? (run || n.lastDurationMs)))
|
||||
if (wait > 0) parts.push(`等 ${formatClock(wait).replace(/\.\d$/, '')}`)
|
||||
const tok = n.tokensIn + n.tokensOut
|
||||
const tok = tokens ?? n.tokensIn + n.tokensOut
|
||||
if (tok > 0 && parts.length < 3) parts.push(formatTokens(tok, { compact: true }))
|
||||
return parts.join(' · ') || NONE
|
||||
}
|
||||
@@ -312,13 +315,15 @@ function buildRows(trace: Trace, graph: TimelineGraph, at: number, labels: Map<s
|
||||
for (const id of ids) {
|
||||
const n = trace.nodes[id]
|
||||
// 回放时状态取游标那一刻的投影:摘要和泳道底色要和画布上的卡片一致
|
||||
const state: NodeState = states ? states[id]?.state ?? 'idle' : n?.state ?? 'idle'
|
||||
const p = states?.[id]
|
||||
const state: NodeState = states ? p?.state ?? 'idle' : n?.state ?? 'idle'
|
||||
const type = nodeTypeOf(byId.get(id))
|
||||
const label = labels.get(id) ?? id
|
||||
rows.push({
|
||||
key: id, kind: 'node', nodeId: id, label, type,
|
||||
segs: (n?.segments ?? []).filter((s) => s.kind === 'run' || s.kind === 'wait' || s.kind === 'retry'),
|
||||
state, count: n?.count ?? 0, summary: summarize(n, state, at), measuredMs: measuredOf(n, at),
|
||||
state, count: n?.count ?? 0, measuredMs: measuredOf(n, at),
|
||||
summary: summarize(n, state, at, states ? (p?.tokensIn ?? 0) + (p?.tokensOut ?? 0) : undefined),
|
||||
note: state === 'blocked' ? (failedLabel ? `阻断:上游「${failedLabel}」失败` : '阻断:上游失败')
|
||||
: state === 'unreached' ? '未到达' : undefined,
|
||||
name: label, top, height: ROW_H,
|
||||
@@ -381,11 +386,11 @@ export function lastStampOf(trace: Trace, stamps: number[] = stampsOf(trace)): n
|
||||
|
||||
/**
|
||||
* 停下的运行此刻的样子。project 在「不早于最后一条事件」时读节点的当前状态(含推导出的
|
||||
* 阻断、未到达)和后端给的权威时长,早于它就按段重建、这两样都丢了。最后一条事件的时刻
|
||||
* 只记在内部簿记里,所以有 endedAt 时取一个一定不早于它的时刻;结束时刻照样按 endedAt 算
|
||||
* 阻断、未到达)和后端给的权威时长,早于它就按段重建、这两样都丢了。所以按最后一条事件
|
||||
* 的时刻投影;结束时刻照样按 endedAt 算
|
||||
*/
|
||||
export function projectSettled(trace: Trace): Projection {
|
||||
return project(trace, trace.endedAt != null ? Number.MAX_SAFE_INTEGER : lastStampOf(trace))
|
||||
return project(trace, lastEventAt(trace))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,7 @@ import clsx from 'clsx'
|
||||
import { StatusBadge } from '../components/ui'
|
||||
import { formatClock, formatDuration, NONE } from '../lib/format'
|
||||
import { statusMeta } from '../lib/status'
|
||||
import type { TeamMemberEx } from '../run/decode'
|
||||
import type { NodeTrace, Segment } from '../run/trace'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
import type { TeamMember, TeamRound, TeamRun } from '../types'
|
||||
@@ -63,6 +64,27 @@ interface Roster {
|
||||
description?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮数用完之后怎么收场。后端在最后一轮交回之后还会让调度者只判定、不派活地
|
||||
* 看一次(agent.route.* 带 closing):它说完成了就正常交付;没说完成,节点按
|
||||
* 「用完轮数时」的配置失败或降档交付。这一次判定不是新的一轮,矩阵不给它加列
|
||||
*/
|
||||
export interface TeamEnding {
|
||||
/**
|
||||
* 收尾判定。open = 调度者还在判;at 是开始判定的时刻(agent.route.start),
|
||||
* 矩阵据此认出哪一段调度是这次判定。老后端没有这一步
|
||||
*/
|
||||
verdict?: { done: boolean; reason: string; open: boolean; at?: number }
|
||||
/** 用完轮数仍未完成:fail 节点失败,degrade 降档交付(成果是成员最后的原话) */
|
||||
exhausted?: 'fail' | 'degrade'
|
||||
/** 调度者最后给的理由:收尾判定的,没有就取报错或产出里的 */
|
||||
reason?: string
|
||||
/** 后端点名的「一次都没被派到」的成员(报错原话、产出的 never_dispatched) */
|
||||
never?: string[]
|
||||
/** 报错、日志原话里的「用完 N 轮」:配置里的最多轮数可能在运行之后改过 */
|
||||
rounds?: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
roster: Roster[]
|
||||
/** 还没跑过就没有:这时矩阵就是花名册 */
|
||||
@@ -79,6 +101,18 @@ interface Props {
|
||||
maxParallel?: number
|
||||
/** 服务端时钟偏差,实时计时要扣掉 */
|
||||
skewMs?: number
|
||||
ending?: TeamEnding
|
||||
/** 成员失败的原因(agent.step.end 的 error),按名字 */
|
||||
memberErrors?: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 真正派过活的轮次。调度者的理由按轮记,收尾判定那一次(round = 上限)也会记下
|
||||
* 一条只有理由、没有成员的「轮」——它不是一轮协作,不能让表头写成「第 5 轮 / 上限 4」
|
||||
*/
|
||||
function worked(team: TeamRun | undefined): TeamRun | undefined {
|
||||
if (!team || team.rounds.every((r) => r.members.length)) return team
|
||||
return { ...team, rounds: team.rounds.filter((r) => r.members.length) }
|
||||
}
|
||||
|
||||
/** 当前该看哪一轮:有在跑的就看那一轮,否则看最后一轮 */
|
||||
@@ -88,6 +122,24 @@ function currentRound(team: TeamRun | undefined) {
|
||||
return running.length ? running[running.length - 1] : team.rounds[team.rounds.length - 1]
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一段调度是不是轮数用完后的收尾判定。认事件(agent.route.* 带 closing,卡片折成
|
||||
* verdict):不拿轮次和配置里的「最多轮数」比——没配时后端按缺省值跑,运行之后还可能
|
||||
* 改过(调大了再接着跑、回放历史运行),那样比出来的是错的。收尾判定是这一次执行里
|
||||
* 最后一段调度,它开始之后的那段就是它
|
||||
*/
|
||||
const isClosing = (seg: Segment | undefined, verdict: TeamEnding['verdict']): boolean =>
|
||||
!!seg && !!verdict && (verdict.at == null || seg.start >= verdict.at)
|
||||
|
||||
/** 收尾判定的一句话。reason 太长的放悬停,表头只放得下结论 */
|
||||
export function verdictText(v: TeamEnding['verdict'], full = false): string {
|
||||
if (!v) return ''
|
||||
if (v.open) return '轮数用完 · 调度者在判定'
|
||||
if (v.done) return full ? '轮数用完 · 调度者判定:已完成' : '轮数用完 · 判定已完成'
|
||||
const why = v.reason.trim()
|
||||
return full ? `轮数用完 · 调度者判定:未完成${why ? `(${why})` : ''}` : '轮数用完 · 判定未完成'
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一轮是几个人并行:按派出去的人数,不按此刻还有几个在跑。三人并行的一轮
|
||||
* 交回两个之后仍是并行的一轮,说成「串行推进」就和底部的「并行省下」打架了。
|
||||
@@ -156,15 +208,16 @@ export function teamAt(team: TeamRun | undefined, trace: NodeTrace | undefined,
|
||||
* 「2/3 在跑 · 第 2 轮」「调度中 · 第 2 轮」「共 3 轮 · 并行省下 28.4 s」
|
||||
* 进行中的把此刻的读数放前面:精简档缩到 0.4 倍以下时这一句放不全,截掉的该是轮次
|
||||
*/
|
||||
export function teamBrief(team: TeamRun | undefined, trace: NodeTrace | undefined, live: boolean, at?: number | null): string {
|
||||
team = teamAt(team, trace, at)
|
||||
export function teamBrief(team: TeamRun | undefined, trace: NodeTrace | undefined, live: boolean, at?: number | null,
|
||||
verdict?: TeamEnding['verdict']): string {
|
||||
team = worked(teamAt(team, trace, at))
|
||||
const round = currentRound(team)
|
||||
const dispatch = lastSeg(trace, 'dispatch', undefined, at)
|
||||
const thinking = live && dispatch && dispatch.end == null
|
||||
if (!team?.rounds.length) return thinking ? '调度中' : live ? '进行中' : NONE
|
||||
const no = `第 ${(round?.round ?? 0) + 1} 轮`
|
||||
if (live) {
|
||||
if (thinking) return `调度中 · ${no}`
|
||||
if (thinking) return isClosing(dispatch, verdict) ? '轮数用完 · 收尾判定中' : `调度中 · ${no}`
|
||||
const running = round?.members.filter((m) => m.status === 'running').length ?? 0
|
||||
const size = round?.members.length ?? 0
|
||||
if (running) return `${running}/${size} 在跑 · ${no}`
|
||||
@@ -192,8 +245,10 @@ function memberText(m: TeamMember | undefined, status = m?.status): string {
|
||||
return statusMeta(status).short
|
||||
}
|
||||
|
||||
function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRounds, maxParallel, skewMs = 0 }: Props) {
|
||||
const team = teamAt(final, trace, at)
|
||||
function TeamMatrixImpl({
|
||||
roster, team: final, trace, live, replay, at, maxRounds, maxParallel, skewMs = 0, ending, memberErrors,
|
||||
}: Props) {
|
||||
const team = worked(teamAt(final, trace, at))
|
||||
const round = currentRound(team)
|
||||
// 事件里出现过、但花名册里没有的名字也要显示。配置被人改过、或者调度者报了
|
||||
// 一个不存在的成员时,这里至少能看出"确实派过这么个人"
|
||||
@@ -224,8 +279,16 @@ function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRound
|
||||
status,
|
||||
roundNo,
|
||||
hint: roster.find((r) => r.name === name)?.description,
|
||||
// 原因按轮记在 reduceTeam 给的那一格上;老数据没有就用事件里捞到的最后一次
|
||||
error: status === 'failed' ? (member as TeamMemberEx | undefined)?.error || memberErrors?.[name] : undefined,
|
||||
}
|
||||
})
|
||||
// 轮数用完还没完成时,一次都没被派到的人要点出来:负责定稿的那个常常就在里面,
|
||||
// 写「—」看着像它还没轮到,其实是整次协作都没用上它
|
||||
const undone = !!ending?.exhausted || (!!ending?.verdict && !ending.verdict.open && !ending.verdict.done)
|
||||
const never = undone && !live ? new Set(rows.filter((r) => !r.member).map((r) => r.name)) : null
|
||||
// 悬停里的名单再并上后端点的名:花名册在运行之后被改过时,矩阵里可能已经没有那一行
|
||||
const neverNamed = never ? [...new Set([...never, ...(ending?.never ?? [])])] : []
|
||||
|
||||
// 条形按同一批数归一化,长短才可比
|
||||
const busiest = Math.max(1, ...rows.map((r) => (r.active ? r.member?.ms ?? 0 : 0)))
|
||||
@@ -236,43 +299,66 @@ function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRound
|
||||
const dispatch = lastSeg(trace, 'dispatch', undefined, at)
|
||||
const thinking = live && !!dispatch && dispatch.end == null
|
||||
const decided = dispatch?.end != null ? dispatch.end - dispatch.start : undefined
|
||||
const verdict = ending?.verdict
|
||||
const closing = isClosing(dispatch, verdict)
|
||||
const dispatchRound = team?.rounds.find((r) => r.round === (dispatch?.iteration ?? 0) - 1)
|
||||
const dispatchNote = dispatch && !thinking
|
||||
? dispatchRound?.members.length ? `派 ${dispatchRound.members.length} 人` : '收尾'
|
||||
? closing ? '收尾判定' : dispatchRound?.members.length ? `派 ${dispatchRound.members.length} 人` : '收尾'
|
||||
: ''
|
||||
// 用完了几轮:以报错、日志原话为准,配置里的数可能在运行之后改过
|
||||
const usedUp = ending?.rounds ?? (maxRounds || team?.rounds.length)
|
||||
|
||||
const width = widthOf(round)
|
||||
let headRight = ''
|
||||
/** 表头右边这句的语气:用完轮数没完成时失败是红、降档是琥珀,别的安静 */
|
||||
let headTone: 'err' | 'warn' | '' = ''
|
||||
if (!team) headRight = maxParallel ? `并发上限 ${maxParallel}` : ''
|
||||
else if (live) {
|
||||
headRight = thinking ? '调度中'
|
||||
headRight = thinking ? closing ? verdictText({ done: false, reason: '', open: true }) : '调度中'
|
||||
: width > 1 ? runningNow ? `本轮 ${width} 人并行 · ${runningNow} 人在跑` : `本轮 ${width} 人已交回`
|
||||
: runningNow ? '串行推进' : '等调度者'
|
||||
} else if (ending?.exhausted) {
|
||||
headRight = `用完 ${usedUp} 轮 · 未完成`
|
||||
headTone = ending.exhausted === 'fail' ? 'err' : 'warn'
|
||||
} else if (verdict && !verdict.open) {
|
||||
headRight = verdictText(verdict)
|
||||
headTone = verdict.done ? '' : 'warn'
|
||||
} else {
|
||||
headRight = unsettledNote(rows.filter((r) => r.active && r.member)
|
||||
.map((r) => ({ ...r.member!, status: r.status! })))
|
||||
|| (width > 1 ? `${width} 人并行完成` : team.finished ? '已收尾' : '')
|
||||
}
|
||||
const reason = ending?.reason || verdict?.reason || ''
|
||||
const headTitle = ending?.exhausted || verdict
|
||||
? [
|
||||
verdict ? verdictText(verdict, true) : `协作团队用完 ${usedUp} 轮仍未完成`,
|
||||
ending?.exhausted === 'degrade' ? '按降档交付:成果是成员最后的原话,不是调度者认可的结论' : '',
|
||||
ending?.exhausted === 'fail' ? '节点判为失败。可以调大「最多轮数」,或把「用完轮数时」改成降档交付' : '',
|
||||
reason && !(verdict && !verdict.done && !verdict.open) ? `理由:${reason}` : '',
|
||||
neverNamed.length ? `一次都没被派到:${neverNamed.join('、')}` : '',
|
||||
].filter(Boolean).join('\n')
|
||||
: undefined
|
||||
// 省下多少只算整轮交齐的;有并行过但没交齐(失败、取消)的不能说成"全程串行"
|
||||
const serialOnly = !!team?.finished && !team.rounds.some((r) => widthOf(r) > 1)
|
||||
|
||||
return (
|
||||
<div className={clsx('team-matrix', live && 'is-live')}>
|
||||
<div className="team-head">
|
||||
<div className="team-head" title={headTitle}>
|
||||
<span className="tnum">
|
||||
{team?.rounds.length
|
||||
? `第 ${(round?.round ?? 0) + 1} 轮${maxRounds ? ` / 上限 ${maxRounds}` : ''}`
|
||||
: `花名册${maxRounds ? ` · 上限 ${maxRounds} 轮` : ''}`}
|
||||
</span>
|
||||
<span className="team-head-rule" />
|
||||
<span>{headRight}</span>
|
||||
<span className={clsx('team-head-right', headTone && `is-${headTone}`)}>{headRight}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={clsx('team-row team-row-dispatch', thinking && 'team-row-running', !dispatch && 'team-row-idle')}
|
||||
title={[
|
||||
'调度者:决定下一轮派谁、几个人同时做',
|
||||
round?.reason ? `理由:${round.reason}` : '',
|
||||
closing && verdict ? verdictText(verdict, true)
|
||||
: round?.reason ? `理由:${round.reason}` : '',
|
||||
dispatch?.estimated ? '耗时由事件间隔推算' : '',
|
||||
].filter(Boolean).join('\n')}
|
||||
>
|
||||
@@ -283,19 +369,20 @@ function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRound
|
||||
</span>
|
||||
<span className="team-ms tnum">
|
||||
{thinking ? (
|
||||
ticking ? <>思考 <LiveClock from={dispatch!.start} skewMs={skewMs} coarse /></>
|
||||
: at != null ? `思考 ${stillClock(at - dispatch!.start)}` : '思考中'
|
||||
ticking ? <>{closing ? '判定' : '思考'} <LiveClock from={dispatch!.start} skewMs={skewMs} coarse /></>
|
||||
: at != null ? `${closing ? '判定' : '思考'} ${stillClock(at - dispatch!.start)}` : '思考中'
|
||||
) : decided != null ? (
|
||||
`${dispatch?.estimated ? '≈' : ''}${formatDuration(decided)}${dispatchNote ? ` · ${dispatchNote}` : ''}`
|
||||
) : NONE}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{rows.map(({ name, active, member, status, roundNo, hint }) => {
|
||||
{rows.map(({ name, active, member, status, roundNo, hint, error }) => {
|
||||
const running = status === 'running'
|
||||
const done = status === 'done'
|
||||
const failed = status === 'failed'
|
||||
const open = running ? lastSeg(trace, 'member', name, at) : undefined
|
||||
const unused = !!never?.has(name)
|
||||
return (
|
||||
<div
|
||||
key={name}
|
||||
@@ -305,14 +392,17 @@ function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRound
|
||||
done && 'team-row-done',
|
||||
failed && 'team-row-failed',
|
||||
active && 'team-row-active',
|
||||
!member && 'team-row-idle',
|
||||
!member && !unused && 'team-row-idle',
|
||||
unused && 'team-row-never',
|
||||
member && !active && 'team-row-past',
|
||||
)}
|
||||
data-member-status={status ?? 'idle'}
|
||||
data-member-status={unused ? 'never' : status ?? 'idle'}
|
||||
title={[
|
||||
hint,
|
||||
running && member?.instruction ? `在做:${member.instruction}` : '',
|
||||
member ? `第 ${roundNo + 1} 轮 · ${memberText(member, status)}` : '',
|
||||
failed && error ? `原因:${error}` : '',
|
||||
unused ? `用完 ${usedUp} 轮,一次都没被派到` : '',
|
||||
].filter(Boolean).join('\n') || name}
|
||||
>
|
||||
<StatusBadge status={status ?? 'idle'} size={9} decorative />
|
||||
@@ -332,7 +422,7 @@ function TeamMatrixImpl({ roster, team: final, trace, live, replay, at, maxRound
|
||||
{running && open && open.end == null && ticking
|
||||
? <LiveClock from={open.start} skewMs={skewMs} coarse />
|
||||
: running && open && at != null ? stillClock(at - open.start)
|
||||
: memberText(member, status)}
|
||||
: unused ? '未派到' : memberText(member, status)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,7 +2,9 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
import { ChevronLeft, History, RotateCcw, ShieldCheck } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { diffGraphs, toFlow, useStudio, type FlowNode, type GraphDiff } from '../store/studio'
|
||||
import {
|
||||
EDIT_LOCK_TEXT, diffGraphs, toFlow, useEditLock, useStudio, type EditLock, type FlowNode, type GraphDiff,
|
||||
} from '../store/studio'
|
||||
import { ErrorState, Skeleton, toast } from '../components/ui'
|
||||
import { formatDateTime, formatTime } from '../lib/format'
|
||||
import { WORKFLOW_STATUS_LABEL } from '../lib/terms'
|
||||
@@ -29,7 +31,8 @@ export function VersionsSheet({ workflow, onClose }: { workflow: Workflow; onClo
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const dirty = useStudio((s) => s.dirty)
|
||||
const locked = useStudio((s) => s.copilot.active)
|
||||
// 助手在改、正式运行在跑:恢复旧版也是改图,一样拦下
|
||||
const lock = useEditLock()
|
||||
const restoreVersion = useStudio((s) => s.restoreVersion)
|
||||
const undo = useStudio((s) => s.undo)
|
||||
|
||||
@@ -135,7 +138,7 @@ export function VersionsSheet({ workflow, onClose }: { workflow: Workflow; onClo
|
||||
: 'error' in detail ? <ErrorState error={detail.error} compact />
|
||||
: target && diff && (
|
||||
<VersionPreview version={v.version} target={target} diff={diff}
|
||||
locked={locked} onRestore={restore} />
|
||||
lock={lock} onRestore={restore} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -153,9 +156,9 @@ export function VersionsSheet({ workflow, onClose }: { workflow: Workflow; onClo
|
||||
)
|
||||
}
|
||||
|
||||
function VersionPreview({ version, target, diff, locked, onRestore }: {
|
||||
function VersionPreview({ version, target, diff, lock, onRestore }: {
|
||||
version: number; target: { nodes: FlowNode[]; edges: Edge[] }; diff: GraphDiff
|
||||
locked: boolean; onRestore: () => void
|
||||
lock: EditLock; onRestore: () => void
|
||||
}) {
|
||||
const current = useStudio((s) => s.nodes)
|
||||
const same = diff.total === 0
|
||||
@@ -192,8 +195,8 @@ function VersionPreview({ version, target, diff, locked, onRestore }: {
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<button type="button" className="btn btn-sm mt-2 w-full justify-center" disabled={same || locked}
|
||||
title={locked ? '助手正在改这张工作流,等它做完' : undefined} onClick={onRestore}>
|
||||
<button type="button" className="btn btn-sm mt-2 w-full justify-center" disabled={same || lock != null}
|
||||
title={lock ? EDIT_LOCK_TEXT[lock] : undefined} onClick={onRestore}>
|
||||
<RotateCcw size={11} /> 恢复 v{version} 到画布
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* 助手的 update_node 怎么落到节点上,以及改完之后工具绑定变了什么。
|
||||
*
|
||||
* 规则和后端 app/api/copilot.py 的 merge_node_config / tool_changes 一字不差:
|
||||
* 流式期间画布按这里逐条落,收尾时 final.graph 是后端按同一套规则合好的整张图。
|
||||
* 两边口径一不一样,画布就会在 final 到来那一下跳一次——更糟的是以前前端整体替换
|
||||
* config,流到一半断掉时,画布上的半成品里 agent 的工具已经没了。
|
||||
*
|
||||
* 以前是整体替换:模型只想改一句提示词,也得把整份 config 抄一遍,漏抄的字段就没了。
|
||||
* 真出过事——改写提示词时漏了 tools,要查库的 agent 全丢了工具,最后把一堆工具调用
|
||||
* 的原始标记当答案交了出去。
|
||||
*
|
||||
* 纯函数,不依赖 React 和 store,检查脚本能直接 import。
|
||||
*/
|
||||
import type { ToolChange } from '../types'
|
||||
|
||||
type Config = Record<string, any>
|
||||
|
||||
/** 成员条目里写 remove: true 表示删掉这个成员 */
|
||||
const REMOVE_MEMBER = 'remove'
|
||||
|
||||
const isObject = (v: unknown): v is Config => !!v && typeof v === 'object' && !Array.isArray(v)
|
||||
|
||||
// 和 engine/nodes/multi.py 的叫法一致:没起名字的成员按位置叫 agentN
|
||||
const memberKey = (member: Config, index: number): string => String(member.name || `agent${index}`)
|
||||
|
||||
/** 按字段合并:写了的覆盖,写 null 的删掉,没写的原样保留。返回新对象 */
|
||||
function mergeFields(old: Config, patch: Config): Config {
|
||||
const out: Config = { ...old }
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
if (value === null) delete out[key]
|
||||
else if (value !== undefined) out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 协作成员按 name 合并。原有成员保持原来的次序,新名字接在后面 */
|
||||
function mergeMembers(old: unknown[], patch: unknown[]): unknown[] {
|
||||
const merged = [...old]
|
||||
const where = new Map<string, number>()
|
||||
merged.forEach((m, i) => { if (isObject(m)) where.set(memberKey(m, i), i) })
|
||||
const dropped = new Set<number>()
|
||||
patch.forEach((entry, i) => {
|
||||
if (!isObject(entry)) return
|
||||
const key = memberKey(entry, i)
|
||||
const at = where.get(key)
|
||||
if (entry[REMOVE_MEMBER] === true) {
|
||||
if (at != null) dropped.add(at)
|
||||
return
|
||||
}
|
||||
const { [REMOVE_MEMBER]: _flag, ...fields } = entry
|
||||
if (at != null) {
|
||||
merged[at] = mergeFields(merged[at] as Config, fields)
|
||||
} else {
|
||||
where.set(key, merged.length)
|
||||
merged.push(Object.fromEntries(Object.entries(fields).filter(([, v]) => v != null)))
|
||||
}
|
||||
})
|
||||
return merged.filter((_, i) => !dropped.has(i))
|
||||
}
|
||||
|
||||
/**
|
||||
* update_node 的 config 落到节点上:
|
||||
* 1. 顶层按字段浅合并。写 null 删键;没写的保留;args、output_schema 这类嵌套对象整个换掉。
|
||||
* 2. 只有 supervisor 的 agents 是列表时,成员按 name(没名字按 agentN)合并;
|
||||
* 成员自己的字段同样浅合并(没写 tools 的保留原来的 tools)。
|
||||
* 3. {name, remove: true} 删掉那个成员;不认识的名字接在后面,写 null 的字段不留。
|
||||
*/
|
||||
export function mergeNodeConfig(nodeType: string, old: Config, patch: Config): Config {
|
||||
let next = patch
|
||||
if (nodeType === 'supervisor' && Array.isArray(patch.agents)) {
|
||||
const members = Array.isArray(old.agents) ? old.agents : []
|
||||
next = { ...patch, agents: mergeMembers(members, patch.agents) }
|
||||
}
|
||||
return mergeFields(old, next)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 工具绑定变化
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** GraphSpec 的节点和画布上的 FlowNode 都认:FlowNode 的 type 是 'card',真类型在 data.nodeType */
|
||||
interface NodeLike {
|
||||
id: string
|
||||
type?: string
|
||||
data?: { nodeType?: string; label?: string; config?: Config }
|
||||
}
|
||||
|
||||
const toolNames = (value: unknown): string[] =>
|
||||
Array.isArray(value) ? value.filter((t): t is string => typeof t === 'string' && !!t) : []
|
||||
|
||||
interface Binding { nodeId: string; member: string | null; label: string; field: string; tools: string[] }
|
||||
|
||||
/** (节点 id, 成员名) → 绑定的工具。成员名为 null 的是 agent 节点本身 */
|
||||
function bindings(nodes: NodeLike[]): Map<string, Binding> {
|
||||
const out = new Map<string, Binding>()
|
||||
for (const node of nodes) {
|
||||
const type = node.data?.nodeType ?? node.type
|
||||
const cfg = node.data?.config ?? {}
|
||||
const label = node.data?.label || node.id
|
||||
if (type === 'agent') {
|
||||
out.set(JSON.stringify([node.id, null]),
|
||||
{ nodeId: node.id, member: null, label, field: 'tools', tools: toolNames(cfg.tools) })
|
||||
} else if (type === 'supervisor' && Array.isArray(cfg.agents)) {
|
||||
cfg.agents.forEach((m: unknown, i: number) => {
|
||||
if (!isObject(m)) return
|
||||
const member = memberKey(m, i)
|
||||
out.set(JSON.stringify([node.id, member]),
|
||||
{ nodeId: node.id, member, label, field: `agents[${i}].tools`, tools: toolNames(m.tools) })
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 改图前后都在、而绑定的工具不一样了的节点和成员,按改后的图排序。和后端 tool_changes
|
||||
* 同一套口径:新加、删掉的节点不算,那是结构变化,回执本来就会列出来。
|
||||
* 老后端的 final 不带 tool_changes 时用它自己比。
|
||||
*/
|
||||
export function toolChangesOf(before: NodeLike[], after: NodeLike[]): ToolChange[] {
|
||||
const old = bindings(before)
|
||||
const out: ToolChange[] = []
|
||||
for (const [key, now] of bindings(after)) {
|
||||
const was = old.get(key)
|
||||
if (!was) continue
|
||||
const a = new Set(was.tools)
|
||||
const b = new Set(now.tools)
|
||||
if (a.size === b.size && [...a].every((t) => b.has(t))) continue
|
||||
out.push({
|
||||
node_id: now.nodeId, label: now.label, member: now.member, field: now.field,
|
||||
before: was.tools, after: now.tools,
|
||||
added: now.tools.filter((t) => !a.has(t)),
|
||||
removed: was.tools.filter((t) => !b.has(t)),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 工具集合变小了的那几条。换一个工具(数量没少)是正常改图,不算 */
|
||||
export function shrunkTools(changes: ToolChange[]): ToolChange[] {
|
||||
return changes.filter((c) => c.removed.length > 0 && new Set(c.after).size < new Set(c.before).size)
|
||||
}
|
||||
|
||||
/** 回执里的一行:「数据查询」:db_query__shop、db_schema__shop → 空 */
|
||||
export function describeToolChange(c: ToolChange): string {
|
||||
const who = c.member ? `「${c.label}」的成员「${c.member}」` : `「${c.label}」`
|
||||
const list = (xs: string[]) => (xs.length ? xs.join('、') : '空')
|
||||
return `${who}:${list(c.before)} → ${list(c.after)}`
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* 校验问题 → 能定位的东西:哪一类(图级 / 节点 / 边)、哪个节点、节点里的哪个字段。
|
||||
*
|
||||
* 后端的 ValidationIssue 只带 node_id / edge_id,不带字段。可检查器要把消息落到具体
|
||||
* 输入框下面——「分支「协作」的条件写错了」只挂在面板顶上,人还得自己去找是第几个
|
||||
* case。这里按两条线索补上字段:
|
||||
* 检查器要把消息落到具体输入框下面——「分支「协作」的条件写错了」只挂在面板顶上,人还得
|
||||
* 自己去找是第几个 case。后端给了 field 就用它;老后端不给时按两条线索补上:
|
||||
* 1. 消息里带 {{ path }} 的(变量问题),去节点配置里找写着这个引用的字段;
|
||||
* 2. 其余按后端 schema.py 里那几句固定说法认(「跳过条件」「分支「X」的条件」……)。
|
||||
* 认不出来的就不认,留在面板顶部,不猜。后端哪天给了 field,优先用它。
|
||||
* 认不出来的就不认,留在面板顶部,不猜。
|
||||
*
|
||||
* 例外是「提示词要求用 X,但没绑定」:后端的 field 指着点名的那句提示词,可修法在工具
|
||||
* 那一栏,定位落到工具上(见 toolBindingOf)。
|
||||
*/
|
||||
import type { FlowNode } from '../store/studio'
|
||||
import type { ValidationIssue } from '../types'
|
||||
@@ -59,6 +61,53 @@ function findText(config: Record<string, any>, needle: string): string | null {
|
||||
return walk(config, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* 「提示词要求用「X」,但节点没有绑定它」这一类(后端 schema._check_named_tools)。
|
||||
* 点了名的是 error,只是「提到了」的是 warning;笼统的「要求调用工具,但没有绑定任何工具」
|
||||
* 没有点名。三种的修法都是去绑工具
|
||||
*/
|
||||
const NAMED_TOOL = /(?:要求用|提到了)「([^」]+)」,但/
|
||||
const VAGUE_TOOL = /要求调用工具,但(?:这个节点|这个成员)没有绑定任何工具/
|
||||
|
||||
/** 这条问题要绑的是哪个工具。不是这一类、或者没有点名,返回 null */
|
||||
export function unboundToolOf(message: string): string | null {
|
||||
return NAMED_TOOL.exec(message)?.[1] ?? null
|
||||
}
|
||||
|
||||
/** 工具没绑的问题落到哪一栏:agent 的「可用工具」,或者那个成员的工具;协作目标点的名落到成员列表 */
|
||||
function toolBindingOf(issue: ValidationIssue, node: FlowNode): FieldRef | null {
|
||||
if (!NAMED_TOOL.test(issue.message) && !VAGUE_TOOL.test(issue.message)) return null
|
||||
const at = issue.field ? parseFieldPath(issue.field) : null
|
||||
if (at?.key === 'agents' && at.index != null) return { key: 'agents', index: at.index, sub: 'tools' }
|
||||
if (node.data.nodeType === 'supervisor') return { key: 'agents' }
|
||||
if (node.data.nodeType === 'agent') return { key: 'tools' }
|
||||
return at
|
||||
}
|
||||
|
||||
const toolList = (v: unknown): string[] => (Array.isArray(v) ? v.filter((t) => typeof t === 'string') : [])
|
||||
|
||||
/**
|
||||
* 一键绑定:把 tool 加进 at 指着的那一栏(agent 的 tools,或第 i 个成员的 tools),返回新的
|
||||
* config。已经绑了、或者 at 指的不是工具栏,返回 null——按钮就不出现
|
||||
*/
|
||||
export function withToolBound(
|
||||
config: Record<string, any>, at: FieldRef | null | undefined, tool: string,
|
||||
): Record<string, any> | null {
|
||||
if (!at) return null
|
||||
if (at.key === 'tools' && at.index == null) {
|
||||
const cur = toolList(config.tools)
|
||||
return cur.includes(tool) ? null : { ...config, tools: [...cur, tool] }
|
||||
}
|
||||
if (at.key === 'agents' && at.index != null && at.sub === 'tools' && Array.isArray(config.agents)) {
|
||||
const member = config.agents[at.index]
|
||||
if (!member || typeof member !== 'object') return null
|
||||
const cur = toolList(member.tools)
|
||||
if (cur.includes(tool)) return null
|
||||
return { ...config, agents: config.agents.map((a: any, i: number) => (i === at.index ? { ...a, tools: [...cur, tool] } : a)) }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 后端 schema.py 的固定说法 → 字段。顺序有讲究:具体的在前 */
|
||||
const RULES: [RegExp, string][] = [
|
||||
[/^跳过条件/, 'skip_if'],
|
||||
@@ -74,9 +123,9 @@ const RULES: [RegExp, string][] = [
|
||||
[/代码把输出交给/, 'code'],
|
||||
]
|
||||
|
||||
export function fieldOfIssue(
|
||||
issue: ValidationIssue & { field?: string | null }, node: FlowNode | undefined,
|
||||
): FieldRef | null {
|
||||
export function fieldOfIssue(issue: ValidationIssue, node: FlowNode | undefined): FieldRef | null {
|
||||
const binding = node ? toolBindingOf(issue, node) : null
|
||||
if (binding) return binding
|
||||
if (issue.field) return parseFieldPath(issue.field)
|
||||
if (!node) return null
|
||||
const config = node.data.config ?? {}
|
||||
|
||||
@@ -195,7 +195,21 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
fields: [
|
||||
{ key: 'goal', label: '团队目标', type: 'prompt' },
|
||||
{ key: 'agents', label: '团队成员', type: 'agents' },
|
||||
{ key: 'max_rounds', label: '最大轮次', type: 'number', min: 1, max: 25 },
|
||||
// 叫「最多轮数」:团队用完轮数的报错和右栏都说「调大『最多轮数』」,字段名得对得上
|
||||
{ key: 'max_rounds', label: '最多轮数', type: 'number', min: 1, max: 25 },
|
||||
{
|
||||
// 以前轮数用完就把成员最后的原话当成功结果交出去:成员一直没查到数、只会输出
|
||||
// 工具调用的原始标记,运行照样显示「已完成」。默认改成判失败,降档要自己选
|
||||
key: 'on_exhausted', label: '用完轮数时', type: 'select',
|
||||
// 没写和写 fail 是一回事(后端只认 degrade)。选项用 fail:没写时下拉框落在第一项上
|
||||
options: [
|
||||
{ value: 'fail', label: '判为失败(默认)' },
|
||||
{ value: 'degrade', label: '降档交付' },
|
||||
],
|
||||
help: '最后一轮调度者仍没判定完成时怎么收场。判为失败:节点报错、运行停下,并点出一次都没'
|
||||
+ '被派到的成员;降档交付:把成员最后的原话交给下游,标上「未完成」,出具和复核随之降档。'
|
||||
+ '要出数、要出报告的,留在判为失败',
|
||||
},
|
||||
{
|
||||
key: 'max_parallel', label: '每轮最多同时派几人', type: 'number', min: 1, max: 6,
|
||||
help: '互不依赖的任务调度者可以放在同一轮同时执行,总耗时按最慢的那个算。'
|
||||
|
||||
@@ -48,7 +48,9 @@ export const STUDIO_SHORTCUTS: StudioShortcut[] = [
|
||||
{ id: 'delete', combo: 'Backspace', alt: ['Delete'], label: '删除选中的节点或连线', group: '编辑', passive: true },
|
||||
|
||||
{ id: 'focus', combo: 'F', label: '镜头对准选中的节点(运行中没有选中时:逐个对准要处理的节点)', group: '画布' },
|
||||
{ id: 'fit', combo: 'Shift+1', label: '缩放到看全所有节点', group: '画布' },
|
||||
// 它回到打开时的取景(从入口看起,缩放不低于可读下限),不是「看全所有节点」:大图上
|
||||
// 看全要把卡片缩到读不清。真要看全,用画布左下角的「适配全图」
|
||||
{ id: 'fit', combo: 'Shift+1', label: '重新取景(回到打开时的视角,从入口看起)', group: '画布' },
|
||||
{ id: 'layout', combo: 'Shift+L', label: '自动排版', group: '画布' },
|
||||
{ id: 'search', combo: '/', label: '搜索节点库', group: '画布' },
|
||||
{ id: 'nextProblem', combo: 'F8', label: '跳到下一个问题', group: '画布' },
|
||||
|
||||
@@ -313,6 +313,161 @@
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
/* 看运行时选中了跑过的节点:属性面板不自动盖上右栏,这里给一个明确的入口 */
|
||||
.sf-peek {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
max-width: 260px;
|
||||
pointer-events: auto;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border-strong);
|
||||
background: color-mix(in srgb, var(--bg-panel) 92%, transparent);
|
||||
box-shadow: var(--elev-1);
|
||||
color: var(--text-dim);
|
||||
font-size: var(--text-2xs);
|
||||
line-height: 18px;
|
||||
white-space: nowrap;
|
||||
transition: color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.sf-peek:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
.sf-peek:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.sf-peek-name {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Copilot 这一轮删掉的节点:原地一道虚线框,停一下再淡出(时长和 FlowCanvas 的
|
||||
GHOST_MS 一致)。框在画布坐标里,跟着平移缩放;标签的字按缩放补回来,精简档里
|
||||
(窄画布打开就是 0.4)也不小于 11px,到远景档才跟着缩小。长名字由 max-width 截成省略号 */
|
||||
.sf-ghost {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
border: 1.5px dashed color-mix(in srgb, var(--nt, var(--text-faint)) 60%, var(--text-faint));
|
||||
border-radius: var(--radius-lg);
|
||||
background: color-mix(in srgb, var(--nt, var(--text-faint)) 5%, transparent);
|
||||
pointer-events: none;
|
||||
animation: sf-ghost-out 2400ms var(--ease-out) forwards;
|
||||
}
|
||||
.sf-ghost-tag {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 10px;
|
||||
max-width: calc(100% - 20px);
|
||||
padding: 0 6px;
|
||||
overflow: hidden;
|
||||
transform: translateY(-50%);
|
||||
border-radius: 999px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--text-dim);
|
||||
font-size: calc(11px / min(max(var(--zoom, 1), 0.35), 1));
|
||||
line-height: 1.5;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@keyframes sf-ghost-out {
|
||||
0% { opacity: 0; }
|
||||
10% { opacity: 1; }
|
||||
70% { opacity: 1; }
|
||||
100% { opacity: 0; }
|
||||
}
|
||||
|
||||
/* 双击空白处的快速添加 */
|
||||
.sf-quick {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 312px;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-xl);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-panel);
|
||||
box-shadow: var(--elev-3);
|
||||
}
|
||||
.sf-quick-search {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--text-faint);
|
||||
}
|
||||
.sf-quick-search input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-size: var(--text-xs);
|
||||
outline: none;
|
||||
}
|
||||
.sf-quick-search input::placeholder {
|
||||
color: var(--text-faint);
|
||||
}
|
||||
.sf-quick-search:focus-within {
|
||||
color: var(--accent);
|
||||
}
|
||||
.sf-quick-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 4px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.sf-quick-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 6px;
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text-dim);
|
||||
font-size: var(--text-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sf-quick-item.is-active {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text);
|
||||
}
|
||||
.sf-quick-item .sf-dim {
|
||||
flex: none;
|
||||
font-size: var(--text-2xs);
|
||||
}
|
||||
.sf-quick-icon {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-sm);
|
||||
background: color-mix(in srgb, var(--nt) 18%, transparent);
|
||||
color: var(--nt);
|
||||
}
|
||||
.sf-quick-empty {
|
||||
padding: 10px 8px;
|
||||
color: var(--text-faint);
|
||||
font-size: var(--text-2xs);
|
||||
}
|
||||
.sf-quick-foot {
|
||||
flex: none;
|
||||
padding: 5px 10px;
|
||||
border-top: 1px solid var(--hairline);
|
||||
color: var(--text-faint);
|
||||
font-size: var(--text-2xs);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
运行胶囊(工具栏)
|
||||
-------------------------------------------------------------------------- */
|
||||
@@ -425,6 +580,15 @@
|
||||
background: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 运行类别的记号:正式实心、探索空心,颜色跟字走 */
|
||||
.sf-dot {
|
||||
flex: none;
|
||||
}
|
||||
/* 放弃停在审批上的运行:次级动作,悬停才露出危险色 */
|
||||
.sf-btn-abandon:hover:not(:disabled) {
|
||||
color: var(--st-failed);
|
||||
}
|
||||
|
||||
/* 发起浮层 */
|
||||
.sf-pop {
|
||||
position: absolute;
|
||||
@@ -537,6 +701,7 @@
|
||||
.sf-class {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 0 7px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
@@ -1280,7 +1445,8 @@
|
||||
-------------------------------------------------------------------------- */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.sf-canvas .edge-packet,
|
||||
.sf-sweep {
|
||||
.sf-sweep,
|
||||
.sf-ghost {
|
||||
display: none;
|
||||
}
|
||||
.sf-canvas[data-moment='failed'] .react-flow__edge.sf-e-cut .react-flow__edge-path,
|
||||
|
||||
Reference in New Issue
Block a user