mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-16 02:22:03 +00:00
变量表抽屉;顺便治了一个每敲一键发一次全图请求的老毛病
先说顺带修的那个,因为它是前提:validate() **零防抖**,从七个 mutation 点
直接调,其中包括 updateNode——也就是 Inspector 里每敲一个字都发一次带全图
的 POST。实测敲 15 个字 = 15 次请求。再挂一个变量分析就是翻倍,所以必须先
治:一次防抖(300ms)、两个请求并发、epoch 丢弃过期响应(图在飞行期间又改
了的话,旧答案不能覆盖新答案——校验结果闪回是最难查的那种 UI bug)。
现在敲 15 个字 = 1 次请求。
变量表另有一层跳过:**"有哪些变量"只取决于结构,不取决于文案**。节点 id、
类型、assign_to、入口字段名组成签名,改 prompt 里一个字不会触发变量分析。
抽屉本身做成挤压式而不是浮层——React Flow 的 Controls 和 MiniMap 是绝对
定位在画布容器里的,浮层会把它俩埋掉,挤压会把它俩顶上去。限高并给画布
留底(React Flow 容器高度归零会直接报 error 004),可拖拽改高,两端都夹住。
表里四列:变量 / 来自哪个节点 / 被引用几处 / 最近一次运行的值。点开右侧
详情能看到谁产出、每一处引用在哪个节点的哪个字段,点一下定位到画布。
实跑验证:
{{ input.question }} 输入 — 变量表要显示这个值
{{ vars.question }} 输入 — 变量表要显示这个值
{{ nodes.start }} 输入 — { "question": "变量表要显示这个值" }
{{ last_message }} 内置 1 处 —
另外让用户看得见**真正跑的那份代码**:代码节点送进沙箱的是 {{ }} 渲染后的
字符串,和编辑器里那份可能差很远(一个带引号或换行的值插进字符串字面量里
就把程序写坏了),而报错指的是渲染后的行号,对着自己那份怎么也数不对。
sandbox.start 现在带上渲染结果,只在真插过值时才显示(没插值的两份一模一样,
显示等于噪音)。沙箱步骤的 detail/result 也分开了:detail 是跑的什么,
result 是跑出了什么——塞一个字段里的话,报错时最需要的两样东西只能看见一样。
This commit is contained in:
@@ -121,8 +121,14 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 留空跟随整机默认。要的那档不可用时会安静退回默认,不阻断运行。
|
||||
isolation = ctx.cfg("isolation", "") or None
|
||||
|
||||
# 把真正要跑的那份代码发出来。用户在编辑器里写的是带 {{ }} 的模板,
|
||||
# 送进沙箱的是渲染后的字符串——两者可能差很远:一个带引号或换行的值
|
||||
# 插进字符串字面量里就会把程序写坏,而报错指的是渲染后的行号,用户对着
|
||||
# 自己那份数怎么也对不上。这条事件是他们唯一能看到"实际跑了什么"的地方。
|
||||
ctx.emit(EventType.SANDBOX_START, language=language, limits=limits.model_dump(),
|
||||
isolation=isolation or "auto")
|
||||
isolation=isolation or "auto", code=code[:8000],
|
||||
code_truncated=len(code) > 8000,
|
||||
interpolated="{{" in str(ctx.cfg("code", "")))
|
||||
result = await sandbox_manager.run(
|
||||
code,
|
||||
language=language,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {
|
||||
Approval, GraphSpec, KbDocument, MemoryItem, Provider, Run, RunEvent,
|
||||
Skill, ToolInfo, ValidationIssue, Workflow,
|
||||
Skill, ToolInfo, ValidationIssue, VarIssue, Variable, Workflow,
|
||||
} from '../types'
|
||||
|
||||
const BASE = '/api'
|
||||
@@ -74,6 +74,9 @@ export const api = {
|
||||
`/workflows/${id}/publish`, { level, version }),
|
||||
validate: (graph: GraphSpec) =>
|
||||
post<{ ok: boolean; issues: ValidationIssue[] }>('/workflows/validate', { graph }),
|
||||
/** 这张图里有哪些变量、谁产出、谁引用。纯静态分析,不需要跑过 */
|
||||
variables: (graph: GraphSpec) =>
|
||||
post<{ variables: Variable[]; issues: VarIssue[] }>('/workflows/variables', { graph }),
|
||||
},
|
||||
|
||||
// ---- 运行 ----
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, ChevronDown, Crosshair, Database, Hash, Info, Package, Variable as VarIcon, X,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { useStudio } from '../store/studio'
|
||||
import type { Variable, VarIssue } from '../types'
|
||||
|
||||
/**
|
||||
* 画布底部的变量抽屉。
|
||||
*
|
||||
* 这套编排靠 `{{ }}` 串数据流,但"这张图里到底有哪些变量"此前在界面上
|
||||
* 根本无处可查——只能靠翻每个节点的 assign_to 自己拼。拼错一个名字还不会
|
||||
* 报错(模板取不到值渲染成空字符串),于是排查只能靠猜。
|
||||
*
|
||||
* 做成挤压式而不是浮层:React Flow 的 Controls 和 MiniMap 是绝对定位在
|
||||
* 画布容器里的,浮层会把它俩埋掉;挤压会把它俩顶上去。代价是画布底部被
|
||||
* 裁掉一截(React Flow v12 的 ResizeObserver 只更新尺寸,不会自动重新取景),
|
||||
* 所以要限高,并且保证画布至少剩一截——高度归零时 React Flow 会直接报错。
|
||||
*/
|
||||
const MIN_CANVAS = 200
|
||||
const DEFAULT_HEIGHT = 260
|
||||
|
||||
export function VariablesDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const variables = useStudio((s) => s.variables)
|
||||
const varIssues = useStudio((s) => s.varIssues)
|
||||
const analyzeNow = useStudio((s) => s.analyzeNow)
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
const [height, setHeight] = useState(DEFAULT_HEIGHT)
|
||||
|
||||
// 打开时立刻算一次:变量表是按结构签名跳过的,可能已经很久没刷新了
|
||||
useEffect(() => { if (open) void analyzeNow() }, [open, analyzeNow])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const selected = variables.find((v) => v.path === picked) ?? null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative z-10 flex shrink-0 flex-col border-t bg-panel"
|
||||
style={{ height, maxHeight: `max(${MIN_CANVAS}px, 60vh)` }}
|
||||
>
|
||||
<ResizeHandle height={height} onResize={setHeight} />
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2 border-b px-3 py-1.5">
|
||||
<VarIcon size={12} style={{ color: 'var(--accent)' }} />
|
||||
<span className="text-[11.5px] font-semibold">变量</span>
|
||||
<span className="text-[10px] text-faint">{variables.length} 个</span>
|
||||
<IssueChips issues={varIssues} />
|
||||
<span className="flex-1" />
|
||||
<button className="rounded p-1 text-faint transition-colors hover:bg-hover"
|
||||
title="收起(⌥V)" onClick={onClose}>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<div className="min-w-0 flex-1 overflow-y-auto">
|
||||
<VarTable variables={variables} picked={picked} onPick={setPicked} />
|
||||
</div>
|
||||
{selected && (
|
||||
<div className="w-[300px] shrink-0 overflow-y-auto border-l">
|
||||
<VarDetail variable={selected} onClose={() => setPicked(null)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 拖拽改高。上下都要夹住:高度归零会让 React Flow 直接报错 004。 */
|
||||
function ResizeHandle({ height, onResize }: {
|
||||
height: number; onResize: (h: number) => void
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-x-0 -top-1 z-10 h-2 cursor-row-resize"
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault()
|
||||
const startY = e.clientY
|
||||
const startH = height
|
||||
const max = Math.max(MIN_CANVAS, window.innerHeight * 0.6)
|
||||
const move = (ev: PointerEvent) => {
|
||||
onResize(Math.min(max, Math.max(120, startH - (ev.clientY - startY))))
|
||||
}
|
||||
const up = () => {
|
||||
window.removeEventListener('pointermove', move)
|
||||
window.removeEventListener('pointerup', up)
|
||||
}
|
||||
window.addEventListener('pointermove', move)
|
||||
window.addEventListener('pointerup', up)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function IssueChips({ issues }: { issues: VarIssue[] }) {
|
||||
const errors = issues.filter((i) => i.level === 'error').length
|
||||
const warns = issues.filter((i) => i.level === 'warning').length
|
||||
const infos = issues.filter((i) => i.level === 'info').length
|
||||
return (
|
||||
<>
|
||||
{errors > 0 && (
|
||||
<span className="chip" style={{ color: 'var(--err)', borderColor: 'var(--err)' }}>
|
||||
<AlertTriangle size={9} /> {errors} 个引用不到
|
||||
</span>
|
||||
)}
|
||||
{warns > 0 && (
|
||||
<span className="chip" style={{ color: 'var(--warn)' }}>{warns} 个取值时机不对</span>
|
||||
)}
|
||||
{infos > 0 && <span className="chip text-faint">{infos} 个没人用</span>}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const KIND_META: Record<string, { icon: typeof Hash; text: string }> = {
|
||||
input: { icon: Database, text: '入口输入' },
|
||||
var: { icon: VarIcon, text: '节点写入' },
|
||||
node: { icon: Package, text: '节点输出' },
|
||||
builtin: { icon: Hash, text: '内置' },
|
||||
}
|
||||
|
||||
function VarTable({ variables, picked, onPick }: {
|
||||
variables: Variable[]; picked: string | null; onPick: (p: string | null) => void
|
||||
}) {
|
||||
const runtime = useRuntimeValues()
|
||||
|
||||
if (!variables.length) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-[11px] text-faint">
|
||||
画布上还没有节点
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<table className="w-full text-[11px]">
|
||||
<thead className="sticky top-0 bg-panel">
|
||||
<tr className="border-b text-left text-[10px] text-faint">
|
||||
<th className="px-3 py-1.5 font-medium">变量</th>
|
||||
<th className="px-2 py-1.5 font-medium">来自</th>
|
||||
<th className="px-2 py-1.5 font-medium">被引用</th>
|
||||
<th className="px-2 py-1.5 font-medium">最近一次运行的值</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{variables.map((v) => {
|
||||
const meta = KIND_META[v.kind] ?? KIND_META.builtin
|
||||
const value = runtime[v.path]
|
||||
return (
|
||||
<tr
|
||||
key={v.path}
|
||||
className={clsx('cursor-pointer border-b last:border-0 hover:bg-hover',
|
||||
picked === v.path && 'bg-hover')}
|
||||
onClick={() => onPick(picked === v.path ? null : v.path)}
|
||||
>
|
||||
<td className="px-3 py-1.5">
|
||||
<span className="mono" style={{ color: 'var(--accent)' }}>
|
||||
{`{{ ${v.path} }}`}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-1.5 text-dim">
|
||||
<span className="flex items-center gap-1">
|
||||
<meta.icon size={10} className="shrink-0 text-faint" />
|
||||
<span className="truncate">{v.produced_by_label || meta.text}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-1.5">
|
||||
{v.refs.length
|
||||
? <span className="text-dim">{v.refs.length} 处</span>
|
||||
: <span className="text-faint">—</span>}
|
||||
</td>
|
||||
<td className="max-w-0 px-2 py-1.5">
|
||||
{value === undefined
|
||||
? <span className="text-faint">—</span>
|
||||
: <span className="mono block truncate text-dim" title={value}>{value}</span>}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
function VarDetail({ variable, onClose }: { variable: Variable; onClose: () => void }) {
|
||||
const select = useStudio((s) => s.select)
|
||||
const runtime = useRuntimeValues()
|
||||
const value = runtime[variable.path]
|
||||
|
||||
return (
|
||||
<div className="p-2.5">
|
||||
<div className="mb-1.5 flex items-start gap-2">
|
||||
<span className="mono min-w-0 flex-1 break-all text-[11.5px]"
|
||||
style={{ color: 'var(--accent)' }}>
|
||||
{`{{ ${variable.path} }}`}
|
||||
</span>
|
||||
<button className="rounded p-0.5 text-faint hover:bg-hover" onClick={onClose}>
|
||||
<ChevronDown size={12} className="-rotate-90" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mb-2 text-[10.5px] leading-relaxed text-faint">{variable.label}</div>
|
||||
{variable.description && (
|
||||
<div className="mb-2 rounded bg-bg px-2 py-1.5 text-[10.5px] leading-relaxed text-dim">
|
||||
{variable.description}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{variable.produced_by && (
|
||||
<Section title="谁产出">
|
||||
<button className="flex w-full items-center gap-1.5 rounded px-1 py-1 text-left text-[10.5px] text-dim hover:bg-hover"
|
||||
onClick={() => select(variable.produced_by!)}>
|
||||
<Crosshair size={10} className="shrink-0 text-faint" />
|
||||
<span className="min-w-0 flex-1 truncate">{variable.produced_by_label}</span>
|
||||
</button>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title={`被引用 ${variable.refs.length} 处`}>
|
||||
{variable.refs.length ? variable.refs.map((r, i) => (
|
||||
<button key={i}
|
||||
className="flex w-full items-center gap-1.5 rounded px-1 py-1 text-left text-[10.5px] hover:bg-hover"
|
||||
onClick={() => select(r.node_id)}>
|
||||
<Crosshair size={10} className="shrink-0 text-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-dim">{r.node_label}</span>
|
||||
<span className="mono shrink-0 text-[9.5px] text-faint">{r.field}</span>
|
||||
</button>
|
||||
)) : (
|
||||
<div className="px-1 py-1 text-[10.5px] text-faint">
|
||||
没有任何地方引用它。改图改了一半的话这很正常
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="最近一次运行的值">
|
||||
{value === undefined ? (
|
||||
<div className="px-1 text-[10.5px] leading-relaxed text-faint">
|
||||
这次运行里没有它的记录。跑一次就能看到
|
||||
</div>
|
||||
) : (
|
||||
<pre className="mono max-h-40 overflow-auto whitespace-pre-wrap rounded bg-bg px-2 py-1.5 text-[10px] leading-relaxed text-dim">
|
||||
{value}
|
||||
</pre>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-2">
|
||||
<div className="mb-0.5 text-[10px] font-semibold uppercase tracking-wide text-faint">
|
||||
{title}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个变量在最近一次运行里的实际取值。
|
||||
*
|
||||
* 从事件里读,不从别处猜:node.finished 现在带 vars(那一步往变量池写了
|
||||
* 什么)和 preview(那一步自己的输出)。以前 vars 不在任何事件里,只能从
|
||||
* preview 反推 data ?? text ?? output——那个推断大多数时候对,而一个
|
||||
* "大多数时候对"的调试工具比没有更糟。
|
||||
*/
|
||||
function useRuntimeValues(): Record<string, string> {
|
||||
const events = useStudio((s) => s.events)
|
||||
return useMemo(() => {
|
||||
const out: Record<string, string> = {}
|
||||
const show = (v: unknown) =>
|
||||
typeof v === 'string' ? v : JSON.stringify(v, null, 2) ?? String(v)
|
||||
for (const e of events) {
|
||||
if (e.type !== 'node.finished') continue
|
||||
const d: any = e.data ?? {}
|
||||
for (const [k, v] of Object.entries(d.vars ?? {})) {
|
||||
out[`vars.${k}`] = show(v)
|
||||
// 入口节点写进 vars 的那几个同时也是 input.*
|
||||
if (e.node_id && d.preview && typeof d.preview === 'object' && k in d.preview) {
|
||||
out[`input.${k}`] = show(v)
|
||||
}
|
||||
}
|
||||
if (e.node_id && d.preview !== undefined && d.preview !== null) {
|
||||
out[`nodes.${e.node_id}`] = show(d.preview)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}, [events])
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, Check, ChevronDown, Copy, LayoutGrid, Plus, Save, ShieldCheck,
|
||||
Trash2, Wand2,
|
||||
Trash2, Variable, Wand2,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { FlowCanvas } from '../canvas/FlowCanvas'
|
||||
import { Palette } from '../canvas/Palette'
|
||||
import { InspectorSheet } from '../canvas/InspectorSheet'
|
||||
import { VariablesDrawer } from '../canvas/VariablesDrawer'
|
||||
import { AssistantPanel } from '../run/AssistantPanel'
|
||||
import { RunControl } from '../run/RunControl'
|
||||
import { useStudio, toGraph } from '../store/studio'
|
||||
@@ -27,6 +28,7 @@ export function StudioPage() {
|
||||
const [picker, setPicker] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [publishing, setPublishing] = useState(false)
|
||||
const [vars, setVars] = useState(false)
|
||||
const copilotActive = useStudio((s) => s.copilot.active)
|
||||
|
||||
// 首次进来自动打开第一张图
|
||||
@@ -146,6 +148,13 @@ export function StudioPage() {
|
||||
>
|
||||
<Wand2 size={12} /> Copilot
|
||||
</button>
|
||||
<button
|
||||
className={clsx('btn', vars && 'text-[var(--accent)]')}
|
||||
title="看这张图里有哪些变量、谁产出、谁引用(⌥V)"
|
||||
onClick={() => setVars((v) => !v)}
|
||||
>
|
||||
<Variable size={12} /> 变量
|
||||
</button>
|
||||
<button className="btn" onClick={relayout} title="自动排版"><LayoutGrid size={12} /></button>
|
||||
<button className="btn" onClick={() => setPublishing(true)} disabled={!workflow || dirty}
|
||||
title={dirty ? '先保存再发布' : '把当前版本立为正式版本,正式运行只认它'}>
|
||||
@@ -164,8 +173,13 @@ export function StudioPage() {
|
||||
<aside className="w-52 shrink-0 border-r bg-panel">
|
||||
<Palette />
|
||||
</aside>
|
||||
<main className="relative min-w-0 flex-1">
|
||||
<FlowCanvas />
|
||||
{/* 变量抽屉做成挤压式而不是浮层:React Flow 的 Controls 和 MiniMap
|
||||
是绝对定位在画布容器里的,浮层会把它俩埋掉,挤压会把它俩顶上去 */}
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
<div className="min-h-0 flex-1">
|
||||
<FlowCanvas />
|
||||
</div>
|
||||
<VariablesDrawer open={vars} onClose={() => setVars(false)} />
|
||||
</main>
|
||||
{/* 助手常驻,属性是盖在它上面的一层。做成两个 tab 的话它们就互斥了,
|
||||
而这两件事在时间上并不互斥——跑图跑到一半点开节点看配置,整条
|
||||
|
||||
@@ -517,6 +517,13 @@ export function decodeRun(events: RunEvent[]): Step[] {
|
||||
const step: Step = {
|
||||
id: `sb-${seq}`, seq, kind: 'code', nodeId, status: 'running',
|
||||
title: `运行${d.language === 'python' ? ' Python' : d.language ? ` ${d.language}` : ''}代码`,
|
||||
// 渲染后的代码。编辑器里那份带着 {{ }},送进沙箱的是替换完的——
|
||||
// 值里有引号或换行就会把程序写坏,而报错说的是渲染后的行号。
|
||||
// 只有插过值的才值得摆出来,没插值的两份一模一样,显示等于噪音
|
||||
detail: d.interpolated && d.code
|
||||
? `# 实际执行的代码(模板已展开)\n${String(d.code)}`
|
||||
+ (d.code_truncated ? '\n\n(已截断)' : '')
|
||||
: undefined,
|
||||
}
|
||||
push(step, nodeId)
|
||||
return step
|
||||
@@ -530,7 +537,11 @@ export function decodeRun(events: RunEvent[]): Step[] {
|
||||
if (!d.ok) step.level = 'error'
|
||||
step.meta = dur(num(d.duration_ms))
|
||||
const body = [d.stdout, d.stderr].filter(Boolean).join('\n').slice(0, 4000)
|
||||
step.detail = body || (d.ok ? '(无输出)' : `退出码 ${d.exit_code}`)
|
||||
// 和查询步骤同一个分工:detail 是"跑的是什么"(渲染后的代码),
|
||||
// result 是"跑出了什么"。塞进同一个字段的话,报错时最需要的两样
|
||||
// 东西——实际代码和 traceback——只能看见一样
|
||||
step.result = body || (d.ok ? '(无输出)' : `退出码 ${d.exit_code}`)
|
||||
if (!step.detail) step.detail = step.result
|
||||
pendingTools.delete(`sandbox-${nodeId ?? seq}`)
|
||||
}
|
||||
break
|
||||
|
||||
@@ -7,7 +7,8 @@ import { api, streamCopilot, streamRun } from '../api/client'
|
||||
import { NODE_DEFS, sourceHandles } from '../canvas/nodeDefs'
|
||||
import type { CopilotOp } from '../run/decode'
|
||||
import type {
|
||||
GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ValidationIssue, Workflow,
|
||||
GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ValidationIssue,
|
||||
VarIssue, Variable, Workflow,
|
||||
} from '../types'
|
||||
|
||||
export type FlowNode = Node<{ nodeType: NodeType; label: string; config: Record<string, any> }>
|
||||
@@ -92,6 +93,10 @@ interface StudioState {
|
||||
selectedId: string | null
|
||||
dirty: boolean
|
||||
issues: ValidationIssue[]
|
||||
/** 这张图里有哪些变量:谁产出、谁引用。结构不变就不重新请求 */
|
||||
variables: Variable[]
|
||||
/** 变量层面的提示(含"产出了没人用"这类 info,不进 issues) */
|
||||
varIssues: VarIssue[]
|
||||
|
||||
run: Run | null
|
||||
events: RunEvent[]
|
||||
@@ -130,6 +135,7 @@ interface StudioState {
|
||||
select: (id: string | null) => void
|
||||
save: () => Promise<void>
|
||||
validate: () => Promise<void>
|
||||
analyzeNow: () => Promise<void>
|
||||
|
||||
startRun: (input: Record<string, any>) => Promise<Run | null>
|
||||
startFormalRun: (input: Record<string, any>) => Promise<Run | null>
|
||||
@@ -145,6 +151,60 @@ interface StudioState {
|
||||
|
||||
const EMPTY_RUNTIME: NodeRuntime = { status: 'idle' }
|
||||
|
||||
// 300ms:比连续打字的间隔长,比"停下来看结果"的感知阈值短
|
||||
const ANALYZE_DEBOUNCE_MS = 300
|
||||
let analyzeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
/** 每次发起分析自增。回来时对不上就说明图又改过了,这个结果已经过期 */
|
||||
let analyzeEpoch = 0
|
||||
/** 上一次算变量表时的结构签名,没变就不重复请求 */
|
||||
let lastVarSignature = ''
|
||||
|
||||
/**
|
||||
* "有哪些变量"只取决于图的结构,不取决于文案。
|
||||
*
|
||||
* 节点 id、类型、assign_to、入口字段名——只有这些变了,变量集合才会变。
|
||||
* 改 prompt 里的一个字不该触发一次变量分析。
|
||||
*/
|
||||
function varSignature(nodes: FlowNode[]): string {
|
||||
return nodes
|
||||
.map((n) => {
|
||||
const cfg = n.data.config ?? {}
|
||||
const fields = (cfg.fields ?? []).map((f: any) => f?.name ?? '').join(',')
|
||||
return `${n.id}:${n.data.nodeType}:${cfg.assign_to ?? ''}:${fields}`
|
||||
})
|
||||
.sort()
|
||||
.join('|')
|
||||
}
|
||||
|
||||
async function runAnalysis(set: any, get: any, force = false): Promise<void> {
|
||||
const { nodes, edges } = get()
|
||||
if (!nodes.length) {
|
||||
set({ issues: [], variables: [], varIssues: [] })
|
||||
return
|
||||
}
|
||||
const epoch = ++analyzeEpoch
|
||||
const graph = toGraph(nodes, edges)
|
||||
const signature = varSignature(nodes)
|
||||
const needVars = force || signature !== lastVarSignature
|
||||
|
||||
try {
|
||||
const [validation, vars] = await Promise.all([
|
||||
api.workflows.validate(graph),
|
||||
needVars ? api.workflows.variables(graph) : Promise.resolve(null),
|
||||
])
|
||||
// 图在请求飞行期间又改了,这份结果已经不对应眼前的图——丢掉,
|
||||
// 别用旧答案覆盖新答案(校验结果闪回是最难查的那种 UI bug)
|
||||
if (epoch !== analyzeEpoch) return
|
||||
set({ issues: validation.issues ?? [] })
|
||||
if (vars) {
|
||||
lastVarSignature = signature
|
||||
set({ variables: vars.variables ?? [], varIssues: vars.issues ?? [] })
|
||||
}
|
||||
} catch {
|
||||
/* 分析失败不影响编辑 */
|
||||
}
|
||||
}
|
||||
|
||||
export const useStudio = create<StudioState>((set, get) => ({
|
||||
workflow: null,
|
||||
nodes: [],
|
||||
@@ -152,6 +212,8 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
selectedId: null,
|
||||
dirty: false,
|
||||
issues: [],
|
||||
variables: [],
|
||||
varIssues: [],
|
||||
run: null,
|
||||
events: [],
|
||||
runtime: {},
|
||||
@@ -299,18 +361,32 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
set({ workflow: updated, dirty: false })
|
||||
},
|
||||
|
||||
/**
|
||||
* 校验 + 变量分析。名字保留 validate,因为图一变就该重算的地方有八处,
|
||||
* 都在调它。
|
||||
*
|
||||
* 防抖是必须的,不是优化:在此之前它是**零防抖**的——Inspector 里每敲
|
||||
* 一个键都会 updateNode → validate(),实测敲 15 个字发 15 次全图 POST,
|
||||
* 每次都把整张图序列化上传。再挂一个变量分析就是翻倍。
|
||||
*
|
||||
* 变量表另外按结构签名跳过:改 prompt 文本不会改变"有哪些变量",只有
|
||||
* 增删节点、改 assign_to、改入口字段才会。签名不变就不重复请求。
|
||||
*/
|
||||
validate: async () => {
|
||||
const { nodes, edges } = get()
|
||||
const { nodes } = get()
|
||||
if (!nodes.length) {
|
||||
set({ issues: [] })
|
||||
set({ issues: [], variables: [], varIssues: [] })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = await api.workflows.validate(toGraph(nodes, edges))
|
||||
set({ issues: result.issues ?? [] })
|
||||
} catch {
|
||||
/* 校验失败不影响编辑 */
|
||||
}
|
||||
if (analyzeTimer !== null) clearTimeout(analyzeTimer)
|
||||
analyzeTimer = setTimeout(() => void runAnalysis(set, get), ANALYZE_DEBOUNCE_MS)
|
||||
},
|
||||
|
||||
/** 不等防抖,立刻算一次。抽屉打开、切换工作流这类明确动作用它。 */
|
||||
analyzeNow: async () => {
|
||||
if (analyzeTimer !== null) clearTimeout(analyzeTimer)
|
||||
analyzeTimer = null
|
||||
await runAnalysis(set, get, true)
|
||||
},
|
||||
|
||||
// ---- 运行 ----
|
||||
|
||||
@@ -156,3 +156,30 @@ export interface NodeRuntime {
|
||||
thinking?: string
|
||||
toolCalls?: { tool: string; args?: any; result?: string; ok?: boolean }[]
|
||||
}
|
||||
|
||||
/** 一处 {{ }} 引用 */
|
||||
export interface VarRef {
|
||||
node_id: string
|
||||
node_label: string
|
||||
field: string
|
||||
expr: string
|
||||
}
|
||||
|
||||
/** 一个可以被 {{ }} 引用的东西。由后端静态分析整张图得出 */
|
||||
export interface Variable {
|
||||
path: string
|
||||
kind: 'input' | 'var' | 'node' | 'builtin' | 'loop'
|
||||
label: string
|
||||
produced_by?: string | null
|
||||
produced_by_label?: string | null
|
||||
order: number
|
||||
refs: VarRef[]
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface VarIssue {
|
||||
level: 'error' | 'warning' | 'info'
|
||||
message: string
|
||||
node_id?: string | null
|
||||
path: string
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user