可点击证据第二期:取数链路打通、问数据的答案逐段可点;发布前自动修复

一、可点击证据第二期

取数链路
- 智能体、工具节点、代码节点、知识检索取数时都记进证据台账;报告目录按台账编出 Q1… / K1…
- 报告可以引用快照里的一格([[v:Q1.r0.gmv]]),也可以由系统从快照生成整张表([[table:Q1 cols=… rows=0-4]]),
  表里每一格都是可点的片段;取值一律以快照为准,取回快照时复验哈希
- 口径卡表达式新增 cell(x, row, column),lineage 精确到单元格
- 智能体开 cite_fields(配合 output_schema)后,循环结束做一次结构化抽取,每个字段标出取自哪次查询的哪一格,
  再到快照里核对:一致记 verified;不一致以快照为准并告警;查不到的记为空值,永远不兜底成 0
- 代码节点新增 evidence_role(source / compute)和 code_sha;沙箱算出来的数不能被报告直接引用,要进口径卡
- 查询快照记下列类型,文本列按文本渲染(年份 "2026" 不再显示成「2,026」)
- 升级前发起的运行(停在审批上的)一律走旧逻辑:新的 task 只追加在循环之后,恢复时不会错号

证据接口与面板
- 片段链接上查询步骤:SQL、被引用的行加前后各 2 行、高亮到格;数据源可设 mask_columns 遮罩列,
  遮罩在查询时记进快照,数据源事后改名或删除也照样遮罩(在有身份体系之前,遮罩只减少暴露,不是安全边界)
- 输入来源写明核对结果(与快照一致 / 模型报的值和快照不一致 / 没查到记为空);口径卡缺输入时也给出完整的链
- 受管出具要在契约里声明 cells 才能引用单元格;受管与否记在所钉版本上,改画布不再让受管版本的正式运行降级
- 口径卡可以用 caliber_from 钉住另一个已发布工作流里的口径卡,上游有新版本时按 upgrade_policy 处置,
  和子工作流同一套规则;子工作流节点也补上了升版处置的配置项

Copilot、校验与报错
- 问数据的答案里有数字时,搭 input → 智能体 → 报告 → 出口,报告直接引用查过的单元格
- 写 SQL 前核对数据源的表结构,SQL 里出现表结构里没有的列会被打回
- 不再搭「智能体文字 → 转换节点解析 JSON」这种图;转换节点的 JSON 报错分清是上游模型写坏了、
  模板里裸插了模型文字(给出 | json 的改法),还是模板本身写错了
- 工具节点遇到「查询失败」「SQL 被拒绝」判为失败;发起运行前检查绑定的工具是否存在,不存在时直接拒绝并给出入口

二、发布前自动修复

- 问题带上机器编号(code)和修复 id;新增只读接口 POST /api/workflows/{id}/publish-check 和 /autofix
- 修复分三类:答案唯一、不降低要求的一键修复;要人拿主意的给选项(不替人选);结构性问题交给 Copilot
- 一律先预览,不自动保存、不自动发布;删节点、删契约、放宽审批、关掉 strict、改级别等降低要求的改动一律拒绝,
  Copilot 的方案也要过这一关;应用后重跑检查,错误必须变少且不能冒出新的
- 发布弹窗打开就先检查;问题面板新增「发布前检查」,平时就能看到、就地修掉
- 门禁修正:契约有 report_from 时不再要求 narrative(模板⑨可以发成受管);全图默认审批为「全部放行」时同样拦下
- 修掉画布保存会抹掉全图默认(defaults)的老问题:以前任何一次保存都会把它清空,审批 always 因此被悄悄放宽

验证(沙箱):tsc 干净,生产构建通过,pytest 2268 passed(两遍),check-all 17 项检查、3915 项全过
(新增 check-publish);关键行为做了变异验证、全部抓到。
This commit is contained in:
ThearchyHelios
2026-09-28 21:20:04 +08:00
parent 62aac187d8
commit fcdcc30d4e
74 changed files with 19372 additions and 380 deletions
+195 -12
View File
@@ -3,17 +3,18 @@ import { createPortal } from 'react-dom'
import { Link } from 'react-router-dom'
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 { NODE_DEFS, syntaxOf, type FieldDef, type FieldSyntax, type NodeDef } from './nodeDefs'
import { fieldOfIssue, unboundToolOf, withToolBound, type FieldRef } from './issues'
import { hintOf } from './shortcuts'
import { isActivePhase } from '../run/trace'
import { EDIT_LOCK_TEXT, useEditLock, useStudio } from '../store/studio'
import { datasourceTools, modelOptions, useCatalog, useDatasources } from '../store/catalog'
import { api } from '../api/client'
import { IconButton, JsonInput, Modal, isComposing } from '../components/ui'
import { IconButton, JsonInput, Modal, isComposing, useRadioGroup } from '../components/ui'
import { formatShortcut } from '../lib/keys'
import { SUBGRAPH_UPGRADE_HELP, upgradeNewerText } from '../lib/terms'
import { TemplateText } from './TemplateText'
import type { ValidationIssue, WorkflowVersion } from '../types'
import type { NodeType, ValidationIssue, WorkflowVersion } from '../types'
/** 检查器里一条落到字段上的问题 */
type FieldIssue = ValidationIssue & { at: FieldRef | null }
@@ -149,6 +150,26 @@ function NodeRefsInput({ nodeId, type, value, onChange }: {
)
}
/**
* 子工作流钉住版本后的升版处置:和口径卡的是同一个下拉——直接借口径卡的字段定义,选项、
* 文案一字不差,只换说明里「和谁同一套」那半句。上游在钉住的那一版之后又发了版时,正式运行
* 前必须声明,否则挡住(后端 governance.unresolved_caliber_upgrades 两者同一套规则)
*/
const SUBGRAPH_POLICY: FieldDef | null = (() => {
const base = NODE_DEFS.metrics.fields.find((f) => f.key === 'upgrade_policy')
return base ? {
...base, help: SUBGRAPH_UPGRADE_HELP,
when: (c: Record<string, any>) => !!c.workflow_id && c.workflow_version != null && c.workflow_version !== '',
} : null
})()
/** 这个节点要画哪些字段:子工作流在「工作流」后面插上升版处置,其余照 nodeDefs */
function fieldsOf(type: NodeType, def: NodeDef): FieldDef[] {
if (type !== 'subgraph' || !SUBGRAPH_POLICY || def.fields.some((f) => f.key === 'upgrade_policy')) return def.fields
const at = def.fields.findIndex((f) => f.key === 'workflow_id')
return [...def.fields.slice(0, at + 1), SUBGRAPH_POLICY, ...def.fields.slice(at + 1)]
}
/** 属性面板。所有字段都由 nodeDefs 的声明驱动渲染,加节点类型不用改这里。 */
export function Inspector() {
const selectedId = useStudio((s) => s.selectedId)
@@ -197,7 +218,7 @@ export function Inspector() {
const setConfig = (key: string, value: any) =>
updateNode(node.id, { config: { ...config, [key]: value } })
const visible = def.fields.filter((f) => !f.when || f.when(config))
const visible = fieldsOf(node.data.nodeType, def).filter((f) => !f.when || f.when(config))
const keys = new Set(visible.map((f) => f.key))
const basic = visible.filter((f) => !f.advanced)
const advanced = visible.filter((f) => f.advanced)
@@ -382,7 +403,7 @@ function Field({ field, nodeId, value, config, issues, onChange }: {
const id = `f-${nodeId}-${field.key}`
const syntax = syntaxOf(field)
const composite = field.type === 'cases' || field.type === 'agents' || field.type === 'ioFields'
|| field.type === 'metricsList'
|| field.type === 'metricsList' || field.type === 'caliberFrom'
// 复合字段自己把问题落到第几项;落不到具体某一项的,和普通字段一样挂在下面
const own = composite ? issues.filter((i) => i.at?.index == null) : issues
const bad = own.some((i) => i.level === 'error')
@@ -390,8 +411,10 @@ function Field({ field, nodeId, value, config, issues, onChange }: {
// 长文本在 360px 宽的栏里没法写:提示词、代码可以展开到大编辑器里(同一份值,边写边存)
const expandable = (field.type === 'prompt' || field.type === 'code' || field.type === 'textarea') && syntax !== 'plain'
const [wide, setWide] = useState(false)
// 看得见、暂时用不了:说清差什么(比如先写 Schema 才能开 cite_fields)
const off = field.disabled?.(config) ?? null
return (
<div className="mb-3" data-field={field.key}>
<div className="mb-3" data-field={field.key} data-disabled={off ? '' : undefined}>
{field.type !== 'switch' && (
<div className="mb-1 flex items-center gap-1.5">
<label className="label mb-0 min-w-0 flex-1 truncate" htmlFor={composite ? undefined : id}>{field.label}</label>
@@ -413,10 +436,12 @@ function Field({ field, nodeId, value, config, issues, onChange }: {
document.body,
)}
<FieldInput field={field} id={id} nodeId={nodeId} syntax={syntax} value={value} config={config}
invalid={bad} describedBy={errorId} issues={issues} onChange={onChange} />
invalid={bad} describedBy={[errorId, off ? `${id}-off` : ''].filter(Boolean).join(' ') || undefined}
disabled={!!off} issues={issues} onChange={onChange} />
{field.help && field.type !== 'switch' && (
<div className="mt-1 text-2xs leading-snug text-faint">{field.help}</div>
)}
{off && <div id={`${id}-off`} className="mt-1 text-2xs leading-snug" style={{ color: 'var(--st-waiting)' }}>{off}</div>}
{!!own.length && (
<div id={errorId} className="mt-1 space-y-0.5">
{own.map((i, k) => <IssueLine key={k} issue={i} action={bindFix(i, config, (c) => onChange(c[field.key]))} />)}
@@ -426,9 +451,11 @@ function Field({ field, nodeId, value, config, issues, onChange }: {
)
}
function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describedBy, issues, onChange }: {
function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describedBy, disabled, issues, onChange }: {
field: FieldDef; id: string; nodeId: string; syntax: FieldSyntax; value: any
config: Record<string, any>; invalid: boolean; describedBy?: string
/** 字段的 disabled 条件成立(原因写在字段下面,由 describedBy 接上) */
disabled?: boolean
issues: FieldIssue[]; onChange: (v: any) => void
}) {
// 目录只按这个字段用得上的那一张订阅。以前每个字段都订阅整个 catalog:连接心跳、
@@ -500,9 +527,9 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
case 'switch':
return (
<label className="flex cursor-pointer items-center gap-2 py-0.5">
<input id={id} type="checkbox" checked={!!value} onChange={(e) => onChange(e.target.checked)}
className="accent-[var(--accent)]" />
<label className={clsx('flex items-center gap-2 py-0.5', disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer')}>
<input id={id} type="checkbox" checked={!!value} disabled={disabled} aria-describedby={describedBy}
onChange={(e) => onChange(e.target.checked)} className="accent-[var(--accent)]" />
<span className="text-xs">{field.label}</span>
{field.help && <span className="text-2xs text-faint">· {field.help}</span>}
</label>
@@ -574,6 +601,9 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
case 'nodeRefs':
return <NodeRefsInput nodeId={nodeId} type={field.refType} value={value} onChange={onChange} />
case 'caliberFrom':
return <CaliberFromPicker id={id} value={value} invalid={invalid} describedBy={describedBy} />
case 'agents':
return <AgentList value={value ?? []} issues={issues} config={config} onChange={onChange} />
@@ -647,9 +677,15 @@ function SubgraphPicker({ id, value, version, invalid, describedBy, onChange }:
if (!node) return
const config = { ...node.data.config }
if (v) config.workflow_version = Number(v)
else delete config.workflow_version
else {
// 跟随最新就谈不上升版:处置跟着钉的版本走,不钉了一起拿掉(撤销能找回)
delete config.workflow_version
delete config.upgrade_policy
}
updateNode(node.id, { config })
}
const pinned = version != null && String(version) !== '' ? Number(version) : null
const latest = versions?.length ? Math.max(...versions.map((v) => v.version)) : null
return (
<div className="space-y-1.5">
<select id={id} className="field" value={value ?? ''} aria-invalid={invalid || undefined} aria-describedby={describedBy}
@@ -670,12 +706,159 @@ function SubgraphPicker({ id, value, version, invalid, describedBy, onChange }:
<option key={v.id} value={v.version}>v{v.version}{v.note ? ` · ${v.note}` : ''}</option>
))}
</select>
{latest != null && pinned != null && latest > pinned && (
<div className="mt-1 text-2xs leading-snug" style={{ color: 'var(--st-waiting)' }} data-subgraph-newer="">
{upgradeNewerText(latest, pinned)}
</div>
)}
</div>
)}
</div>
)
}
/**
* 口径卡从哪来:在这里定义,或者钉住另一个工作流某一版里的口径卡(caliber_from)。
*
* 钉住时选工作流、版本、那一版图里的口径卡节点,写成 {workflow_id, workflow_version, node_id};
* 本地的名称、版本、指标定义这时不生效(后端 validate 也这么说),切过去就清掉——撤销能找回。
* 版本必须钉:不钉的话口径会跟着上游漂移。上游在钉住的那一版之后又发了版,旁边就提醒
* 要在下面声明升版处置,否则挡住正式运行(和子工作流同一套)
*/
function CaliberFromPicker({ id, value, invalid, describedBy }: {
id: string; value: any; invalid: boolean; describedBy?: string
}) {
const workflows = useCatalog((s) => s.workflows)
const self = useStudio((s) => s.workflow?.id)
const nodeId = useStudio((s) => s.selectedId)
const updateNode = useStudio((s) => s.updateNode)
const ref = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, any> : null
const wfId: string = ref?.workflow_id ? String(ref.workflow_id) : ''
const version: number | null = ref?.workflow_version != null && String(ref.workflow_version) !== ''
? Number(ref.workflow_version) : null
const [versions, setVersions] = useState<WorkflowVersion[] | null>(null)
const [graph, setGraph] = useState<{ key: string; nodes: any[] } | 'error' | null>(null)
useEffect(() => {
setVersions(null)
if (!wfId) return
let alive = true
api.workflows.versions(wfId).then((v) => { if (alive) setVersions(v) }).catch(() => { if (alive) setVersions([]) })
return () => { alive = false }
}, [wfId])
useEffect(() => {
setGraph(null)
if (!wfId || version == null || !Number.isFinite(version)) return
let alive = true
api.workflows.version(wfId, version).then(
(v) => { if (alive) setGraph({ key: `${wfId}@${version}`, nodes: Array.isArray(v?.graph?.nodes) ? v.graph!.nodes : [] }) },
() => { if (alive) setGraph('error') },
)
return () => { alive = false }
}, [wfId, version])
/** 改这个节点的配置:钉住的来源和本地定义是互斥的两套 */
const write = (patch: Record<string, any>, drop: string[] = []) => {
const node = nodeId ? useStudio.getState().nodes.find((n) => n.id === nodeId) : undefined
if (!node) return
const config = { ...node.data.config, ...patch }
for (const k of drop) delete config[k]
updateNode(node.id, { config })
}
const mode: 'local' | 'pinned' = ref ? 'pinned' : 'local'
const setMode = (m: 'local' | 'pinned') => {
if (m === mode) return
if (m === 'pinned') write({ caliber_from: {} }, ['caliber', 'caliber_version', 'metrics'])
else write({ caliber_version: 'v1', metrics: [{ id: 'total', name: '', unit: '', expression: '' }] },
['caliber_from', 'upgrade_policy'])
}
const radio = useRadioGroup(CALIBER_MODES, mode, setMode)
const cards = graph && graph !== 'error' ? graph.nodes.filter((n) => (n?.type ?? n?.data?.nodeType) === 'metrics') : []
const cardOf = (n: any) => ({ id: String(n.id), label: n.data?.label || n.title || '', config: n.data?.config ?? n.config ?? {} })
const chosen = cards.map(cardOf).find((c) => c.id === ref?.node_id)
const latest = versions?.length ? Math.max(...versions.map((v) => v.version)) : null
// 那一版里只有一张口径卡:直接钉上,不让人多点一次
useEffect(() => {
if (!ref || ref.node_id || cards.length !== 1) return
const only = cardOf(cards[0])
if (!only.config.caliber_from) write({ caliber_from: { ...ref, node_id: only.id } })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [graph])
return (
<div className="space-y-1.5" data-caliber-from={mode}>
<div role="radiogroup" aria-label="口径卡从哪来" className="inline-flex rounded-md border p-px" aria-describedby={describedBy}>
{CALIBER_MODES.map((m) => (
<button key={m} type="button" {...radio(m)} onClick={() => setMode(m)}
className={clsx('rounded px-2 py-0.5 text-2xs', mode === m ? 'bg-accent-soft text-fg' : 'text-faint hover:text-dim')}>
{m === 'local' ? '在这里定义' : '钉住别的工作流里的口径卡'}
</button>
))}
</div>
{ref && (
<>
<select id={id} className="field" value={wfId} aria-label="钉住哪个工作流" aria-invalid={invalid || undefined}
style={invalid && !wfId ? { borderColor: 'var(--err)' } : undefined}
onChange={(e) => write({ caliber_from: e.target.value ? { workflow_id: e.target.value } : {} })}>
<option value="">— 选择工作流 —</option>
{workflows.filter((w) => w.id !== self).map((w) => (
<option key={w.id} value={w.id}>{w.name}{w.is_template ? '(模板)' : ''}</option>
))}
</select>
{!!wfId && (
<div>
<label className="mb-0.5 block text-2xs text-faint" htmlFor={`${id}-version`}>钉住版本(必须钉:不钉口径会跟着上游漂移)</label>
<select id={`${id}-version`} className="field" value={version ?? ''} disabled={!versions}
onChange={(e) => write({ caliber_from: { workflow_id: wfId, ...(e.target.value ? { workflow_version: Number(e.target.value) } : {}) } })}>
<option value="">{versions ? (versions.length ? '— 选择版本 —' : '这个工作流还没有保存过版本') : '正在取版本…'}</option>
{(versions ?? []).map((v) => (
<option key={v.id} value={v.version}>v{v.version}{v.published ? '(已发布)' : ''}{v.note ? ` · ${v.note}` : ''}</option>
))}
</select>
</div>
)}
{!!wfId && version != null && (
<div>
<label className="mb-0.5 block text-2xs text-faint" htmlFor={`${id}-node`}>那一版里的哪张口径卡</label>
<select id={`${id}-node`} className="field" value={ref.node_id ?? ''} disabled={!graph || graph === 'error'}
onChange={(e) => write({ caliber_from: { workflow_id: wfId, workflow_version: version, ...(e.target.value ? { node_id: e.target.value } : {}) } })}>
<option value="">{graph === 'error' ? '这一版取不到' : !graph ? '正在取这一版的图…' : cards.length ? '— 选择口径卡 —' : '这一版里没有口径卡'}</option>
{cards.map(cardOf).map((c) => (
// 它自己也是钉住别处的:定义不在这一版里,不能再往下钉
<option key={c.id} value={c.id} disabled={!!c.config.caliber_from}>
{c.label || c.id} · 口径「{c.config.caliber || '—'}」{c.config.caliber_version ?? ''}
{c.config.caliber_from ? '(它也是钉住别处的,不能再钉)' : ''}
</option>
))}
</select>
</div>
)}
{chosen && (
<div className="rounded border bg-bg px-2 py-1.5 text-2xs leading-relaxed" data-caliber-preview="">
<div>
口径「{chosen.config.caliber || '—'}」<span className="mono">{chosen.config.caliber_version ?? ''}</span>
{' · '}{Array.isArray(chosen.config.metrics) ? chosen.config.metrics.length : 0} 个指标
</div>
{Array.isArray(chosen.config.metrics) && chosen.config.metrics.length > 0 && (
<div className="mono text-faint [overflow-wrap:anywhere]">
{chosen.config.metrics.slice(0, 8).map((m: any) => m?.id).filter(Boolean).join('、')}
{chosen.config.metrics.length > 8 ? ' …' : ''}
</div>
)}
</div>
)}
{latest != null && version != null && latest > version && (
<div className="text-2xs leading-snug" style={{ color: 'var(--st-waiting)' }} data-caliber-newer="">
{upgradeNewerText(latest, version)}
</div>
)}
</>
)}
</div>
)
}
const CALIBER_MODES = ['local', 'pinned'] as const
// -------------------------------------------------------------------------
// 复合编辑器
// -------------------------------------------------------------------------
+9 -1
View File
@@ -65,8 +65,16 @@ function summarize(type: NodeType, config: Record<string, any>): string {
return first(config.title) || '人工审批 · 未填标题'
case 'validate':
return 'JSON Schema 校验' + (config.repair_with_llm ? ' · 失败自动返工' : '')
case 'metrics':
case 'metrics': {
// 钉住别的工作流里的口径卡:本地那几项不生效,写「0 个指标」会让人以为卡是空的
const from = config.caliber_from
if (from && typeof from === 'object') {
return from.workflow_id && from.workflow_version && from.node_id
? `钉住上游口径卡 v${from.workflow_version} · 节点 ${from.node_id}${config.upgrade_policy ? ` · 升版按 ${config.upgrade_policy}` : ''}`
: '钉住上游口径卡 · 还没选完'
}
return `${config.caliber || '口径'}@${config.caliber_version || 'v1'} · ${(config.metrics ?? []).length} 个指标`
}
case 'report': {
const from = Array.isArray(config.metrics_from) ? config.metrics_from.length : 0
return `${first(config.instructions) || '未填写作要求'} · ${from ? `${from} 张口径卡` : '上游全部口径卡'}`
+50 -4
View File
@@ -1,12 +1,16 @@
import { useEffect, useRef } from 'react'
import { AlertTriangle, CheckCircle2, CornerDownRight, Plus, RotateCw, Trash2, Unlink, Workflow, XCircle } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import {
AlertTriangle, CheckCircle2, CornerDownRight, ListChecks, Plus, RotateCw, ShieldCheck, Trash2, Unlink, Workflow, XCircle,
} from 'lucide-react'
import clsx from 'clsx'
import { NODE_DEFS } from './nodeDefs'
import { unboundToolOf, withToolBound, type FieldRef, type Problem } from './issues'
import { problemsOf, unboundToolOf, withToolBound, type FieldRef, type Problem } from './issues'
import { PublishPreflightPane } from './PublishDialog'
import { formatShortcut } from '../lib/keys'
import { PUBLISH_FIX_TEXT } from '../lib/terms'
import { useCatalog } from '../store/catalog'
import { useEditLock, useStudio } from '../store/studio'
import { Spinner } from '../components/ui'
import { Spinner, useRadioGroup } from '../components/ui'
/**
* 问题面板:图级、节点、边上的 error 和 warning,一条一行,点一下定位。
@@ -21,6 +25,48 @@ export function ProblemsPane({ problems, activeId, onLocate, onDeleteEdge }: {
activeId: string | null
onLocate: (p: Problem) => void
onDeleteEdge: (edgeId: string) => void
}) {
// 校验:画布上随改随查的那一份。发布前检查:按选定的发布等级另查一遍门禁,带修法——
// 在画布上就能提前发现、提前修,不用等到点发布那一刻
const [mode, setMode] = useState<'lint' | 'publish'>('lint')
const radio = useRadioGroup(MODES, mode, setMode)
const hasWorkflow = useStudio((s) => !!s.workflow)
const errors = problems.filter((p) => p.level === 'error').length
return (
<>
{hasWorkflow && (
<div className="flex shrink-0 items-center gap-1 px-2 pt-1.5" role="radiogroup" aria-label="问题面板看哪一份">
{MODES.map((m) => (
<button key={m} type="button" {...radio(m)} data-problems-mode={m}
onClick={() => setMode(m)}
className={clsx('flex items-center gap-1 rounded px-2 py-0.5 text-2xs transition-colors',
mode === m ? 'bg-hover text-fg' : 'text-faint hover:text-dim')}>
{m === 'lint'
? <><ListChecks size={11} aria-hidden /> {PUBLISH_FIX_TEXT.lint}
{errors > 0 && <span className="tnum" style={{ color: 'var(--err)' }}>{errors}</span>}</>
: <><ShieldCheck size={11} aria-hidden /> {PUBLISH_FIX_TEXT.section}</>}
</button>
))}
</div>
)}
{mode === 'publish' && hasWorkflow
? <PublishPreflightPane onLocate={(issue) => {
const { nodes } = useStudio.getState()
const [p] = problemsOf([issue], nodes)
if (p) onLocate(p)
}} />
: <LintPane problems={problems} activeId={activeId} onLocate={onLocate} onDeleteEdge={onDeleteEdge} />}
</>
)
}
const MODES = ['lint', 'publish'] as const
function LintPane({ problems, activeId, onLocate, onDeleteEdge }: {
problems: Problem[]
activeId: string | null
onLocate: (p: Problem) => void
onDeleteEdge: (edgeId: string) => void
}) {
const nodes = useStudio((s) => s.nodes)
const analysis = useStudio((s) => s.analysis)
+654 -53
View File
@@ -1,17 +1,26 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { AlertTriangle, Check, CornerDownRight, PenLine, ShieldCheck, XCircle } from 'lucide-react'
import {
AlertTriangle, ArrowRight, Check, CheckCircle2, CornerDownRight, PenLine, RotateCw, ShieldCheck, Sparkles, Wand2,
XCircle,
} from 'lucide-react'
import clsx from 'clsx'
import { api } from '../api/client'
import { diffGraphs, toFlow, useStudio, type GraphDiff } from '../store/studio'
import { Modal, Spinner, toast } from '../components/ui'
import { WORKFLOW_STATUS_HINT } from '../lib/terms'
import {
EDIT_LOCK_TEXT, diffGraphs, editLockOf, toFlow, toGraph, useEditLock, useStudio, type GraphDiff,
} from '../store/studio'
import { useCatalog } from '../store/catalog'
import { Modal, Spinner, toast, useRadioGroup } from '../components/ui'
import { humanizeError } from '../lib/errors'
import { PUBLISH_FIX_TEXT as T, WORKFLOW_STATUS_HINT, WORKFLOW_STATUS_LABEL } from '../lib/terms'
import { setLocalActor, useLocalActor } from '../lib/actor'
import type { Workflow } from '../types'
import {
autoFixIds, choiceReady, contentSig, fixFieldLabel, fixFor, fixValueLines, fixValueText, isMissingEndpoint, mergeIssues,
normalizeAutofix, normalizeCheck, type NodeNameOf,
} from './issues'
import type { AutofixResult, PublishCheck, PublishFix, PublishLevel, ValidationIssue, Workflow } from '../types'
type Level = 'published' | 'governed'
const LEVEL_DETAIL: Record<Level, string> = {
const LEVEL_DETAIL: Record<PublishLevel, string> = {
published: '基础校验通过即可。正式运行从这一版发起,之后画布上继续改不影响它',
governed: '另过治理门禁:不许有「多 Agent 协作」这类全动态规划节点;子工作流要钉住版本;'
+ '至少一个「成果」节点声明出具契约;Agent 的危险工具至少要人工审批',
@@ -23,7 +32,11 @@ const LEVEL_DETAIL: Record<Level, string> = {
* 等级的初值跟着工作流现在的等级走:以前写死「已发布」,对一张受管工作流直接点
* 「发布」,后端照 level 改写状态,它就被悄悄降了级。选中态用底色 + 勾,不只靠一圈
* 1px 描边。发布是要留痕的动作,所以写明以谁的名义发布;没署名就就地填。
* 门禁拦下的问题一条一行、前置节点名,点一下关掉弹窗、定位到那个节点。
*
* 打开就先做一遍发布前检查(和真正发布同一套口径),问题先列出来,能修的就地给修法:
* 以前红字只能一条条抄进助手里描述一遍。修复一律先出预览,人点「应用并重新检查」才存草稿、
* 重查;发布永远要人自己点。不修也照旧能点发布,门禁照旧拦。老后端没有检查接口时,
* 退回原来的样子:点发布才知道被拦下了什么。
*/
export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
workflow: Workflow
@@ -32,10 +45,11 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
onLocate: (nodeId: string) => void
}) {
const load = useStudio((s) => s.load)
const nodes = useStudio((s) => s.nodes)
const [level, setLevel] = useState<Level>(workflow.status === 'governed' ? 'governed' : 'published')
const dirty = useStudio((s) => s.dirty)
const [level, setLevel] = useState<PublishLevel>(workflow.status === 'governed' ? 'governed' : 'published')
const [busy, setBusy] = useState(false)
const [issues, setIssues] = useState<any[] | null>(null)
/** 真的点了发布、被门禁拦下时它回的问题。和检查同一套口径,拦下之后以它为准 */
const [gate, setGate] = useState<ValidationIssue[] | null>(null)
// 署名只存在这台浏览器里(和请求头 X-Actor 是同一份,见 lib/actor)。存不进去(隐私模式)
// 时这一次弹窗里先记着,照样写得进发布提示
const stored = useLocalActor()
@@ -45,6 +59,10 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
const [delta, setDelta] = useState<GraphDiff | null>(null)
const published = workflow.published_version
const downgrade = workflow.status === 'governed' && level === 'published'
const pf = usePreflight(workflow.id, level, { onRechecked: () => setGate(null) })
// 换了等级:上一档被拦下的那张单子不再适用
useEffect(() => { setGate(null) }, [level])
// 和上一个已发布版比一比:发布之前知道这次到底改了什么
useEffect(() => {
@@ -66,10 +84,9 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
const publish = async () => {
setBusy(true)
setIssues(null)
setGate(null)
try {
const res = await api.workflows.publish(workflow.id, level)
setIssues(res.issues ?? [])
if (res.ok) {
toast.ok(`已发布 v${res.version}${level === 'governed' ? ' · 受管' : ''}${actor ? ` · ${actor}` : ''}`)
const fresh = await api.workflows.get(workflow.id)
@@ -80,6 +97,7 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
else load(fresh)
onDone()
} else {
setGate(normalizeCheck({ issues: res.issues }, level).issues)
toast.warn('发布被门禁拦下:下面列了要改的地方,点一条定位到节点')
}
} catch (e) {
@@ -89,20 +107,22 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
}
}
const labelOf = (id?: string | null) => (id ? nodes.find((n) => n.id === id)?.data.label || id : '')
const errors = (issues ?? []).filter((i) => i.level === 'error')
// 预览摆着、正在存、存失败了:这时发布的是还没修的那一版,先让人把修复这件事办完。
// 存失败(或被锁没存上)时预览可能已经收起(换过等级),说「先应用或放弃预览」就不对了
const held = unsavedFix(pf) ? T.unsaved : pf.pending ? T.pendingPreview : dirty ? T.unsaved : ''
return (
<Modal open onClose={onClose} title={`发布「${workflow.name}」v${workflow.version}`} width={560}
footer={<>
<button className="btn" onClick={onClose}>取消</button>
<button className="btn btn-primary" onClick={publish} disabled={busy} data-autofocus="">
<button className="btn btn-primary" onClick={publish} disabled={busy || !!held} title={held || undefined}
data-autofocus="" data-publish-submit="">
{busy ? <Spinner size={12} /> : <ShieldCheck size={12} />}
{level === 'governed' ? '发布为受管' : '发布'}
</button>
</>}>
<div className="mb-3 grid grid-cols-2 gap-2" role="radiogroup" aria-label="发布等级">
{(['published', 'governed'] as Level[]).map((l) => {
{(['published', 'governed'] as PublishLevel[]).map((l) => {
const on = level === l
return (
<button
@@ -110,10 +130,14 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
type="button"
role="radio"
aria-checked={on}
// 修复正在出预览、存草稿、重查时不换档:换档会把这一次的预览和状态清掉,
// 在途的保存要是失败了,就没有地方再给「重试保存」
disabled={pf.working}
onClick={() => setLevel(l)}
// 两张卡说明长短不一,grid 把它们拉成一样高;按钮默认把内容竖直居中,标题就对不齐了
className={clsx('relative flex flex-col justify-start rounded-lg border px-3 py-2.5 text-left transition-colors',
on ? 'border-[var(--accent)] bg-accent-soft' : 'hover:bg-hover')}
'disabled:cursor-not-allowed disabled:opacity-60',
on ? 'border-[var(--accent)] bg-accent-soft' : 'enabled:hover:bg-hover')}
>
{on && (
<span className="absolute right-2 top-2 flex h-4 w-4 items-center justify-center rounded-full bg-accent-solid text-on-accent">
@@ -183,39 +207,9 @@ export function PublishDialog({ workflow, onClose, onDone, onLocate }: {
</div>
</dl>
{issues && !!issues.length && (
<div className="mt-3">
<div className="mb-1 text-2xs font-medium" style={{ color: errors.length ? 'var(--err)' : 'var(--warn)' }}>
{errors.length ? `门禁拦下了 ${errors.length} 处,改完再发布` : '已发布,另有这些提示'}
</div>
<ul className="max-h-48 space-y-0.5 overflow-y-auto">
{issues.map((issue, i) => {
const err = issue.level === 'error'
const Icon = err ? XCircle : AlertTriangle
const where = labelOf(issue.node_id)
return (
<li key={i}>
<button
type="button"
disabled={!issue.node_id}
onClick={() => { onLocate(issue.node_id); onClose() }}
className={clsx('flex w-full items-start gap-1.5 rounded px-1.5 py-1 text-left text-2xs leading-snug',
issue.node_id && 'hover:bg-hover')}
title={issue.node_id ? '定位到这个节点' : undefined}
>
<Icon size={11} className="mt-px shrink-0" style={{ color: err ? 'var(--err)' : 'var(--warn)' }} />
<span className="min-w-0 flex-1">
{where && !String(issue.message).includes(`「${where}」`) && <b className="font-semibold">「{where}」</b>}
{issue.message}
</span>
{issue.node_id && <CornerDownRight size={10} className="mt-px shrink-0 text-faint" />}
</button>
</li>
)
})}
</ul>
</div>
)}
<div className="mt-3" data-preflight="dialog">
<Preflight pf={pf} gate={gate} onLocate={(issue) => { if (issue.node_id) { onLocate(issue.node_id); onClose() } }} />
</div>
</Modal>
)
}
@@ -230,3 +224,610 @@ function describe(d: GraphDiff): string {
].filter(Boolean)
return parts.join('、')
}
// -------------------------------------------------------------------------
// 发布前检查:发布弹窗和问题面板共用
// -------------------------------------------------------------------------
type CheckState = {
status: 'idle' | 'loading' | 'ready' | 'unsupported' | 'error'
/** 上一次查到的:重查期间照样列着,不闪成一片空白 */
data?: PublishCheck
/** data 是按哪一版画布内容查的(contentSig) */
sig?: string
error?: unknown
}
type PreviewState =
| { status: 'loading'; assist: boolean }
| { status: 'ready'; assist: boolean; result: AutofixResult; sig: string }
| { status: 'error'; assist: boolean; error: unknown }
| { status: 'unsupported'; assist: boolean }
type ApplyState =
| { status: 'saving' | 'checking' | 'stale' }
/** unsaved:修复已经落到画布上,要存时画布锁着、没存(重试保存时撞上的) */
| { status: 'locked'; why: string; unsaved?: boolean }
| { status: 'failed'; error: unknown }
type PreviewRequest = { apply: string[]; choices?: Record<string, unknown>; assist?: boolean }
export type PreflightState = ReturnType<typeof usePreflight>
const canvasGraph = () => {
const s = useStudio.getState()
return toGraph(s.nodes, s.edges)
}
const isAbort = (e: unknown) => (e as { name?: string } | null)?.name === 'AbortError'
const reasonOf = (e: unknown) => {
const h = humanizeError(e)
return h.reason ? `${h.title}:${h.reason}` : h.title
}
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
/** 修复已经落到画布上、还没存上:存失败了,或者重试保存时画布锁着 */
const unsavedApply = (a: ApplyState) => a.status === 'failed' || (a.status === 'locked' && !!a.unsaved)
const unsavedFix = (pf: PreflightState) => !!pf.apply && unsavedApply(pf.apply)
/**
* 节点 id → 名字和类型。跟着 issues 换新(改名、改配置之后校验都会重跑),不订阅 nodes:
* 问题面板开着时拖一下节点,这一整块不必跟着每帧重渲染
*/
function useNodeLookup(): (id: string) => { label: string; type: string } | undefined {
const tick = useStudio((s) => s.issues)
const map = useMemo(() => new Map(useStudio.getState().nodes.map((n) => [n.id, { label: n.data.label, type: n.data.nodeType }])),
// eslint-disable-next-line react-hooks/exhaustive-deps
[tick])
return useCallback((id: string) => map.get(id), [map])
}
/**
* 发布前检查的状态:查、出修复预览、应用(落画布 → 走保存接口存草稿 → 重查)。
* 查的一律是画布上此刻的图:发布弹窗只在没有未保存改动时打开得了,这时画布就是草稿;
* 问题面板里画布可能改了没存,查的也正是眼前这张。接口只读,存草稿走的是现有的保存。
*/
export function usePreflight(workflowId: string | undefined, level: PublishLevel,
{ onRechecked }: { onRechecked?: () => void } = {}) {
const [check, setCheck] = useState<CheckState>({ status: 'idle' })
const [preview, setPreview] = useState<PreviewState | null>(null)
const [apply, setApply] = useState<ApplyState | null>(null)
const [choices, setChoices] = useState<Record<string, unknown>>({})
const seq = useRef(0)
const checkCtl = useRef<AbortController | null>(null)
const previewCtl = useRef<AbortController | null>(null)
const lastRequest = useRef<PreviewRequest | null>(null)
/** 落到画布上、还没存上的那一次:重试保存时用同一句版本说明 */
const pendingSave = useRef<{ labels: string[]; count: number } | null>(null)
const rechecked = useRef(onRechecked)
rechecked.current = onRechecked
const runCheck = useCallback(async (fresh = false): Promise<PublishCheck | null> => {
if (!workflowId) return null
const n = ++seq.current
checkCtl.current?.abort()
const ctl = new AbortController()
checkCtl.current = ctl
const graph = canvasGraph()
setCheck((c) => (fresh ? { status: 'loading' } : { ...c, status: 'loading', error: undefined }))
try {
const raw = await api.workflows.publishCheck(workflowId, { level, graph }, { signal: ctl.signal })
if (n !== seq.current) return null
const data = normalizeCheck(raw, level)
setCheck({ status: 'ready', data, sig: contentSig(graph) })
return data
} catch (e) {
if (n !== seq.current || isAbort(e)) return null
setCheck(isMissingEndpoint(e) ? { status: 'unsupported' } : { status: 'error', error: e })
return null
}
}, [workflowId, level])
// 打开、换等级:从头查一遍,上一档的预览和选择都不再适用。只有「修复已经落到画布上、
// 还没存上」这件事跨档留着:换了等级它照样没存,「重试保存」得一直看得见
useEffect(() => {
previewCtl.current?.abort()
setPreview(null)
setApply((a) => (pendingSave.current && a && unsavedApply(a) ? a : null))
setChoices({})
void runCheck(true)
return () => {
checkCtl.current?.abort()
previewCtl.current?.abort()
}
}, [runCheck])
const requestPreview = useCallback(async (req: PreviewRequest) => {
if (!workflowId) return
previewCtl.current?.abort()
const ctl = new AbortController()
previewCtl.current = ctl
lastRequest.current = req
const graph = canvasGraph()
const assist = !!req.assist
setApply(null)
setPreview({ status: 'loading', assist })
try {
const raw = await api.workflows.autofix(workflowId, {
level, graph, apply: req.apply,
...(req.choices && Object.keys(req.choices).length ? { choices: req.choices } : {}),
...(assist ? { assist: true } : {}),
}, { signal: ctl.signal })
if (ctl.signal.aborted) return
setPreview({ status: 'ready', assist, result: normalizeAutofix(raw), sig: contentSig(graph) })
} catch (e) {
if (ctl.signal.aborted || isAbort(e)) return
setPreview(isMissingEndpoint(e) ? { status: 'unsupported', assist } : { status: 'error', assist, error: e })
}
}, [workflowId, level])
const discard = useCallback(() => {
previewCtl.current?.abort()
setPreview(null)
setApply(null)
}, [])
/**
* 存草稿,和页面自己的保存同一套规矩:画布锁着(助手在改、正式运行在跑)不存——助手改到一半
* 的图存下去就是半成品;恢复旧版本留下的「回滚到 vN」不能被这一句盖掉,两句接着写
*/
const save = useCallback(async () => {
const what = pendingSave.current
if (!what) return
const studio = useStudio.getState()
const lock = editLockOf(studio)
if (lock) {
setApply({ status: 'locked', why: EDIT_LOCK_TEXT[lock], unsaved: true })
return
}
const pendingNote = studio.pendingNote.trim()
const note = T.saveNote(what.labels)
setApply({ status: 'saving' })
try {
await studio.save(pendingNote ? `${pendingNote};${note}` : note)
} catch (e) {
setApply({ status: 'failed', error: e })
return
}
pendingSave.current = null
void useCatalog.getState().refresh()
setApply({ status: 'checking' })
await runCheck()
rechecked.current?.()
setPreview(null)
setApply(null)
toast.ok(T.applied(what.count, useStudio.getState().workflow?.version))
}, [runCheck])
const applyPreview = useCallback(async () => {
if (preview?.status !== 'ready' || !preview.result.graph) return
// 预览是按发请求那一刻的画布算的:之后又改过的话,套上去会把那几下盖掉
if (contentSig(canvasGraph()) !== preview.sig) {
setApply({ status: 'stale' })
return
}
const { result } = preview
const count = result.changes.length || result.applied.length
const labels = result.changes.map((c) => c.label || fixLabelOf(check.data, c.fix_id)).filter(Boolean) as string[]
if (!useStudio.getState().applyFixes(result.graph!, T.undoLabel(count))) {
// 预览摆着的时候画布锁上了(正式运行开始、助手开始改):落不下去,说清为什么
const lock = editLockOf(useStudio.getState())
setApply({ status: 'locked', why: lock ? EDIT_LOCK_TEXT[lock] : EDIT_LOCK_TEXT.formal })
return
}
pendingSave.current = { labels: labels.length ? labels : [preview.assist ? T.assist : T.fixOne], count }
await save()
}, [preview, check.data, save])
const retryPreview = useCallback(() => {
if (lastRequest.current) void requestPreview(lastRequest.current)
}, [requestPreview])
const choose = useCallback((fix: PublishFix, value: unknown) => {
setChoices((c) => {
if (!fix.multiple) return { ...c, [fix.id]: value }
const cur = Array.isArray(c[fix.id]) ? c[fix.id] as unknown[] : []
const next = cur.some((v) => same(v, value)) ? cur.filter((v) => !same(v, value)) : [...cur, value]
return { ...c, [fix.id]: next }
})
}, [])
const working = preview?.status === 'loading' || apply?.status === 'saving' || apply?.status === 'checking'
return {
level, check, preview, apply, choices, working,
/** 预览摆着、正在存、存失败(或被锁没存上):发布按钮等这件事办完 */
pending: preview?.status === 'loading' || preview?.status === 'ready'
|| apply?.status === 'saving' || apply?.status === 'checking' || (!!apply && unsavedApply(apply)),
recheck: () => runCheck(),
requestPreview, discard, applyPreview, retryPreview, retrySave: save, choose,
}
}
function fixLabelOf(data: PublishCheck | undefined, id: string): string {
return data?.fixes.find((f) => f.id === id)?.label ?? ''
}
/**
* 发布前检查的整块:一句结论(+ 一键修复)、修复预览、问题清单(每条旁边给修法)。
* gate:真点了发布、被门禁拦下时回的那张单子,有它就列它。
*/
export function Preflight({ pf, gate, onLocate, stale }: {
pf: PreflightState
gate?: ValidationIssue[] | null
onLocate: (issue: ValidationIssue) => void
/** 问题面板:查完之后画布又改过 */
stale?: boolean
}) {
const nodeOf = useNodeLookup()
const lock = useEditLock()
const { check } = pf
const fixes = check.data?.fixes ?? []
const issues = gate ?? check.data?.issues ?? null
// validate 和门禁对同一处各报一条:合成一行,计数也按一处算
const rows = useMemo(() => (issues ? mergeIssues(issues) : null), [issues])
const errors = (rows ?? []).filter((r) => r.issue.level === 'error').length
const warns = (rows ?? []).length - errors
const canFix = !lock && check.status !== 'unsupported'
const autoIds = issues ? autoFixIds(issues, fixes) : []
const labelOf = (id?: string | null) => (id ? nodeOf(id)?.label || id : '')
const nameOf: NodeNameOf = (id) => nodeOf(id)?.label || undefined
const anyFix = !!issues?.some((i) => fixFor(i, fixes))
// 同一个修复只画一次控件:挂在第一条指向它的问题上(几条问题共用一个修复时,比如全图默认
// 一改、跟随它的几个节点一起好了),别处再画一组就是两个共用状态的「预览」
const drawn = new Set<string>()
const fixOf = (issue: ValidationIssue): PublishFix | undefined => {
const fix = canFix ? fixFor(issue, fixes) : undefined
if (!fix || drawn.has(fix.id)) return undefined
drawn.add(fix.id)
return fix
}
return (
<div className="space-y-2 text-2xs" data-preflight-status={check.status}>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
{check.status === 'loading' && !check.data && !gate && (
<span className="flex items-center gap-1.5 text-faint"><Spinner size={11} /> {T.checking}</span>
)}
{check.status === 'unsupported' && !gate && (
<span className="text-faint" data-preflight-unsupported="">{T.unsupported}</span>
)}
{check.status === 'error' && !gate && (
<>
<span style={{ color: 'var(--warn)' }}>{T.failed}:{reasonOf(check.error)}</span>
<button type="button" className="btn btn-xs" onClick={() => void pf.recheck()}>
<RotateCw size={10} aria-hidden /> {T.retry}
</button>
</>
)}
{issues && (
<span className="flex min-w-0 items-center gap-1.5 font-medium" data-preflight-summary=""
style={{ color: errors ? 'var(--err)' : warns ? 'var(--warn)' : 'var(--ok)' }}>
{errors ? <XCircle size={12} className="shrink-0" aria-hidden />
: <CheckCircle2 size={12} className="shrink-0" aria-hidden />}
<span className="min-w-0">
{gate ? T.gateBlocked(errors) : errors ? T.blocked(errors) : T.passed}
{warns > 0 && <span className="font-normal text-faint">{errors || gate ? ',' : ';'}{T.warnings(warns)}</span>}
</span>
</span>
)}
{check.status === 'loading' && (check.data || gate) && <Spinner size={11} />}
<span className="flex-1" />
{canFix && autoIds.length > 0 && (
<button type="button" className="btn btn-xs" data-fix-all={autoIds.length} disabled={pf.working}
onClick={() => void pf.requestPreview({ apply: autoIds })}>
<Wand2 size={10} aria-hidden /> {T.fixAll(autoIds.length)}
</button>
)}
</div>
{stale && check.status === 'ready' && (
<div className="flex items-center gap-1.5" style={{ color: 'var(--st-waiting)' }} data-preflight-stale="">
<AlertTriangle size={11} className="shrink-0" aria-hidden /> {T.stale}
</div>
)}
{lock && anyFix && (
<div className="text-faint" data-preflight-locked="">{T.locked(EDIT_LOCK_TEXT[lock])}</div>
)}
{pf.preview && <FixPreview pf={pf} labelOf={labelOf} nameOf={nameOf}
typeOf={(id) => (id ? nodeOf(id)?.type : undefined)} />}
{/* 修复落到画布上却没存上,预览又已经收起了(换过等级):「重试保存」照样得在 */}
{pf.preview?.status !== 'ready' && unsavedFix(pf) && <SaveTrouble pf={pf} />}
{rows && !!rows.length && (
<ul className="space-y-0.5" aria-label="发布前检查的问题">
{rows.map(({ issue, others }, i) => (
<PreflightRow key={`${issue.code ?? ''}:${issue.node_id ?? ''}:${i}`} issue={issue} others={others}
fix={fixOf(issue)} where={labelOf(issue.node_id)}
pf={pf} onLocate={() => onLocate(issue)} />
))}
</ul>
)}
</div>
)
}
function PreflightRow({ issue, others, fix, where, pf, onLocate }: {
issue: ValidationIssue; others: string[]; fix?: PublishFix; where: string; pf: PreflightState; onLocate: () => void
}) {
const err = issue.level === 'error'
const Icon = err ? XCircle : AlertTriangle
return (
<li data-preflight-issue={issue.code ?? ''} data-fix-kind={fix?.kind}>
<button
type="button"
disabled={!issue.node_id}
onClick={onLocate}
className={clsx('flex w-full items-start gap-1.5 rounded px-1.5 py-1 text-left leading-snug',
issue.node_id && 'hover:bg-hover')}
// 合成一行的那几条的其他说法:悬停看得到,不在清单里重复一遍
title={[issue.node_id ? '定位到这个节点' : '', ...others].filter(Boolean).join('\n') || undefined}
>
<Icon size={11} className="mt-px shrink-0" style={{ color: err ? 'var(--err)' : 'var(--warn)' }}
aria-label={err ? '错误' : '提示'} />
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]">
{where && !String(issue.message).includes(`「${where}」`) && <b className="font-semibold">「{where}」</b>}
{issue.message}
</span>
{issue.node_id && <CornerDownRight size={10} className="mt-px shrink-0 text-faint" aria-hidden />}
</button>
{fix && <FixControl fix={fix} pf={pf} />}
</li>
)
}
/** 一条问题的修法:auto 一个「修复」,choice 一组选项(不替人选),assist 交给 Copilot */
function FixControl({ fix, pf }: { fix: PublishFix; pf: PreflightState }) {
const value = pf.choices[fix.id]
if (fix.kind === 'choice') {
const ready = choiceReady(fix, value)
const picked = (v: unknown) => (fix.multiple
? Array.isArray(value) && value.some((x) => same(x, v))
: value !== undefined && same(value, v))
return (
<fieldset className="mb-1 ml-[22px] mt-0.5 rounded border px-2 py-1.5" data-fix-choice={fix.id}>
<legend className="px-1 text-faint">{fix.label}{fix.multiple ? ` · ${T.multiple}` : ''}</legend>
<div className="flex flex-wrap gap-x-3 gap-y-1">
{(fix.options ?? []).map((o, k) => (
<label key={k} className="inline-flex min-w-0 cursor-pointer items-start gap-1.5" title={o.hint ?? undefined}>
<input type={fix.multiple ? 'checkbox' : 'radio'} name={`fix-${fix.id}`} className="mt-0.5 accent-[var(--accent)]"
checked={picked(o.value)} disabled={pf.working} onChange={() => pf.choose(fix, o.value)} />
<span className="min-w-0 [overflow-wrap:anywhere]">
{o.label}
{fix.default !== undefined && (fix.multiple
? Array.isArray(fix.default) && fix.default.some((d) => same(d, o.value))
: same(fix.default, o.value)) && (
<span className="ml-1 rounded border px-1 text-faint">{T.suggested}</span>
)}
{o.hint && <span className="block text-faint">{o.hint}</span>}
</span>
</label>
))}
</div>
<div className="mt-1.5 flex items-center gap-2">
<button type="button" className="btn btn-xs" data-fix-action="choice" disabled={!ready || pf.working}
onClick={() => void pf.requestPreview({ apply: [fix.id], choices: { [fix.id]: value } })}>
<Wand2 size={10} aria-hidden /> {T.choose}
</button>
{!ready && <span className="text-faint">{T.chooseFirst}</span>}
</div>
</fieldset>
)
}
const assist = fix.kind === 'assist'
return (
<div className="mb-1 ml-[22px] flex flex-wrap items-center gap-x-2 gap-y-0.5">
<button type="button" className="btn btn-xs shrink-0" data-fix-action={fix.kind} disabled={pf.working}
title={assist ? T.assistHint : T.fixHint(fix.label)}
onClick={() => void pf.requestPreview(assist ? { apply: [], assist: true } : { apply: [fix.id] })}>
{assist ? <Sparkles size={10} aria-hidden /> : <Wand2 size={10} aria-hidden />} {assist ? T.assist : T.fixOne}
</button>
<span className="min-w-0 text-faint [overflow-wrap:anywhere]">{fix.label}</span>
</div>
)
}
/** 修复预览:逐项「节点 · 字段:原值 → 新值」,没采用的写原因,Copilot 的问题原样摆出来 */
function FixPreview({ pf, labelOf, nameOf, typeOf }: {
pf: PreflightState; labelOf: (id?: string | null) => string; nameOf: NodeNameOf
typeOf: (id?: string | null) => string | undefined
}) {
const dirty = useStudio((s) => s.dirty)
const p = pf.preview!
const box = 'rounded-md border px-2.5 py-2'
// 点的可能是清单最底下那一条的「修复」:预览在清单上面出来,得让人看得见
const ref = useRef<HTMLDivElement>(null)
useEffect(() => { ref.current?.scrollIntoView({ block: 'nearest' }) }, [p.status])
if (p.status === 'loading') {
return (
<div ref={ref} className={clsx(box, 'flex items-center gap-2')} data-fix-preview="loading" aria-live="polite">
<Spinner size={11} />
<span className="min-w-0 flex-1 text-dim">{p.assist ? T.assisting : T.previewing}</span>
<button type="button" className="btn btn-xs" onClick={pf.discard}>{T.stop}</button>
</div>
)
}
if (p.status === 'unsupported' || p.status === 'error') {
return (
<div ref={ref} className={clsx(box, 'flex flex-wrap items-center gap-2')} style={{ borderColor: 'var(--warn)' }}
data-fix-preview={p.status} role="alert">
<AlertTriangle size={11} className="shrink-0" style={{ color: 'var(--warn)' }} aria-hidden />
<span className="min-w-0 flex-1" style={{ color: 'var(--warn)' }}>
{p.status === 'unsupported' ? T.autofixMissing : `${T.autofixFailed}:${reasonOf(p.error)}`}
</span>
{p.status === 'error' && (
<button type="button" className="btn btn-xs" onClick={pf.retryPreview}><RotateCw size={10} aria-hidden /> {T.retry}</button>
)}
<button type="button" className="btn btn-xs" onClick={pf.discard}>{T.discard}</button>
</div>
)
}
const { result } = p
const applying = pf.apply?.status === 'saving' || pf.apply?.status === 'checking'
const unsaved = unsavedFix(pf)
const left = result.remaining.filter((i) => i.level === 'error').length
const usable = !!result.graph && (result.changes.length > 0 || result.applied.length > 0)
return (
<section ref={ref} className={clsx(box, 'space-y-1.5')} style={{ borderColor: 'var(--accent)' }}
data-fix-preview="ready" aria-label="修复预览">
<div className="font-medium">{result.changes.length ? T.previewTitle(result.changes.length) : T.noChange}</div>
{!!result.changes.length && (
<ul className="space-y-1" data-fix-changes="">
{result.changes.map((c, i) => {
const where = c.node_title || labelOf(c.node_id) || T.whole
const field = fixFieldLabel(c.field, typeOf(c.node_id))
return (
<li key={i} className="leading-snug" data-fix-change={c.fix_id}>
<span className="[overflow-wrap:anywhere]">
<b className="font-semibold">「{where}」</b>{field && ` · ${field}`}:
<FixValue value={c.before} field={c.field} nameOf={nameOf} className="text-faint line-through" data-fix-before="" />
<ArrowRight size={10} className="mx-1 inline align-[-1px] text-faint" aria-label="改成" />
<FixValue value={c.after} field={c.field} nameOf={nameOf} className="font-medium" data-fix-after="" />
</span>
{c.label && <span className="block text-faint">{c.label}</span>}
</li>
)
})}
</ul>
)}
{!!result.rejected.length && (
<div data-fix-rejected="">
<div className="text-faint">{T.rejected}</div>
<ul className="space-y-0.5">
{result.rejected.map((r, i) => (
<li key={i} className="flex items-start gap-1 [overflow-wrap:anywhere]" style={{ color: 'var(--warn)' }}>
<AlertTriangle size={10} className="mt-0.5 shrink-0" aria-hidden />
<span className="min-w-0">
{r.fix_id === 'assist' ? T.assistSaid : fixLabelOf(pf.check.data, r.fix_id) || r.fix_id}:{r.reason}
</span>
</li>
))}
</ul>
</div>
)}
{result.assist && (result.assist.summary || !!result.assist.questions?.length) && (
<div className="space-y-1" data-fix-assist="">
{result.assist.summary && (
<div className="flex items-start gap-1 [overflow-wrap:anywhere]">
<Sparkles size={10} className="mt-0.5 shrink-0 text-faint" aria-hidden />
<span className="min-w-0"><span className="text-faint">{T.assistSaid}:</span>{result.assist.summary}</span>
</div>
)}
{!!result.assist.questions?.length && (
<div className="rounded border px-2 py-1" style={{ borderColor: 'var(--st-waiting)' }} data-fix-questions="">
<div style={{ color: 'var(--st-waiting)' }}>{T.questions}</div>
<ul className="list-disc pl-4">
{result.assist.questions.map((q, i) => <li key={i} className="[overflow-wrap:anywhere]">{q}</li>)}
</ul>
</div>
)}
</div>
)}
{usable && (
<div style={{ color: result.ok ? 'var(--ok)' : 'var(--warn)' }} data-fix-after-check="">
{result.ok ? T.afterOk : T.afterLeft(left)}
</div>
)}
{pf.apply?.status === 'stale' && <div role="alert" style={{ color: 'var(--warn)' }}>{T.stalePreview}</div>}
{pf.apply?.status === 'locked' && !pf.apply.unsaved && (
<div role="alert" style={{ color: 'var(--warn)' }}>{T.locked(pf.apply.why)}</div>
)}
{unsaved && <SaveTrouble pf={pf} />}
{!unsaved && (
<div className="flex flex-wrap items-center gap-2 pt-0.5">
<span className="min-w-0 flex-1 text-faint">
{applying ? (pf.apply?.status === 'saving' ? T.saving : T.rechecking)
: usable ? `${T.applyNote}${dirty ? `。${T.dirtyNote}` : ''}` : ''}
</span>
<button type="button" className="btn btn-xs" onClick={pf.discard} disabled={applying}>{T.discard}</button>
{usable && (
<button type="button" className="btn btn-xs btn-primary" data-fix-apply="" disabled={applying || pf.apply?.status === 'stale'}
onClick={() => void pf.applyPreview()}>
{applying ? <Spinner size={10} /> : <Check size={10} aria-hidden />} {T.apply}
</button>
)}
</div>
)}
</section>
)
}
/**
* 预览里的一个值。整份契约(生成契约骨架)一键一行地写,别的压成一行;节点引用写节点名
*/
function FixValue({ value, field, nameOf, className, ...data }: {
value: unknown; field?: string | null; nameOf: NodeNameOf; className?: string
'data-fix-before'?: string; 'data-fix-after'?: string
}) {
const lines = fixValueLines(value, field, nameOf)
if (!lines) return <span className={className} {...data}>{fixValueText(value, field, nameOf)}</span>
return (
<span className={clsx(className, 'block pl-3')} {...data}>
{lines.map((line, i) => <span key={i} className="block">{line}</span>)}
</span>
)
}
/**
* 修复已经落到画布上、还没存上:存失败了,或者重试保存时画布锁着(助手在改、正式运行在跑)。
* 说清楚为什么,给「重试保存」。预览里有一份;预览收起了(换过等级)就在清单上面单独一份
*/
function SaveTrouble({ pf }: { pf: PreflightState }) {
const a = pf.apply
if (!a || !unsavedApply(a)) return null
const failed = a.status === 'failed'
return (
<div role="alert" className="flex flex-wrap items-center gap-2" style={{ color: failed ? 'var(--err)' : 'var(--warn)' }}
data-fix-save-failed={failed ? '' : 'locked'}>
<span className="min-w-0 flex-1">
{failed ? `${T.saveFailed}:${reasonOf(a.error)}` : a.status === 'locked' ? `${T.saveFailed}(${a.why})` : ''}。
{T.saveFailedHint}
</span>
<button type="button" className="btn btn-xs" onClick={() => void pf.retrySave()}>
<RotateCw size={10} aria-hidden /> {T.retrySave}
</button>
</div>
)
}
const LEVELS = ['published', 'governed'] as const
/**
* 问题面板里的「发布前检查」:选一档,查一遍,同一套修法。画布上就能提前发现、提前修,
* 不用等到点发布那一刻。点一条照样定位到节点
*/
export function PublishPreflightPane({ onLocate }: { onLocate: (issue: ValidationIssue) => void }) {
const workflow = useStudio((s) => s.workflow)
const [level, setLevel] = useState<PublishLevel>(workflow?.status === 'governed' ? 'governed' : 'published')
// 修复正在出预览、存草稿、重查时不换档(和发布弹窗同一条):方向键也换不了
const busy = useRef(false)
const pick = useCallback((l: PublishLevel) => { if (!busy.current) setLevel(l) }, [])
const radio = useRadioGroup(LEVELS, level, pick)
const pf = usePreflight(workflow?.id, level)
busy.current = pf.working
// 查完之后画布又改了:结论可能已经过时。跟着 issues 重算(每次改图后校验都会换新),
// 不订阅 nodes——那样拖一帧就要把整张图序列化一遍
const tick = useStudio((s) => s.issues)
const sig = pf.check.sig
const stale = useMemo(() => sig != null && contentSig(canvasGraph()) !== sig, [tick, sig])
if (!workflow) return null
return (
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-2" data-preflight="panel">
<div className="mb-2 flex flex-wrap items-center gap-2 text-2xs">
<div role="radiogroup" aria-label="按哪一档检查" className="inline-flex rounded-md border p-px">
{LEVELS.map((l) => (
<button key={l} type="button" {...radio(l)} onClick={() => pick(l)} disabled={pf.working}
className={clsx('rounded px-2 py-0.5 disabled:cursor-not-allowed disabled:opacity-60',
level === l ? 'bg-accent-soft text-fg' : 'text-faint enabled:hover:text-dim')}>
{WORKFLOW_STATUS_LABEL[l]}
</button>
))}
</div>
<span className="flex-1" />
<button type="button" className="btn btn-xs" onClick={() => void pf.recheck()}
disabled={pf.check.status === 'loading' || pf.working}>
<RotateCw size={10} aria-hidden /> {T.recheck}
</button>
</div>
<Preflight pf={pf} onLocate={onLocate} stale={stale} />
</div>
)
}
+228 -1
View File
@@ -10,8 +10,11 @@
* 例外是「提示词要求用 X,但没绑定」:后端的 field 指着点名的那句提示词,可修法在工具
* 那一栏,定位落到工具上(见 toolBindingOf)。
*/
import { ApiError } from '../api/client'
import { APPROVAL_POLICY_LABEL } from '../lib/terms'
import { NODE_DEFS } from './nodeDefs'
import type { FlowNode } from '../store/studio'
import type { ValidationIssue } from '../types'
import type { AutofixResult, GraphSpec, PublishCheck, PublishFix, PublishLevel, ValidationIssue } from '../types'
export interface FieldRef {
/** 顶层配置键:prompt、cases、fields… 'label' 表示节点名称 */
@@ -187,3 +190,227 @@ export function problemsOf(
}
return list.sort((a, b) => order(a) - order(b) || (a.level === b.level ? 0 : a.level === 'error' ? -1 : 1))
}
// -------------------------------------------------------------------------
// 发布前检查与自动修复(POST /workflows/{id}/publish-check、/autofix)
//
// 接口是这一期才有的,老后端没有;新后端也可能少给字段。这里把回来的东西收成确定的形状,
// 认不出的丢掉,不猜:少了 fixes 就当没有修复,少了 changes 就当没有改动。
// -------------------------------------------------------------------------
const asArray = <T = unknown>(v: unknown): T[] => (Array.isArray(v) ? v as T[] : [])
const asText = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v))
function normalizeIssue(raw: any): ValidationIssue | null {
if (!raw || typeof raw !== 'object' || !raw.message) return null
return {
level: raw.level === 'error' ? 'error' : 'warning',
message: asText(raw.message),
node_id: raw.node_id ?? null,
edge_id: raw.edge_id ?? null,
field: raw.field ?? null,
code: typeof raw.code === 'string' ? raw.code : null,
fix: typeof raw.fix === 'string' && raw.fix ? raw.fix : null,
}
}
function normalizeFix(raw: any): PublishFix | null {
if (!raw || typeof raw !== 'object' || typeof raw.id !== 'string' || !raw.id) return null
const kind = raw.kind === 'choice' || raw.kind === 'assist' ? raw.kind : raw.kind === 'auto' ? 'auto' : null
if (!kind) return null
const options = asArray<any>(raw.options)
.filter((o) => o && typeof o === 'object' && 'value' in o)
.map((o) => ({ value: o.value, label: asText(o.label ?? o.value), hint: o.hint ? asText(o.hint) : null }))
// 选项类没有候选就没法选:不给控件,比给一个空下拉强
if (kind === 'choice' && !options.length) return null
return {
id: raw.id,
code: asText(raw.code),
kind,
node_id: raw.node_id ?? null,
label: asText(raw.label) || raw.id,
preview: raw.preview && typeof raw.preview === 'object' ? raw.preview : null,
options,
multiple: !!raw.multiple,
default: raw.default,
}
}
export function normalizeCheck(raw: any, level: PublishLevel): PublishCheck {
const issues = asArray(raw?.issues).map(normalizeIssue).filter((i): i is ValidationIssue => !!i)
const fixes = asArray(raw?.fixes).map(normalizeFix).filter((f): f is PublishFix => !!f)
return {
level: raw?.level === 'governed' || raw?.level === 'published' ? raw.level : level,
ok: typeof raw?.ok === 'boolean' ? raw.ok : !issues.some((i) => i.level === 'error'),
issues,
fixes: [...new Map(fixes.map((f) => [f.id, f])).values()],
}
}
export function normalizeAutofix(raw: any): AutofixResult {
const graph = raw?.graph && typeof raw.graph === 'object' && Array.isArray(raw.graph.nodes) ? raw.graph as GraphSpec : null
const remaining = asArray(raw?.remaining).map(normalizeIssue).filter((i): i is ValidationIssue => !!i)
const assist = raw?.assist && typeof raw.assist === 'object'
? { ok: !!raw.assist.ok, summary: asText(raw.assist.summary), questions: asArray(raw.assist.questions).map(asText).filter(Boolean) }
: null
return {
graph,
changes: asArray<any>(raw?.changes).filter((c) => c && typeof c === 'object').map((c) => ({
fix_id: asText(c.fix_id), node_id: c.node_id ?? null, node_title: c.node_title ?? null,
field: c.field ?? null, before: c.before, after: c.after, label: c.label ? asText(c.label) : null,
})),
applied: asArray(raw?.applied).map(asText).filter(Boolean),
rejected: asArray<any>(raw?.rejected).filter((r) => r && typeof r === 'object')
.map((r) => ({ fix_id: asText(r.fix_id), reason: asText(r.reason) || '没说原因' })),
remaining,
assist,
ok: typeof raw?.ok === 'boolean' ? raw.ok : !remaining.some((i) => i.level === 'error'),
}
}
/**
* 老后端没有这个接口:FastAPI 对不存在的路由回 404 {"detail":"Not Found"}(方法不对是 405)。
* 别的 404(工作流不在了)是真的出错,要照实说
*/
export function isMissingEndpoint(e: unknown): boolean {
if (!(e instanceof ApiError) || e.kind !== 'http') return false
return e.status === 405 || (e.status === 404 && (e.detail == null || e.detail === 'Not Found'))
}
/**
* 这条问题的修复:后端点了 fix id 就按 id 找;没点的(/publish 被拦时的回包只有 code)按 code + 节点认。
* 认不出时和后端 autofix.annotate 同一个退路:图级问题(没有节点,比如「没有带契约的出口」,
* 修复却落在唯一的出口上)认同一编号的第一条修复;图级修复(改的是全图默认,不落在任何节点上)
* 认同一编号的每一条问题。再认不出就没有
*/
export function fixFor(issue: ValidationIssue, fixes: PublishFix[]): PublishFix | undefined {
if (issue.fix) return fixes.find((f) => f.id === issue.fix)
if (!issue.code) return undefined
const same = fixes.filter((f) => f.code === issue.code)
const exact = same.find((f) => (f.node_id ?? null) === (issue.node_id ?? null))
if (exact) return exact
return issue.node_id == null ? same[0] : same.find((f) => f.node_id == null)
}
/**
* 同一处问题只列一行:validate 和门禁常对同一处各报一条(同 code、同节点,说法不同),
* 列两行就是两组一样的修复控件、「会被拦下 2 处」。合成的那一行取最重的级别、第一条 error 的说法,
* 其余说法收进 others(悬停可见)。没有 code 的认不出是不是同一处,照原样各列一行
*/
export function mergeIssues(issues: ValidationIssue[]): { issue: ValidationIssue; others: string[] }[] {
const out: { issue: ValidationIssue; others: string[] }[] = []
const at = new Map<string, number>()
for (const issue of issues) {
const key = issue.code ? `${issue.code}\u0000${issue.node_id ?? ''}` : null
const i = key != null ? at.get(key) : undefined
if (i == null) {
if (key != null) at.set(key, out.length)
out.push({ issue, others: [] })
continue
}
const row = out[i]
const cur = row.issue
const worse = issue.level === 'error' && cur.level !== 'error'
const [keep, drop] = worse ? [issue, cur] : [cur, issue]
row.issue = { ...keep, fix: cur.fix ?? issue.fix ?? null, field: keep.field ?? drop.field ?? null }
if (drop.message !== keep.message && !row.others.includes(drop.message)) row.others.push(drop.message)
row.others = row.others.filter((m) => m !== keep.message)
}
return out
}
/** 「一键修复」会应用的那几项:挂在眼前这些问题上的 auto 修复,去重 */
export function autoFixIds(issues: ValidationIssue[], fixes: PublishFix[]): string[] {
const ids = issues.map((i) => fixFor(i, fixes)).filter((f) => f?.kind === 'auto').map((f) => f!.id)
return [...new Set(ids)]
}
/** 选项类修复选好了没有:多选至少一项,单选要有值 */
export function choiceReady(fix: PublishFix, value: unknown): boolean {
if (fix.multiple) return Array.isArray(value) && value.length > 0
return value !== undefined
}
/**
* 画布内容的签名:节点的类型、名字、配置和连线,不含位置。预览是按发请求那一刻的图算的,
* 应用时画布内容变了就对不上;只是挪了挪节点不算变
*/
export function contentSig(graph: GraphSpec): string {
return JSON.stringify({
nodes: (graph.nodes ?? []).map((n) => [n.id, n.type, n.data?.label ?? '', n.data?.config ?? {}]),
edges: (graph.edges ?? []).map((e) => [e.source, e.target, e.sourceHandle ?? null]),
})
}
/** 出具契约里的几个键在界面上的叫法。拆成几行写契约骨架时也按这个顺序 */
const CONTRACT_KEYS: Record<string, string> = {
metrics_from: '指标来自', report_from: '报告来自', required: '必需指标', expected: '期望指标',
strict: '严格模式', narrative: '叙述', cells: '单元格引用', allow_numbers: '允许不带出处的数',
}
/** 不在节点定义的字段表里、由检查器自己画的几项(子工作流钉的版本、升版处置),以及图级的全图默认 */
const EXTRA_FIELDS: Record<string, string> = {
workflow_version: '钉住版本', upgrade_policy: '上游发了新版本时', defaults: '全图默认',
}
/** 点号后面那一段的叫法:契约里的键,全图默认里的审批策略 */
const SUB_KEYS: Record<string, string> = { ...CONTRACT_KEYS, approval: '审批策略' }
/** 值是节点 id 的几个键(报告、契约的 metrics_from,契约的 report_from):预览里写节点名,不写 id */
const NODE_REF_KEYS = new Set(['metrics_from', 'report_from'])
/** 节点 id → 画布上的名字;画布上没有这个节点时返回 undefined */
export type NodeNameOf = (id: string) => string | undefined
const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
/** 修复改的是哪个字段:顶层键用节点定义里的叫法,契约里的键另有一张表,其余原样 */
export function fixFieldLabel(field: string | null | undefined, nodeType?: string): string {
if (!field) return ''
const [head, ...rest] = field.split('.')
if (head === 'label') return '节点名称'
const def = nodeType ? NODE_DEFS[nodeType as keyof typeof NODE_DEFS] : undefined
const base = def?.fields.find((f) => f.key === head)?.label ?? EXTRA_FIELDS[head] ?? head
return [base, ...rest.map((k) => SUB_KEYS[k] ?? k)].join(' · ')
}
/**
* 改动前后的值怎么写:空写「(空)」,审批策略写界面上的选项文字,节点引用写「节点名」
* (画布上找不到的照写 id——它本来就指着一个不存在的节点),契约骨架按键写成「指标来自:…;…」,
* 其余压成一行
*/
export function fixValueText(value: unknown, field?: string | null, nameOf?: NodeNameOf): string {
if (value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)
|| (isRecord(value) && !Object.keys(value).length)) return '(空)'
const key = field?.split('.').pop()
if (key === 'approval' && typeof value === 'string' && value in APPROVAL_POLICY_LABEL) {
return APPROVAL_POLICY_LABEL[value as keyof typeof APPROVAL_POLICY_LABEL]
}
if (typeof value === 'boolean') return value ? '是' : '否'
if (key === 'workflow_version' && (typeof value === 'number' || /^\d+$/.test(String(value)))) return `v${value}`
if (key && NODE_REF_KEYS.has(key)) {
const ids = Array.isArray(value) ? value : [value]
if (ids.every((v) => typeof v === 'string')) {
return ids.map((id) => { const name = nameOf?.(id as string); return name ? `「${name}」` : id }).join('、')
}
}
const lines = fixValueLines(value, field, nameOf)
if (lines) return lines.join(';')
if (Array.isArray(value) && value.every((v) => typeof v !== 'object' || v === null)) return value.join('、')
const text = typeof value === 'string' ? value : JSON.stringify(value)
return text.length > 80 ? `${text.slice(0, 80)}…` : text
}
/**
* 整份契约(field 为 contract、值是对象,比如「生成契约骨架」)拆成一键一行:「指标来自:「周报口径」」
* 「必需指标:gmv、orders」。键名用界面叫法、按 CONTRACT_KEYS 的顺序,值和单独改一项时写法相同。
* 不是整份契约的返回 null
*/
export function fixValueLines(value: unknown, field?: string | null, nameOf?: NodeNameOf): string[] | null {
if (field !== 'contract' || !isRecord(value) || !Object.keys(value).length) return null
const order = Object.keys(CONTRACT_KEYS)
const keys = Object.keys(value).sort((a, b) => {
const [x, y] = [order.indexOf(a), order.indexOf(b)]
return (x < 0 ? order.length : x) - (y < 0 ? order.length : y)
})
return keys.map((k) => `${CONTRACT_KEYS[k] ?? k}:${fixValueText(value[k], `contract.${k}`, nameOf)}`)
}
+57 -5
View File
@@ -2,13 +2,13 @@ import {
Bot, Braces, Brain, CheckCircle2, Code2, Database, FileInput, FileOutput, FileText,
Gauge, GitBranch, Hand, Repeat, Search, Shuffle, Users, Wrench,
} from 'lucide-react'
import { APPROVAL_POLICY_LABEL, NODE_TYPE_LABEL } from '../lib/terms'
import { APPROVAL_POLICY_LABEL, NODE_TYPE_LABEL, UPGRADE_POLICY_LABEL } from '../lib/terms'
import type { NodeType } from '../types'
export type FieldType =
| 'text' | 'textarea' | 'prompt' | 'code' | 'number' | 'select' | 'switch'
| 'json' | 'model' | 'tools' | 'skills' | 'collection'
| 'ioFields' | 'cases' | 'agents' | 'metricsList' | 'nodeRefs'
| 'ioFields' | 'cases' | 'agents' | 'metricsList' | 'nodeRefs' | 'caliberFrom'
/**
* 这个字段里写的是什么语法。
@@ -36,11 +36,30 @@ export interface FieldDef {
step?: number
/** 只在满足条件时显示,避免面板一次糊一屏用不上的选项 */
when?: (config: Record<string, any>) => boolean
/**
* 看得见但暂时用不了:返回一句为什么(「先写 Schema 才能开」),返回 null 就能用。
* 和 when 的区别:藏起来的人不知道有这个选项,禁用的知道、也知道差什么
*/
disabled?: (config: Record<string, any>) => string | null
/** nodeRefs:只能选这一类的上游节点(报告的 metrics_from 只收口径卡) */
refType?: NodeType
advanced?: boolean
}
/**
* 写没写结构化输出 Schema:对象形状(type: object 或带 properties),画布里存成 JSON 文本的也认,
* 和后端 llm._output_schema 的认法一致
*/
export function hasOutputSchema(schema: unknown): boolean {
let value = schema
if (typeof value === 'string') {
if (!value.trim()) return false
try { value = JSON.parse(value) } catch { return false }
}
return !!value && typeof value === 'object' && !Array.isArray(value)
&& ((value as any).type === 'object' || 'properties' in (value as any))
}
/** 字段实际的语法:显式声明优先,否则按类型推 */
export function syntaxOf(field: Pick<FieldDef, 'type' | 'syntax'>): FieldSyntax {
if (field.syntax) return field.syntax
@@ -199,6 +218,18 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
help: '默认关闭:一轮只调一个工具,看到结果再想下一步。开启后一轮可发多个,更快,'
+ '但这一批中间没有新的思考',
},
{
key: 'output_schema', label: '结构化输出 Schema', type: 'json', advanced: true,
help: '要把查到的数交给口径卡时写。写了还要开下面的「按出处核对字段」才生效;'
+ '只写 Schema 不开,产出和以前一样只有文字',
},
{
key: 'cite_fields', label: '按出处核对字段', type: 'switch', advanced: true,
// 已经开着的不锁:开了之后又清掉 Schema,得还能把它关上
disabled: (c) => (c.cite_fields || hasOutputSchema(c.output_schema) ? null : '先在上面写「结构化输出 Schema」才能开'),
help: '结束后多一次抽取调用:模型为 Schema 里每个字段写出它来自哪次查询的哪一格,系统按查询快照取值、'
+ '核对,对不上的以快照为准;查不到的记为空,不兜底成 0。下游口径卡用 vars.变量名.字段 读',
},
...MODEL_FIELDS,
...COMMON_TAIL,
],
@@ -294,6 +325,12 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
],
},
{ key: 'fail_fast', label: '执行失败即中断', type: 'switch', advanced: true },
{
key: 'evidence_role', label: '证据角色', type: 'select', advanced: true,
options: [{ value: '', label: '计算(默认)' }, { value: 'source', label: '取数' }],
help: '报告不能直接引用代码节点的产出,沙箱算出来的数要进口径卡。只是把外部数据原样取回来'
+ '(调接口、读文件)的标「取数」;做了业务计算的留在「计算」,口径卡用它的数时会提醒',
},
...COMMON_TAIL,
],
defaults: { language: 'python', code: 'print("hello")', timeout: 30, network: false, fail_fast: true },
@@ -532,9 +569,24 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
description: '受控指标集:所有算术在这里发生,叙述层只能引用',
hasTarget: true, sources: [{ id: 'out', label: '' }],
fields: [
{ key: 'caliber', label: '口径名称', type: 'text', syntax: 'template', placeholder: '周报口径' },
{ key: 'caliber_version', label: '口径版本', type: 'text', placeholder: 'v1' },
{ key: 'metrics', label: '指标定义', type: 'metricsList' },
{ key: 'caliber_from', label: '口径卡从哪来', type: 'caliberFrom' },
{
key: 'caliber', label: '口径名称', type: 'text', syntax: 'template', placeholder: '周报口径',
when: (c) => !c.caliber_from,
},
{ key: 'caliber_version', label: '口径版本', type: 'text', placeholder: 'v1', when: (c) => !c.caliber_from },
{ key: 'metrics', label: '指标定义', type: 'metricsList', when: (c) => !c.caliber_from },
{
key: 'upgrade_policy', label: '上游发了新版本时', type: 'select', when: (c) => !!c.caliber_from,
options: [
{ value: '', label: '没声明:上游有新版本时挡住正式运行' },
{ value: 'recompute', label: `${UPGRADE_POLICY_LABEL.recompute}(recompute)` },
{ value: 'dual', label: `${UPGRADE_POLICY_LABEL.dual}(dual)` },
{ value: 'incomparable', label: `${UPGRADE_POLICY_LABEL.incomparable}(incomparable)` },
],
help: '钉住的那一版之后上游又发了新版本,正式运行前必须声明怎么处置,和子工作流的升版处置是同一套规则;'
+ '声明了就照它执行,并记进运行记录',
},
{
key: 'on_missing', label: '缺输入时', type: 'select', advanced: true,
options: [{ value: '', label: '整个节点失败' }, { value: 'null', label: '记为空值,交给出具契约判档' }],