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

一、可点击证据第二期

取数链路
- 智能体、工具节点、代码节点、知识检索取数时都记进证据台账;报告目录按台账编出 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
+16 -3
View File
@@ -1,7 +1,8 @@
import type {
Approval, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, ReviewResult, Run, RunEvent, RunStatus,
Skill, ToolChange, ToolInfo, ToolTrust, ValidationIssue, VarIssue, Variable, Workflow, WorkflowVersion,
Approval, AutofixResult, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, PublishCheck, PublishLevel, ReviewResult, Run,
RunEvent, RunStatus, Skill, ToolChange, ToolInfo, ToolTrust, ValidationIssue, VarIssue, Variable, Workflow,
WorkflowVersion,
} from '../types'
import { localActor } from '../lib/actor'
import { VALIDATION_TITLE, describeValidation } from '../lib/validation'
@@ -420,6 +421,18 @@ export const api = {
`/workflows/${id}/publish`, { level, version }),
validate: (graph: GraphSpec) =>
post<{ ok: boolean; issues: ValidationIssue[] }>('/workflows/validate', { graph }),
/**
* 发布前检查:validate 和发布门禁的并集,和真正发布同一套口径,另给每条问题的修复。
* 只读。不带 graph 就查库里的草稿。老后端没有这个接口(404),调用方按「不支持」处理
*/
publishCheck: (id: string, body: { level: PublishLevel; graph?: GraphSpec }, opts?: RequestOptions) =>
request<PublishCheck>(`/workflows/${id}/publish-check`,
{ method: 'POST', body: JSON.stringify(body), ...opts }),
/** 按选中的修复出一份预览(整张图 + 逐项改动)。只读:不存草稿、不发布。assist 时会调模型,可能要几十秒 */
autofix: (id: string, body: {
level: PublishLevel; graph?: GraphSpec; apply: string[]; choices?: Record<string, unknown>; assist?: boolean
}, opts?: RequestOptions) =>
request<AutofixResult>(`/workflows/${id}/autofix`, { method: 'POST', body: JSON.stringify(body), ...opts }),
/** 这张图里有哪些变量、谁产出、谁引用。纯静态分析,不需要跑过 */
variables: (graph: GraphSpec) =>
post<{ variables: Variable[]; issues: VarIssue[] }>('/workflows/variables', { graph }),
+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: '记为空值,交给出具契约判档' }],
+17
View File
@@ -25,6 +25,7 @@ import * as evidence from '../lib/evidence'
import { EvidenceDoc, EvidenceField } from '../run/EvidenceDoc'
import { Markdown } from '../run/Markdown'
import evidenceFixture from '../run/__tests__/evidence-doc.json'
import evidenceQuery from '../run/__tests__/evidence-query.json'
import mdPinned from '../run/__tests__/markdown-pinned.json'
import type { EvidenceDocData } from '../types'
import '../index.css'
@@ -185,6 +186,8 @@ function DatasourceConsumers() {
}
const EV_DOC = evidenceFixture.doc as unknown as EvidenceDocData
/** 第二期:查询单元格、整表、口径卡来源(evidence-query.json,compose_doc 真跑出来的) */
const EV_QUERY = evidenceQuery.doc as unknown as EvidenceDocData
const EV_LEGACY = evidenceFixture.legacy
/** 同一份旧契约的出具,去掉位置:老运行就是这样,只能按字符串标 */
const LEGACY_LOOSE = {
@@ -253,6 +256,19 @@ function EvidenceOnly() {
</div>
</div>
<EvidenceDemo />
{/*
第二期:报告直接引用查询单元格、整表,口径卡的输入核对到 agent 字段和查询快照。
片段接口由 check-evidence 用 page.route 伪造(按 runId 认出这一份夹具)
*/}
<div className="flex flex-col gap-4" id="evidence-query-demo">
<div id="evidence-query" className="rounded-lg border p-3">
<div className="mb-1 text-2xs text-faint">查询单元格、整表、口径卡来源</div>
<EvidenceDoc doc={EV_QUERY} artifact={evidenceQuery.doc_artifact} runId={evidenceQuery.run_id} label="answer" tally />
</div>
<div id="evidence-query-narrow" className="rounded-lg border bg-panel p-2.5" style={{ width: 360, maxWidth: '100%' }}>
<EvidenceDoc doc={EV_QUERY} artifact={evidenceQuery.doc_artifact} runId={evidenceQuery.run_id} label="answer" dense tally />
</div>
</div>
<div id="evidence-long" className="rounded-lg border p-3">
<div className="mb-1 text-2xs text-faint">长报告:{EV_LONG.blocks.length} 块,块级 content-visibility,超过 3000 字先折叠</div>
<EvidenceDoc doc={EV_LONG} label="长报告" tally />
@@ -544,6 +560,7 @@ function Harness() {
// 检查脚本直接拿应用同一份模块实例测 lib:instanceof ApiError 才靠得住
lib: { format, status, keys, terms, errors, explain, health, actor, validation, evidence },
evidenceFixture,
evidenceQuery,
}
createRoot(document.getElementById('root')!).render(
+201 -8
View File
@@ -11,10 +11,12 @@
* 不存在)。其余几种先把外观定下,后续期接上时不用再各处补。
*/
import { EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, evidenceTally } from './terms'
import { EVIDENCE_KIND_LABEL, EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, UPGRADE_POLICY_LABEL, evidenceTally } from './terms'
import { NONE, formatNumber, shortId } from './format'
import type {
EvidenceBlock, EvidenceDocData, EvidenceFieldRef, EvidenceGraph, EvidenceSeal, EvidenceSegment,
EvidenceSegmentDetail, EvidenceStep, EvidenceUnit, EvidenceViolation, ReviewResult,
EvidenceBlock, EvidenceCaliberSource, EvidenceCaliberUpgrade, EvidenceDocData, EvidenceFieldRef, EvidenceGraph,
EvidenceInput, EvidenceLocator, EvidenceSeal, EvidenceSegment, EvidenceSegmentDetail, EvidenceStep, EvidenceUnit,
EvidenceViolation, ReviewResult,
} from '../types'
import type { MarkSpec } from '../run/Markdown'
@@ -54,7 +56,7 @@ export const EVIDENCE_STATE: Record<EvidenceStateCode, EvidenceStateMeta> = {
code: 'deterministic', label: EVIDENCE_STATE_LABEL.deterministic, line: 'solid', glyph: '',
color: 'var(--st-done)', decoration: mix('--st-done', 60), soft: 'var(--st-done-soft)',
alert: false, phase: 1,
hint: '数字由系统从口径卡取值、按口径卡的格式渲染,不是模型写的',
hint: '由系统从证据(口径卡、查询快照、运行输入)里取值、按确定的规则渲染,不是模型写的',
},
supported: {
code: 'supported', label: EVIDENCE_STATE_LABEL.supported, line: 'badge', glyph: '◆',
@@ -123,19 +125,210 @@ export function unitText(unit: Pick<EvidenceUnit, 'segments'>): string {
return (unit.segments ?? []).filter((s) => s.kind !== 'structural').map((s) => s.text).join('')
}
/** 片段的来源说一句:「口径卡指标 环比增幅」「运行输入 week」 */
/**
* 片段的来源说一句:「口径卡指标 环比增幅」「运行输入 week」「查询 Q3 · 第 6 行 · amount」。
* 单元格先看 cite 的种类:查询条目在目录里是 query,引用它的一格是 cell
*/
export function sourceOf(seg: EvidenceSegment, doc?: Pick<EvidenceDocData, 'catalog'> | null): string {
const cite = seg.cite
if (!cite) return ''
const entry = cite.alias ? doc?.catalog?.[cite.alias] : undefined
if (cite.kind === 'cell' || (cite.kind !== 'metric' && cite.kind !== 'input' && entry?.kind === 'query')) {
const where = locatorText(cite.locator)
return [EVIDENCE_TEXT.query(cite.alias ?? ''), where].filter(Boolean).join(' · ')
}
if (cite.kind === 'metric' || entry?.kind === 'metric') {
const name = entry?.name ?? cite.locator?.metric ?? cite.ref ?? ''
return name ? `口径卡指标 ${name}` : '口径卡指标'
return name ? `${EVIDENCE_KIND_LABEL.metric} ${name}` : EVIDENCE_KIND_LABEL.metric
}
if (cite.kind === 'input' || entry?.kind === 'input') {
return `运行输入 ${entry?.locator?.field ?? cite.locator?.field ?? cite.ref ?? ''}`.trim()
return `${EVIDENCE_KIND_LABEL.input} ${entry?.locator?.field ?? cite.locator?.field ?? cite.ref ?? ''}`.trim()
}
return cite.alias ?? cite.ref ?? ''
const kind = cite.kind ? EVIDENCE_KIND_LABEL[cite.kind] : ''
return [kind, cite.alias ?? cite.ref].filter(Boolean).join(' ')
}
/**
* 查询快照里的位置怎么说:「第 6 行 · amount」「第 1–5 行 · amount」「第 1–5 行 · week、amount」。
* 行号给人看从 1 数(引用原文 Q3.r5 里的 r5 从 0 数,面板另把原文摆出来)
*/
export function locatorText(loc: EvidenceLocator | null | undefined): string {
if (!loc) return ''
const ints = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : null)
let rows = ''
const row = ints(loc.row)
if (row != null) rows = `第 ${formatNumber(row + 1)} 行`
else if (Array.isArray(loc.rows) && loc.rows.length) {
const a = ints(loc.rows[0])
const b = ints(loc.rows[loc.rows.length - 1])
if (a != null && b != null) rows = a === b ? `第 ${formatNumber(a + 1)} 行` : `第 ${formatNumber(a + 1)}–${formatNumber(b + 1)} 行`
}
const cols = typeof loc.column === 'string' && loc.column ? loc.column
: loc.columns && typeof loc.columns === 'object' ? Object.values(loc.columns).filter((c) => typeof c === 'string').join('、')
: ''
return [rows, cols].filter(Boolean).join(' · ')
}
/** 证据里的值怎么写:数带千分位、不丢小数;布尔写是否;拿不到写「—」 */
export function evidenceValue(v: unknown): string {
if (v == null || v === '') return NONE
if (typeof v === 'number') return Number.isFinite(v) ? v.toLocaleString('en-US', { maximumFractionDigits: 20 }) : String(v)
if (typeof v === 'boolean') return v ? '是' : '否'
if (typeof v === 'object') return JSON.stringify(v)
return String(v)
}
/**
* 查询步骤的窗口:接口只给被引用的行加前后各 2 行。
*
* - offset:rows[0] 在快照里是第几行;没给就当从 0 开始、也不说位置
* - marks:要高亮的行,换算成窗口里的下标。highlight.rows 按快照行号给(方案第 5 节);
* 全都落在窗口里才这么认,否则看它们是不是本来就是窗口下标(row_offset 之前的号、老接口)
* - windowed:窗口没盖住整份快照,要说「仅显示被引用的行及前后各 2 行」
*/
export function queryWindow(step: Pick<EvidenceStep,
'rows' | 'columns' | 'row_offset' | 'row_index' | 'total_rows' | 'highlight'>): {
columns: string[]; rows: unknown[][]
/** 每一行在快照里是第几行(从 0 数);不知道时是 null */
index: number[] | null
total: number | null
marks: number[]; cols: string[]
/** 精确到格的高亮:[窗口下标, 列名];接口没给时 null,按 marks × cols 画 */
cells: [number, string][] | null
windowed: boolean
/** 「第 4–8、10–12 行」:窗口在快照里的位置,从 1 数;不知道时 '' */
span: string
} {
const rows = Array.isArray(step.rows) ? step.rows.filter(Array.isArray) as unknown[][] : []
const columns = Array.isArray(step.columns) ? step.columns.map(String) : []
const int = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : null)
const total = int(step.total_rows)
// 行号:row_index 一行一个(窗口可以不连续)最准;只有 row_offset 时按连续的算
const given = Array.isArray(step.row_index) ? step.row_index.map(int) : null
const offset = int(step.row_offset)
const index = given && given.length === rows.length && given.every((r) => r != null) ? given as number[]
: offset != null ? rows.map((_, i) => offset + i)
: null
const toWindow = (r: number): number => {
if (index) {
const at = index.indexOf(r)
if (at >= 0) return at
}
return -1
}
const inWindow = (r: number) => r >= 0 && r < rows.length
// 行号按快照认(方案第 5 节),认得出几个标几个:窗口被截到 MAX_WINDOW_ROWS 时后面几行不在窗口里,
// 不能因此一行都不标。一个都认不出、却都落在窗口里的,当成窗口下标(老接口);认不出的是 -1
const place = (list: number[]): number[] | null => {
const hit = list.map(toWindow)
return hit.some((i) => i >= 0) ? hit : list.every(inWindow) ? list : null
}
const wanted = (Array.isArray(step.highlight?.rows) ? step.highlight.rows : []).map(int).filter((r): r is number => r != null)
const marks = ((wanted.length && place(wanted)) || []).filter((i) => i >= 0)
const cols = (Array.isArray(step.highlight?.cols) ? step.highlight.cols : []).map(String).filter((c) => columns.includes(c))
const rawCells = (Array.isArray(step.highlight?.cells) ? step.highlight.cells : [])
.filter((c) => Array.isArray(c) && int(c[0]) != null && columns.includes(String(c[1])))
const cellRows = rawCells.length ? place(rawCells.map((c) => c[0] as number)) : null
const placed = cellRows ? rawCells.map((c, i) => [cellRows[i], String(c[1])] as [number, string]).filter(([r]) => r >= 0) : []
const cells = placed.length ? placed : null
const windowed = !!index && total != null && index.length < total
return { columns, rows, index, total, marks, cols, cells, windowed, span: index ? spanText(index) : '' }
}
/** [3,4,5,6,7,9,10,11] → 「第 4–8、10–12 行」(从 1 数) */
function spanText(index: number[]): string {
if (!index.length) return ''
const sorted = [...index].sort((a, b) => a - b)
const parts: string[] = []
let start = sorted[0]
let prev = sorted[0]
for (const r of [...sorted.slice(1), Number.NaN]) {
if (r === prev + 1) { prev = r; continue }
parts.push(start === prev ? formatNumber(start + 1) : `${formatNumber(start + 1)}–${formatNumber(prev + 1)}`)
start = r
prev = r
}
return `第 ${parts.join('、')} 行`
}
/**
* 这个输入对应链里的哪一个查询步骤:先按快照工件认,再按接口补的全局编号(input.query、
* input.cell 的前缀)认。agent 字段的 ref 是那个节点内部的编号,不拿它对。认不出返回 -1
*/
export function queryOf(
input: Pick<EvidenceInput, 'artifact' | 'query' | 'cell'>, queries: Pick<EvidenceStep, 'artifact' | 'alias'>[],
): number {
if (input.artifact) {
const i = queries.findIndex((q) => q.artifact === input.artifact)
if (i >= 0) return i
}
const alias = input.query || (typeof input.cell === 'string' ? input.cell.split('.')[0] : '')
return alias ? queries.findIndex((q) => q.alias === alias) : -1
}
export type SourceTone = 'ok' | 'warn' | 'alert' | 'muted'
/**
* 输入来源那一行说什么、多醒目。
*
* - agent 字段(开了 cite_fields):与快照一致 / 模型报 X 快照是 Y 已按快照取值 / 没查到记为空;
* unresolved 和 missing(模型写了 from: null)同一种说法:值都是空的,没有兜底成 0
* - cell() 取数:与快照一致 / 算的时候用的值和快照不一样(值没被换掉,照实说)/ 核对不到
* - 代码节点:取数角色提醒(核对不到快照),计算角色醒目(沙箱里的算术不该绕开口径卡)
* - 其余(运行输入、老运行):一期的 ok / missing
*/
export function inputSource(input: EvidenceInput): { tone: SourceTone; text: string; reason?: string } {
const status = input.status ?? ''
if (input.via === 'agent_field') {
if (status === 'verified') return { tone: 'ok', text: EVIDENCE_TEXT.sourceVerified }
if (status === 'mismatch') {
return { tone: 'warn', text: EVIDENCE_TEXT.sourceMismatch(evidenceValue(input.model_value), evidenceValue(input.value)) }
}
return { tone: 'warn', text: EVIDENCE_TEXT.sourceEmpty, reason: input.reason || undefined }
}
if (input.via === 'tool_cell') {
if (status === 'verified') return { tone: 'ok', text: EVIDENCE_TEXT.sourceVerified }
if (status === 'mismatch') {
return { tone: 'warn', text: EVIDENCE_TEXT.cellMismatch(evidenceValue(input.value),
evidenceValue(input.snapshot_value !== undefined ? input.snapshot_value : input.value)) }
}
if (input.value == null) return { tone: 'warn', text: EVIDENCE_TEXT.sourceEmpty, reason: input.reason || undefined }
return { tone: 'warn', text: EVIDENCE_TEXT.cellUnresolved, reason: input.reason || undefined }
}
if (input.via === 'code') {
return input.role === 'source'
? { tone: 'warn', text: EVIDENCE_TEXT.codeSource(input.node_id ?? '') }
: { tone: 'alert', text: EVIDENCE_TEXT.codeCompute(input.node_id ?? '') }
}
if (status === 'missing' || input.value == null) return { tone: 'warn', text: EVIDENCE_TEXT.inputMissing }
return { tone: 'muted', text: '' }
}
/** 值得在「输入来源」里单独列一行的输入:能核对到快照的、代码节点的、缺的 */
export const notableInput = (input: EvidenceInput): boolean =>
input.via === 'agent_field' || input.via === 'tool_cell' || input.via === 'code'
|| input.status === 'missing' || input.value == null
/**
* 口径卡钉在哪:「口径卡「周报口径」v3,来自「销售周报」v5」。工作流名接口没给就按目录找,
* 再没有就写工作流 id 的前几位——不写 undefined
*/
export function caliberSourceText(
caliber: string | undefined, version: string | undefined,
from: EvidenceCaliberSource | null | undefined, workflowName?: string,
): string | null {
if (!from || typeof from !== 'object' || (!from.workflow_id && !from.workflow_name)) return null
const wf = from.workflow_name || workflowName || (from.workflow_id ? shortId(from.workflow_id, 12) : NONE)
const v = from.workflow_version != null && from.workflow_version !== '' ? `v${String(from.workflow_version).replace(/^v/, '')}` : ''
return EVIDENCE_TEXT.caliberFrom(caliber ?? '', version ?? '', wf, v)
}
/** 升版处置那一句:「上游已有 v6,按「并排双印新旧口径」处置」。没有升版(null、没写 latest / policy)返回 null */
export function caliberUpgradeText(up: EvidenceCaliberUpgrade | null | undefined): string | null {
if (!up || typeof up !== 'object' || (!up.policy && !up.policy_label)) return null
const latest = up.latest != null && String(up.latest) !== '' ? `v${String(up.latest).replace(/^v/, '')}` : null
const policy = up.policy_label || (up.policy ? UPGRADE_POLICY_LABEL[up.policy] ?? up.policy : '')
return EVIDENCE_TEXT.caliberUpgrade(latest, policy)
}
/** 无证据的原因:裸数字,还是引用解析不了(带后端给的人话原因) */
+98
View File
@@ -36,6 +36,13 @@ export interface RunErrorExplain {
fixFirst?: boolean
/** fix 的站内地址,比笼统的「去工具库」更准:直接打开要改的那一项 */
fixTo?: string
/** 入口上写什么(「去数据页接入」)。不给就按 fix 的默认说法 */
fixLabel?: string
/**
* 该去改的节点(名字)和出错的不是同一个:整形节点解析上游的文字失败,毛病在上游那个
* 模型节点,打开整形节点的设置什么也改不了
*/
fixNode?: string
/** 原文,放进「技术细节」 */
raw: string
}
@@ -61,6 +68,58 @@ export function stripClassPrefix(text: string): string {
return s.trim()
}
/** 后端 io.TEMPLATE_HINT:模板渲染出来不是合法 JSON、又说不出是哪一处时的老说法 */
const TEMPLATE_HINT = '检查模板里的引号、逗号,字符串值要用 | json 过滤器输出'
/** 后端 app/api/runs.py 的 TOOL_MISSING:发起运行时发现绑定的工具在本机不存在 */
export const RUN_TOOL_MISSING = 'run_tool_missing'
const DATA_TOOL = /^db_(?:query|schema)__/
/**
* 「绑定的工具在本机不存在:「X」(调用工具)绑的 db_query__nope;「团队」的成员「研究员」绑的 mcp:a/b。
* 去数据页接入,或在节点里重新选」。数据源工具(db_query__ / db_schema__)要去数据页接入,自定义和
* MCP 工具去工具页;两种都缺时入口按第一个缺的走,话里两边都说到
*/
function explainToolMissing(plain: string, raw: string, coded = false): RunErrorExplain | null {
const m = plain.match(/^绑定的工具在本机不存在[::]\s*([\s\S]+)$/)
// 带着机读码、话却改了说法:照样按这一类讲,名字认不出就只给工具页
if (!m && !coded) return null
const body = (m ? m[1] : plain).trim()
const cut = body.lastIndexOf('。')
const list = (cut >= 0 ? body.slice(0, cut) : body).trim()
const advice = cut >= 0 ? body.slice(cut + 1).trim() : ''
// 超过 8 处时后端在最后一个名字后面接「等 N 处」:那个「等」不是名字的一部分
const names = [...list.matchAll(/绑的\s*([^\s;;,,。]+)/g)].map((x) => x[1].replace(/等$/, '')).filter(Boolean)
const first = names[0] ?? ''
const others = names.filter((n) => !DATA_TOOL.test(n))
const toData = DATA_TOOL.test(first) || (!names.length && /数据页/.test(advice))
const fixTo = toData ? '/data'
: !others.length ? '/tools'
: others.every((n) => n.startsWith('mcp:')) ? '/tools/mcp'
: others.every((n) => !n.startsWith('mcp:')) ? '/tools/custom' : '/tools'
return {
title: names.length === 1 ? `绑定的工具「${first}」在本机不存在` : '绑定的工具在本机不存在',
reason: `${endStop(list)}这次运行没有发起,前面的节点一个都没跑。`,
action: `${endStop(advice || (toData ? '去数据页接入,或在节点里重新选' : '去工具页接入,或在节点里重新选'))}接入之后重新运行。`,
continuable: false,
fix: 'tools',
fixTo,
fixLabel: toData ? '去数据页接入' : '去工具页接入',
raw,
}
}
/**
* 发起运行那一下被拒的报错(POST /runs 的 ApiError)。只认「绑定的工具在本机不存在」:认机读码
* run_tool_missing,老后端没码时认原话。别的交给 toast 的通用翻译,返回 null
*/
export function explainStartError(e: unknown): RunErrorExplain | null {
const code = e && typeof e === 'object' ? (e as { code?: unknown }).code : undefined
const text = e instanceof Error ? e.message : typeof e === 'string' ? e : ''
if (code !== RUN_TOOL_MISSING && !/^绑定的工具在本机不存在/.test(text)) return null
return explainToolMissing(stripClassPrefix(text), text, code === RUN_TOOL_MISSING)
}
/** 直达某个自定义工具的编辑框(工具页读 ?edit= 打开它)。fixTo 和工具库里的「去改」共用 */
export const customToolEditPath = (name: string) => `/tools/custom?edit=${encodeURIComponent(name)}`
@@ -135,6 +194,45 @@ export function explainRunError(error: string | null | undefined, detail?: strin
if (!text) {
return { title: '运行失败,但没有留下原因', action: '打开「原始事件」看最后几条记录。', continuable: true, raw }
}
// 整形节点按 JSON 解析失败(后端 io._json_error)。两种原话:出错的位置落在上游模型写的文字里时
// 点名上游(模板没错,别让人去查模板);否则是模板本身写错了。两种都是图的问题:原样接着跑
// 拿到的还是同一段文字、同一份模板,只会再失败一次,所以不给「接着跑」,指到画布上去改
// 标题、原因、怎么办都照原话切,不改写:展开区据此认出原话已经说完了,不再整段贴一遍。
// 放在最前:原话里带着用户起的节点名(「查询超时订单」「额度查询」),排在后面会被超时、限流、
// 连不上那几条按整句关键词抢走,又把「接着跑」给回来
const upstream = plain.match(/^(上游「([^」]+)」输出的不是合法 JSON([^)]*))[,,]\s*([^;;]*)[;;]\s*([\s\S]+)$/)
if (upstream) {
return {
title: upstream[1],
reason: `${endStop(upstream[3].trim())}模板本身没有写错。`,
action: `${endStop(upstream[4].trim())}原样接着跑拿到的还是同一段文字,会再失败一次。`,
continuable: false,
fix: 'canvas',
// 要改的是写出这段文字的上游,不是整形节点:入口指到上游去
fixNode: upstream[2],
raw,
}
}
const badJson = plain.match(/^(模板渲染出来的不是合法 JSON([^)]*))[。.]?\s*([\s\S]*)$/)
if (badJson) {
const hint = badJson[2].trim()
// 后端点名了模板里是哪一处、该怎么改(加 | json、去掉引号、取出来是空的):照它说,
// 不再追加「改用 output_schema」——那句指的是另一条路,和它给的改法对不上。
// 只有老的笼统说法(或者什么都没说)才补这一句
const pointed = hint.startsWith('模板里 {{')
return {
title: badJson[1],
action: `${endStop(hint || TEMPLATE_HINT)}`
+ (pointed ? '改完再运行。' : '模板里插的是 agent / 模型写的文字时,改用 output_schema + cite_fields 让它交结构化数据。改完再运行。'),
continuable: false,
fix: 'canvas',
raw,
}
}
// 发起就被拒:绑定的工具在本机不存在(POST /runs 422 run_tool_missing)。这次运行根本没开始,
// 谈不上接着跑;去接入,或者回画布重新选
const missingTool = explainToolMissing(plain, raw)
if (missingTool) return missingTool
// 工具库里存着的坏参数定义。它不在这次运行的快照里:到工具页改好,回来原样接着跑
// 就能过;不先改,接着跑还是同样的失败
const broken = explainBrokenTools(plain, raw)
+128
View File
@@ -230,8 +230,136 @@ export const EVIDENCE_TEXT = {
docMismatch: '成果字段和报告文档对不上,按普通文本显示',
docOtherRun: '证据文档不是这次运行写的,按普通文本显示',
ambiguous: (candidates: string[]) => `出处不唯一:候选 ${candidates.join('、')}`,
// ---- 第二期:查询步骤、输入来源、口径卡来源 ----
query: (alias: string) => `查询 ${alias}`.trim(),
copySql: '复制 SQL',
/** 窗口外的行:面板只拿到被引用的行加前后各 2 行 */
windowed: '仅显示被引用的行及前后各 2 行',
openSnapshot: '打开完整快照',
snapshotTitle: (alias: string) => `查询 ${alias} · 完整快照`,
masked: '已遮罩',
/** 面板底部:被遮罩的列 + 遮罩不是安全边界(用户拍板写明) */
maskNote: (cols: string[]) =>
`已遮罩的列:${cols.join('、')}。在有身份体系之前,遮罩只减少暴露,不是安全边界:完整快照、工件接口里仍是原值`,
queryMissing: '查询的行要从证据接口取,这一次没取到',
queryPending: '正在取查询的行…',
queryHash: '查询快照取回时哈希对不上,疑似被改过:这些行不能当证据',
truncatedSnapshot: '查询撞了行数上限,库里还有更多',
windowCut: (n: number) => `被引用的行太多,这里只列了前 ${formatNumber(n)} 行,其余看完整快照`,
sources: '输入来源',
gotoQuery: (alias: string) => `看查询 ${alias}`.trim(),
sourceVerified: '与快照一致',
sourceMismatch: (told: string, truth: string) => `模型报 ${told},快照是 ${truth},已按快照取值`,
/** cell() 取数:算的时候用的值和快照不一样,值没有被换掉,照实说上游改写过 */
cellMismatch: (used: string, truth: string) => `算的时候用的是 ${used},快照里是 ${truth}:上游改写过这份结果`,
sourceEmpty: '没查到,记为空,没有兜底成 0',
cellUnresolved: '核对不到查询快照',
codeCompute: (node: string) =>
`代码节点${node ? `「${node}」` : ''}算出来的数(计算):沙箱里的算术系统核对不了,业务计算要写进口径卡`,
codeSource: (node: string) =>
`来自代码节点${node ? `「${node}」` : ''}(标为取数):沙箱跑出来的结果,系统核对不到查询快照`,
inputMissing: '缺:上游没给出这个值',
caliberFrom: (caliber: string, version: string, workflow: string, wfVersion: string) =>
`口径卡「${caliber || '—'}」${version},来自「${workflow}」${wfVersion}`,
caliberUpgrade: (latest: string | null, policy: string) =>
`${latest ? `上游已有 ${latest}` : '上游有新版本'},按「${policy}」处置`,
} as const
/**
* 口径升版的三种处置,和后端 governance.UPGRADE_POLICY_LABELS 同一套说法。子工作流和
* 钉版本的口径卡(caliber_from)共用
*/
export const UPGRADE_POLICY_LABEL: Record<string, string> = {
recompute: '用新口径回算历史',
dual: '并排双印新旧口径',
incomparable: '标注与历史不可比',
}
/**
* 子工作流钉住版本后的升版处置说明。选项和口径卡的那个下拉是同一份(检查器直接借用口径卡
* 的字段定义),这里只换掉说明里「和谁同一套」那半句
*/
export const SUBGRAPH_UPGRADE_HELP = '钉住的那一版之后,被嵌的工作流又发了新版本:正式运行前必须声明怎么处置,'
+ '和钉住别处的口径卡是同一套规则;声明了就照它执行,并记进运行记录'
/** 上游在钉住的那一版之后又发了版:子工作流和口径卡的提醒同一句 */
export const upgradeNewerText = (latest: number, pinned: number) =>
`上游已有 v${latest}(钉的是 v${pinned}):正式运行前要在下面声明升版处置,否则会被挡住`
/**
* 发布前检查与自动修复:发布弹窗和问题面板的「发布前检查」共用一套说法。
* 原则写在话里:修复只出预览、人确认了才存草稿,永远不替人发布
*/
export const PUBLISH_FIX_TEXT = {
section: '发布前检查',
lint: '校验',
checking: '正在做发布前检查…',
unsupported: '这个后端还没有发布前检查:点「发布」时门禁照旧检查,拦下的问题会列在这里',
failed: '发布前检查没做成',
retry: '重试',
recheck: '重新检查',
run: '检查',
stale: '画布改过了,结果可能已经过时',
blocked: (n: number) => `发布前检查:会被门禁拦下 ${n} 处`,
gateBlocked: (n: number) => `门禁拦下了 ${n} 处,改完再发布`,
passed: '发布前检查通过:没有会被门禁拦下的问题',
warnings: (n: number) => `另有 ${n} 条提示`,
fixAll: (n: number) => `一键修复可自动修的 ${n} 处`,
fixOne: '修复',
fixHint: (label: string) => `先看预览:${label}`,
choose: '预览',
chooseFirst: '先选好再预览',
multiple: '可以多选',
suggested: '建议',
assist: '交给 Copilot',
assistHint: '让 Copilot 试着改剩下的问题。它改的同样只是预览,要人拿主意的会原样问你',
locked: (why: string) => `${why}。现在不能修复`,
previewing: '正在生成修复预览…',
assisting: 'Copilot 正在试着修,可能要几十秒…',
stop: '停下',
previewTitle: (n: number) => `修复预览 · ${n} 处改动`,
noChange: '这一次没有可以应用的改动',
rejected: '没有采用',
assistSaid: 'Copilot',
questions: 'Copilot 需要你拿主意',
afterOk: '应用后门禁不再拦',
afterLeft: (n: number) => `应用后还剩 ${n} 处会被拦下`,
apply: '应用并重新检查',
discard: '放弃',
applyNote: '应用后存成新的草稿版本,再重新检查一遍;不会自动发布',
dirtyNote: '画布上还有没保存的改动,应用时会一起存进草稿',
saving: '正在保存草稿…',
rechecking: '正在重新检查…',
saveFailed: '草稿没保存上',
saveFailedHint: '修复已经放到画布上(可以撤销);保存成功之前不能发布',
retrySave: '重试保存',
stalePreview: '预览之后画布又改过了,这份预览对不上了:重新检查一次再修',
autofixMissing: '这个后端还不支持自动修复:照提示手动改,或者打开助手描述一遍',
autofixFailed: '修复预览没生成出来',
applied: (n: number, version?: number) => `已应用 ${n} 处修复${version != null ? `,存为 v${version}` : ''}`,
saveNote: (labels: string[]) => `发布前修复:${labels[0] ?? ''}${labels.length > 1 ? ` 等 ${labels.length} 处` : ''}`,
/** 撤销栈里这一步叫什么 */
undoLabel: (n: number) => `发布前修复(${n} 处)`,
pendingPreview: '先应用或放弃修复预览',
unsaved: '修复还没保存上',
whole: '整张工作流',
} as const
/** 证据的种类怎么叫:aria-label、面板标题、出处那一句 */
export const EVIDENCE_KIND_LABEL: Record<string, string> = {
metric: '口径卡指标',
input: '运行输入',
cell: '查询结果',
query: '查询结果',
table: '整表',
retrieval: '知识库检索',
node_output: '代码节点的产出',
entity: '表或字段',
column: '字段',
quote: '引文',
}
/**
* MCP / 自定义工具的信任档:工具页的三选一、工具徽标、审批卡的「始终允许」共用这一份。
* 「始终允许」只指 always;审批卡上那个按钮设的是 gated,按钮字短,说明里写全
+207 -6
View File
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
AlertTriangle, ChevronRight, Database, FileSpreadsheet, Info, KeyRound, Lock, Plug, Plus, RefreshCw,
AlertTriangle, ChevronRight, Database, EyeOff, FileSpreadsheet, Info, KeyRound, Lock, Plug, Plus, RefreshCw,
Search, Table2, Upload, X,
} from 'lucide-react'
import clsx from 'clsx'
@@ -41,6 +41,9 @@ export const isUploadedTable = (row: any): boolean =>
const NAME_RE = /^[a-z][a-z0-9_]{0,40}$/
/** 数据源 options 里的键:证据面板展示查询原始行时,这些列一律写「已遮罩」 */
const MASK_KEY = 'mask_columns'
/**
* 增、删、改、传之后让全局的数据源目录跟上:检查器挑工具、问数据的范围、助手的数据源
* 提示都读它(store/catalog 的 datasources),不重拉的话刚接入的库在那几处看不见
@@ -222,6 +225,8 @@ function SourceCard({ row, meta, onChange, onRemoved, onEdit, onReupload, kick }
const uploaded = isUploadedTable(row)
// 传上来的表通常只有一两张,直接摊开;库动辄几十上百个对象,默认收着
const [open, setOpen] = useState(() => uploaded && row.table_count > 0 && row.table_count <= 3)
const [masking, setMasking] = useState(false)
const masks = maskList(row.options?.[MASK_KEY])
const clock = useRunClock(!!busy)
const busySince = useRef(0)
useTicker(60_000)
@@ -419,8 +424,24 @@ function SourceCard({ row, meta, onChange, onRemoved, onEdit, onReupload, kick }
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 pb-2.5 pt-1.5 text-2xs text-faint">
<Address row={row} meta={meta} uploaded={uploaded} />
{row.options?.schema && <span className="chip">schema {row.options.schema}</span>}
{masks.length > 0 && (
<span className="chip" data-mask-columns={masks.join(',')} title={`证据面板里显示成「已遮罩」:${masks.join('、')}`}>
<EyeOff size={10} aria-hidden /> 遮罩 {formatNumber(masks.length)} 列
</span>
)}
{uploaded && (
// 传上来的表没有编辑框(只能重传),遮罩列在这里改
<button type="button" className="text-2xs underline decoration-dotted underline-offset-2 hover:text-dim"
onClick={() => setMasking(true)} data-edit-mask="">
{masks.length ? '改遮罩列' : '设遮罩列'}
</button>
)}
{!!row.tools?.length && <span className="mono">{row.tools.join(' · ')}</span>}
</div>
{masking && (
<MaskColumnsDialog row={row} onClose={() => setMasking(false)}
onSaved={(next) => { setMasking(false); onChange(next); syncCatalog() }} />
)}
{failed && (
<div className="px-3 pb-3">
@@ -747,11 +768,13 @@ interface SourceForm {
oracleMode: 'service_name' | 'sid'
serviceName: string
sid: string
/** options 里除 schema / service_name / sid 之外的键,全部摊开可编辑 */
/** options.mask_columns:证据面板展示查询原始行时遮掉的列 */
maskColumns: string[]
/** options 里除 schema / service_name / sid / mask_columns 之外的键,全部摊开可编辑 */
advanced: [string, string][]
}
const OWN_OPTION_KEYS = new Set(['schema', 'service_name', 'sid'])
const OWN_OPTION_KEYS = new Set(['schema', 'service_name', 'sid', MASK_KEY])
function toForm(source: any): SourceForm {
const o = source.options ?? {}
@@ -772,6 +795,7 @@ function toForm(source: any): SourceForm {
// 老数据把服务名存在 database 上:回显它,保存时后端会挪进 options
serviceName: o.service_name ?? (oracle ? source.database ?? '' : ''),
sid: o.sid ?? '',
maskColumns: maskList(o[MASK_KEY]),
advanced: Object.entries(o)
.filter(([k]) => !OWN_OPTION_KEYS.has(k))
.map(([k, v]) => [k, String(v ?? '')]),
@@ -779,9 +803,10 @@ function toForm(source: any): SourceForm {
}
function toBody(form: SourceForm, isNew: boolean, wasOracle = true): any {
const options: Record<string, string> = {}
const options: Record<string, string | string[]> = {}
for (const [k, v] of form.advanced) if (k.trim() && v.trim()) options[k.trim()] = v.trim()
if (form.schema.trim()) options.schema = form.schema.trim()
if (form.maskColumns.length) options[MASK_KEY] = form.maskColumns
const oracle = form.kind === 'oracle'
if (oracle) {
// 只写选中的那一个,另一个不带:两处都有值时引擎听 service_name,
@@ -824,10 +849,10 @@ const FIELD_LABEL: Record<string, string> = {
/**
* 决定连到哪个库的那几项(提交体里的)。schema 不在内:它只影响探查哪一片,不影响
* 连不连得上,后端判断测连接结果还作不作数时同样不看它
* 连不连得上,后端判断测连接结果还作不作数时同样不看它;遮罩列只管面板上怎么显示,也不在内
*/
function connectionOf(body: any): string {
const { schema: _schema, ...options } = body.options ?? {}
const { schema: _schema, [MASK_KEY]: _mask, ...options } = body.options ?? {}
return JSON.stringify([
body.kind, body.host ?? null, body.port ?? null, body.database ?? null, body.username ?? null,
options, !!body.password,
@@ -1120,6 +1145,9 @@ function SourceEditor({ source, kinds, onClose, onSaved }: {
)}
</Field>
<MaskColumnsField sourceId={source.id} synced={!!source.table_count} value={form.maskColumns}
onChange={(maskColumns) => set({ maskColumns })} />
<label className="flex cursor-pointer items-start gap-2 rounded-lg border p-2.5"
style={form.readonly ? undefined : { borderColor: 'var(--warn)', background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
<input type="checkbox" className="mt-0.5" checked={form.readonly}
@@ -1194,6 +1222,179 @@ function OracleTarget({ form, set }: { form: SourceForm; set: (patch: Partial<So
)
}
// ---------------------------------------------------------------------------
// 遮罩列(options.mask_columns)
// ---------------------------------------------------------------------------
/** options.mask_columns → 列名列表。列表和「a, b」这样的文字都认(后端 masked_columns 同一个认法),按大小写不敏感去重 */
function maskList(raw: unknown): string[] {
const items = typeof raw === 'string' ? raw.split(/[,,、\s]+/) : Array.isArray(raw) ? raw : []
const seen = new Set<string>()
const out: string[] = []
for (const item of items) {
const name = typeof item === 'string' || typeof item === 'number' ? String(item).trim() : ''
if (!name || seen.has(name.toLowerCase())) continue
seen.add(name.toLowerCase())
out.push(name)
}
return out
}
/** 挑列时最多读几张表的列:库动辄上百张表,一张一个请求,挑列用不着全读 */
const MASK_SCAN_TABLES = 40
/**
* 从已探查的结构里收列名(列名 → 出现在哪几张表)。第一次聚焦输入框才取,同一个数据源取一次
*/
function useSchemaColumns(sourceId: string | undefined, active: boolean) {
const [state, setState] = useState<{ status: 'idle' | 'loading' | 'ok' | 'error'; columns: Map<string, string[]>; tables: number; scanned: number }>(
{ status: 'idle', columns: new Map(), tables: 0, scanned: 0 })
// 取过就不再取(状态不进依赖:置成 loading 那一下会让 effect 重跑,把正在取的那次当成过期的丢掉)
const started = useRef<string | null>(null)
useEffect(() => {
if (!active || !sourceId || started.current === sourceId) return
started.current = sourceId
let alive = true
setState((s) => ({ ...s, status: 'loading' }))
void (async () => {
try {
const list: string[] = (await api.datasources.schema(sourceId))?.tables ?? []
const pick = list.slice(0, MASK_SCAN_TABLES)
const columns = new Map<string, string[]>()
for (let i = 0; i < pick.length; i += 6) {
const batch = await Promise.all(pick.slice(i, i + 6).map((t) => api.datasources.tableSchema(sourceId, t).catch(() => null)))
batch.forEach((detail, j) => {
for (const c of detail?.columns ?? []) {
const name = String(c?.name ?? '').trim()
if (!name) continue
columns.set(name, [...(columns.get(name) ?? []), pick[i + j]])
}
})
}
if (alive) setState({ status: 'ok', columns, tables: list.length, scanned: pick.length })
} catch {
if (alive) setState((s) => ({ ...s, status: 'error' }))
}
})()
return () => { alive = false; started.current = null }
}, [active, sourceId])
return state
}
/**
* 遮罩的列:列名一个个加成标签,可以从已探查的结构里挑,也可以直接输。
* 用户拍板写明:在有身份体系之前,遮罩只减少暴露,不是安全边界
*/
function MaskColumnsInput({ id, sourceId, synced, value, onChange }: {
id: string; sourceId?: string; synced: boolean; value: string[]; onChange: (v: string[]) => void
}) {
const [draft, setDraft] = useState('')
const [touched, setTouched] = useState(false)
const known = useSchemaColumns(sourceId, touched && synced)
const add = (text: string) => {
const next = maskList([...value, ...maskList(text)])
if (next.length !== value.length) onChange(next)
setDraft('')
}
const has = new Set(value.map((v) => v.toLowerCase()))
const options = [...known.columns.entries()].filter(([c]) => !has.has(c.toLowerCase()))
.sort((a, b) => a[0].localeCompare(b[0]))
const state = !sourceId ? '保存并探查结构之后可以从列里挑;现在可以直接输列名'
: !synced ? '还没探查过结构:直接输列名'
: known.status === 'loading' ? '正在读已探查的结构…'
: known.status === 'error' ? '已探查的结构没取到:直接输列名'
: known.status === 'ok'
? `从已探查的 ${formatNumber(known.scanned)} 张表里挑${known.tables > known.scanned ? `(共 ${formatNumber(known.tables)} 张,只读了前 ${formatNumber(known.scanned)} 张,别的直接输列名)` : ''},或者直接输列名`
: '点输入框可以从已探查的列里挑'
return (
<div data-mask-input="">
{value.length > 0 && (
<div className="mb-1.5 flex flex-wrap gap-1" aria-label="已遮罩的列">
{value.map((c) => (
<span key={c} className="chip mono" style={{ color: 'var(--text)', borderColor: 'var(--border-strong)' }} data-mask-chip={c}>
<EyeOff size={10} aria-hidden /> {c}
<button type="button" className="ml-0.5 hover:opacity-60" aria-label={`不再遮罩 ${c}`}
onClick={() => onChange(value.filter((v) => v !== c))}>
<X size={9} aria-hidden />
</button>
</span>
))}
</div>
)}
<div className="flex gap-1.5">
<input id={id} className="field mono min-w-0 flex-1" list={`${id}-list`} value={draft} autoComplete="off" spellCheck={false}
placeholder="phone, email" aria-describedby={`${id}-hint`}
onFocus={() => setTouched(true)}
onChange={(e) => {
const v = e.target.value
// 从候选里点中一项(浏览器报 insertReplacementText,不是逐字敲的)、或者敲了逗号:直接加成标签。
// 逐字敲到恰好等于某个列名(敲 id_card 途中的 id)不算点中
const kind = (e.nativeEvent as InputEvent).inputType
const picked = (!kind || kind === 'insertReplacementText') && known.columns.has(v)
if (/[,,、]/.test(v) || picked) add(v)
else setDraft(v)
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing && draft.trim()) { e.preventDefault(); add(draft) }
if (e.key === 'Backspace' && !draft && value.length) onChange(value.slice(0, -1))
}} />
<button type="button" className="btn btn-sm" disabled={!draft.trim()} onClick={() => add(draft)}>加上</button>
</div>
<datalist id={`${id}-list`}>
{options.slice(0, 300).map(([c, tables]) => (
<option key={c} value={c}>{tables.slice(0, 3).join('、')}{tables.length > 3 ? ` 等 ${tables.length} 张表` : ''}</option>
))}
</datalist>
<div id={`${id}-hint`} className="mt-1 space-y-0.5 text-2xs leading-relaxed text-faint">
<div>证据面板展示查询结果的原始行时,这些列(不分大小写)一律显示成「已遮罩」。{state}</div>
<div style={{ color: 'var(--st-waiting)' }} data-mask-boundary="">
在有身份体系之前,遮罩只减少暴露,不是安全边界:完整快照仍能按工件取到,SQL 里给列起别名也能绕开
</div>
</div>
</div>
)
}
function MaskColumnsField(props: { sourceId?: string; synced: boolean; value: string[]; onChange: (v: string[]) => void }) {
return (
<div data-field="mask_columns">
<label className="label" htmlFor="ds-mask-columns">遮罩的列</label>
<MaskColumnsInput id="ds-mask-columns" {...props} />
</div>
)
}
/** 传上来的表没有编辑框:卡片上单独改遮罩列,options 其余的键原样带上 */
function MaskColumnsDialog({ row, onClose, onSaved }: { row: any; onClose: () => void; onSaved: (row: any) => void }) {
const [initial] = useState(() => maskList(row.options?.[MASK_KEY]))
const [value, setValue] = useState(initial)
const [saving, setSaving] = useState(false)
const dirty = value.join('\u0000') !== initial.join('\u0000')
const save = async () => {
setSaving(true)
try {
const { [MASK_KEY]: _old, ...rest } = row.options ?? {}
onSaved(await api.datasources.update(row.id, { options: value.length ? { ...rest, [MASK_KEY]: value } : rest }))
toast.ok(value.length ? `「${row.name}」遮罩 ${value.length} 列` : `「${row.name}」不再遮罩任何列`)
} catch (e) {
toast.error(e)
} finally {
setSaving(false)
}
}
return (
<Modal open onClose={onClose} dirty={dirty} width={520} title={`「${row.name}」的遮罩列`}
footer={<>
<button className="btn" onClick={onClose}>取消</button>
<button className="btn btn-primary" disabled={saving || !dirty} onClick={() => void save()}>
{saving ? <Spinner size={11} /> : null} 保存
</button>
</>}>
<MaskColumnsField sourceId={row.id} synced={!!row.table_count} value={value} onChange={setValue} />
</Modal>
)
}
// ---------------------------------------------------------------------------
// 传表格
// ---------------------------------------------------------------------------
+13 -2
View File
@@ -17,7 +17,7 @@ import { useCatalog } from '../../store/catalog'
import type { Approval, Run, RunEvent } from '../../types'
import { FailedBanner, FeedbackStrip, HeldBanner, WaitingBanner, type Feedback } from './Banners'
import { localActor } from '../../lib/actor'
import { explainRunError } from '../../lib/explain'
import { explainRunError, explainStartError } from '../../lib/explain'
import { canLeave, leavePass } from '../../lib/leave'
import { UNSAVED_HINT, isUnsaved, runName } from '../../lib/terms'
import {
@@ -299,7 +299,18 @@ export function RunDetailView({ runId, onChange, onDeleted }: {
toast.ok(`已补上「${field}」重新发起运行`)
navigate({ pathname: `/runs/${next.id}`, search })
} catch (e) {
toast.error(e)
// 绑定的工具在本机不存在(422 run_tool_missing):和画布上发起被拒(run/RunControl)同一套,
// 报错里给直达入口——数据源工具去数据页,自定义 / MCP 工具去工具页
const x = explainStartError(e)
const to = x?.fixTo
if (x && to) {
toast.error(`${x.title}:${x.reason ?? ''}${x.action ?? ''}`, {
detail: x.raw, key: 'runs:run-tool-missing',
action: { label: x.fixLabel ?? '去接入', onClick: () => navigate(to) },
})
} else {
toast.error(e)
}
} finally {
setBusy(null)
}
+86 -29
View File
@@ -830,6 +830,8 @@ interface Failure {
fix?: FixKind | 'rerun'
fixTo?: string
fixFirst?: boolean
/** lib/explain 的 fixNode:该去改的是另一个节点(名字),比如整形节点失败、毛病在上游 */
fixNode?: string
}
/** 这一轮是不是一次运行。Copilot 建图、发起就失败的,不能按运行的失败去讲(「接着跑」无从谈起) */
@@ -851,7 +853,7 @@ function failureOf(turn: StreamTurn): Failure | null {
if (!hint && isRunTurn(turn)) {
const x = explainRunError(text, detail)
return { title: x.title, reason: x.reason, action: x.action, fix: x.fix, fixTo: x.fixTo, fixFirst: x.fixFirst,
raw: x.raw && x.raw !== x.title ? x.raw : undefined }
fixNode: x.fixNode, raw: x.raw && x.raw !== x.title ? x.raw : undefined }
}
const h = humanizeError(hint || detail ? { error: text, hint, detail } : text)
return { title: h.title, reason: h.reason, action: h.action, raw: h.raw && h.raw !== h.title ? h.raw : undefined }
@@ -881,9 +883,12 @@ function FixAction({ fix, nodeId, label, to, first }: {
return <Link to={to ?? '/settings/providers'} className={cls} data-fix="settings"><Settings2 size={10} aria-hidden /> 去模型接入</Link>
}
if (fix === 'tools') {
// 数据源工具(db_query__ 这类)不在工具库里接入,在数据页
const data = !!to?.startsWith('/data')
return (
<Link to={to ?? '/tools'} className={cls} data-fix="tools">
<Wrench size={10} aria-hidden /> {first ? '去改参数定义' : '去工具库'}
<Link to={to ?? '/tools'} className={cls} data-fix={data ? 'data' : 'tools'}>
{data ? <Database size={10} aria-hidden /> : <Wrench size={10} aria-hidden />}
{' '}{data ? '去数据页接入' : first ? '去改参数定义' : '去工具库'}
</Link>
)
}
@@ -904,6 +909,11 @@ function TurnError({ turn }: { turn: StreamTurn }) {
const node = findFirst(turn.steps, (s) => s.kind === 'node' && s.status === 'failed' && !!s.nodeId)
const whereId = rf?.nodeId ?? node?.nodeId
const whereLabel = rf?.sub?.replace(/^出错的节点:/, '') || node?.title
// 该改的是另一个节点(上游写坏了 JSON):入口指到它;这一轮里找不到它就不给入口,不指错
const target = f.fixNode && f.fixNode !== whereLabel
? findFirst(turn.steps, (s) => s.kind === 'node' && s.title === f.fixNode && !!s.nodeId) : null
const fixId = f.fixNode && f.fixNode !== whereLabel ? target?.nodeId : whereId
const fixLabel = f.fixNode && f.fixNode !== whereLabel ? f.fixNode : whereLabel
return (
<div role="alert" data-turn-error=""
className="mt-2 flex items-start gap-2 rounded-lg border px-3 py-2 text-xs"
@@ -930,7 +940,7 @@ function TurnError({ turn }: { turn: StreamTurn }) {
</div>
)}
<div className="flex flex-wrap items-center gap-x-2">
<FixAction fix={f.fix} nodeId={whereId} label={whereLabel} to={f.fixTo} first={f.fixFirst} />
<FixAction fix={f.fix} nodeId={fixId} label={fixLabel} to={f.fixTo} first={f.fixFirst} />
</div>
{f.raw && <div className="mt-1"><TechDetails raw={f.raw} /></div>}
</div>
@@ -1416,16 +1426,33 @@ function ExecGroups({ step, turnMs }: { step: Step; turnMs?: number }) {
)
}
/**
* 失败节点的原话是不是已经被上面的说法原样说完了:原话的每一句(按句号、分号断开,去掉标点和
* 空白比)都出现在「一句话 + 为什么 + 怎么办」里。说完了就不在展开区再贴一遍——用户真实踩到的:
* 「模板渲染出来的不是合法 JSON…」先按标题、怎么办各说一遍,底下又整段贴了一遍原话。
* 说法是改写过的(「模型鉴权没通过」之类)就还留着原话,它是唯一的原文
*/
function saidAlready(detail: string, parts: (string | undefined)[]): boolean {
const norm = (t: string) => t.replace(/[\s。..,,;;::!!??、]/g, '')
const shown = norm(parts.filter(Boolean).join(''))
const sentences = detail.split(/[。;;\n]/).map(norm).filter(Boolean)
return !!shown && sentences.length > 0 && sentences.every((x) => shown.includes(x))
}
/** 展开区:跑的是什么(SQL、代码、参数)+ 跑出了什么 + 技术细节 + 完整证据 */
function StepDetail({ step, table, explained }: {
step: Step; table: Table | null
/** 失败节点按 lib/explain 讲的为什么、怎么办 */
explained?: { reason?: string; action?: string; fix?: FixKind | 'rerun'; fixTo?: string; fixFirst?: boolean } | null
/** 失败节点按 lib/explain 讲的为什么、怎么办(title 是收着时那一行已经说了的一句话) */
explained?: {
title?: string; reason?: string; action?: string; fix?: FixKind | 'rerun'; fixTo?: string; fixFirst?: boolean; fixNode?: string
} | null
}) {
const { openArtifact, dense } = useContext(Ctx)
const pre = clsx('mono max-h-40 overflow-auto whitespace-pre-wrap rounded bg-bg px-2 py-1.5 leading-relaxed text-dim [overflow-wrap:anywhere]',
dense ? 'text-[10.5px]' : 'text-2xs')
const result = step.result
const detail = step.detail && explained && saidAlready(step.detail, [explained.title, explained.reason, explained.action])
? undefined : step.detail
return (
<div className="mb-1 mt-1 space-y-1.5 pl-[18px]">
{explained && (explained.reason || explained.action) && (
@@ -1437,13 +1464,14 @@ function StepDetail({ step, table, explained }: {
<CornerDownRight size={10} className="mt-[3px] shrink-0" aria-hidden />
<span className="min-w-0 [overflow-wrap:anywhere]">{explained.action}</span>
</span>
<FixAction fix={explained.fix} nodeId={step.nodeId} label={step.title}
to={explained.fixTo} first={explained.fixFirst} />
{/* 该改的是上游(fixNode)时这一行不给入口:它只认得自己这个节点,轮次顶上的报错会指到上游去 */}
<FixAction fix={explained.fix} nodeId={explained.fixNode && explained.fixNode !== step.title ? undefined : step.nodeId}
label={step.title} to={explained.fixTo} first={explained.fixFirst} />
</div>
)}
</div>
)}
{step.detail && (
{detail && (
<div className="group/detail relative">
{step.kind === 'query' && (
<div className="mb-0.5 flex items-center gap-2 text-2xs text-dim">
@@ -1454,7 +1482,7 @@ function StepDetail({ step, table, explained }: {
</div>
)}
<pre className={pre}>
{step.detail}
{detail}
</pre>
</div>
)}
@@ -1723,11 +1751,20 @@ function download(name: string, text: string, type: string) {
const fileSafe = (s: string) => s.replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40) || '结果'
/** 查询结果画成表格。一屏 JSON 谁也看不出名堂,表格能一眼看到形状。 */
function ResultTable({ table, artifact, title, full = false }: {
/**
* 查询结果画成表格。一屏 JSON 谁也看不出名堂,表格能一眼看到形状。
*
* 证据面板的查询步骤也用它:highlight 标出被引用的行和格(行是 table.rows 的下标),
* 加 data-highlight,颜色只用令牌;masked 列出被遮罩的列,那几列的值一律写「已遮罩」——
* 后端已经换过,这里再拦一道,老接口、别的入口回来的原值也不画出来
*/
export function ResultTable({ table, artifact, title, full = false, highlight, masked }: {
table: Table; artifact?: string; title?: string
/** 完整证据里:不截列、行数放宽 */
full?: boolean
/** cells 精确到格([行下标, 列名]):有它就只标这几格,没有就标 rows × cols */
highlight?: { rows: number[]; cols: string[]; cells?: [number, string][] | null }
masked?: string[]
}) {
const { dense, openArtifact } = useContext(Ctx)
const maxCols = full ? table.columns.length : dense ? 4 : 8
@@ -1736,6 +1773,10 @@ function ResultTable({ table, artifact, title, full = false }: {
const hiddenCols = table.columns.length - cols.length
const rows = table.rows.slice(0, maxRows)
const numeric = cols.map((c, j) => isMetricColumn(c, rows, j))
const hlCells = highlight?.cells ? new Set(highlight.cells.map(([r, c]) => `${r}\u0000${c}`)) : null
const hlRows = new Set([...(highlight?.rows ?? []), ...(highlight?.cells ?? []).map(([r]) => r)])
const hlCols = new Set(highlight?.cols ?? [])
const hidden = new Set(masked ?? [])
return (
<div className="overflow-hidden rounded border">
@@ -1751,19 +1792,30 @@ function ResultTable({ table, artifact, title, full = false }: {
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr key={i} className="border-b last:border-0">
{row.slice(0, maxCols).map((cell, j) => (
<td key={j} className={clsx('mono max-w-[160px] truncate px-1.5 py-1 text-dim',
numeric[j] && 'tnum text-right')}
title={cell == null ? '' : String(cell)}>
{cell == null ? <span className="opacity-40">null</span>
: typeof cell === 'object' ? JSON.stringify(cell) : String(cell)}
</td>
))}
{hiddenCols > 0 && <td className="px-1.5 py-1 text-dim">…</td>}
</tr>
))}
{rows.map((row, i) => {
const hit = hlRows.has(i)
return (
<tr key={i} className="border-b last:border-0" data-highlight={hit ? 'row' : undefined}
style={hit ? { background: 'var(--st-done-soft)' } : undefined}>
{row.slice(0, maxCols).map((cell, j) => {
const mark = hit && (hlCells ? hlCells.has(`${i}\u0000${cols[j]}`) : hlCols.has(cols[j]))
const mask = hidden.has(cols[j])
return (
<td key={j} className={clsx('mono max-w-[160px] truncate px-1.5 py-1',
mark ? 'font-semibold' : 'text-dim', numeric[j] && 'tnum text-right')}
data-highlight={mark ? 'cell' : undefined} data-masked={mask ? '' : undefined}
style={mark ? { outline: '1px solid var(--st-done)', outlineOffset: -1, color: 'var(--text)' } : undefined}
title={mask ? '已遮罩' : cell == null ? '' : String(cell)}>
{mask ? <span className="font-sans italic text-faint">已遮罩</span>
: cell == null ? <span className="opacity-40">null</span>
: typeof cell === 'object' ? JSON.stringify(cell) : String(cell)}
</td>
)
})}
{hiddenCols > 0 && <td className="px-1.5 py-1 text-dim">…</td>}
</tr>
)
})}
</tbody>
</table>
</div>
@@ -1792,7 +1844,9 @@ function ResultTable({ table, artifact, title, full = false }: {
<span className="flex-1" />
<button type="button" className="inline-flex items-center gap-1 rounded px-1 transition-colors hover:bg-hover hover:text-fg"
title="导出为 CSV(Excel 可直接打开)"
onClick={() => download(`${fileSafe(title ?? '查询结果')}.csv`, toCsv(table.columns, table.rows), 'text/csv;charset=utf-8')}>
onClick={() => download(`${fileSafe(title ?? '查询结果')}.csv`, toCsv(table.columns, hidden.size
? table.rows.map((r) => r.map((v, j) => (hidden.has(table.columns[j]) ? '已遮罩' : v))) : table.rows),
'text/csv;charset=utf-8')}>
<Download size={10} aria-hidden /> CSV
</button>
{artifact && !table.clipped && !full && (
@@ -1812,9 +1866,12 @@ function ResultTable({ table, artifact, title, full = false }: {
*
* 解码器早就给每一步记了工件 id,接口也一直在,界面从没渲染过——「每一步都有
* 工件、数字可回指」这个区别于普通问数工具的卖点,以前在界面上看不见。
* 导出给运行页的工件清单复用:id 为 null 时不渲染。
* 导出给运行页的工件清单复用:id 为 null 时不渲染。证据面板打开查询快照时带上 masked,
* 数据源设了遮罩的那几列同样写「已遮罩」。
*/
export function ArtifactViewer({ id, title, onClose }: { id: string | null; title?: string; onClose: () => void }) {
export function ArtifactViewer({ id, title, masked, onClose }: {
id: string | null; title?: string; masked?: string[]; onClose: () => void
}) {
const [state, setState] = useState<{ id: string; content?: unknown; error?: unknown } | null>(null)
useEffect(() => {
if (!id) return
@@ -1863,7 +1920,7 @@ export function ArtifactViewer({ id, title, onClose }: { id: string | null; titl
</pre>
</div>
)}
{body.table ? <ResultTable table={body.table} full artifact={id ?? undefined} title={title} />
{body.table ? <ResultTable table={body.table} full artifact={id ?? undefined} title={title} masked={masked} />
: (
<div>
<div className="mb-1 flex justify-end"><CopyChip label="复制全文" text={() => body.text} /></div>
+48 -6
View File
@@ -27,8 +27,9 @@ import { BlockView, Markdown, StyledSlice, inlineStyles, numericColumns, type In
* 句末挂「无证据」。
*
* 键盘:整份报告只占一个 Tab 位(roving tabindex)。←/→ 在有状态的片段间走,↑/↓ 按
* 句子走,n / N 跳到下一处 / 上一处无证据,回车打开证据面板,Esc 关掉并留在原片段;
* 面板开着时方向键走到哪、面板跟到哪,Tab 进面板。
* 句子走(表格里按列走到上一行 / 下一行,出了表格接着按句子走),n / N 跳到下一处 /
* 上一处无证据,回车打开证据面板,Esc 关掉并留在原片段;面板开着时方向键走到哪、面板
* 跟到哪,Tab 进面板。
*
* 长报告:事件都挂在容器上(片段只带 data-seg),块用 memo,外加
* content-visibility: auto;超过 TEXT_CAP 的部分先折叠,跳转到折叠里的片段时自动展开。
@@ -56,6 +57,10 @@ interface Model {
alerts: string[]
/** 每块到它为止的累计字数(折叠用) */
chars: number[]
/** 表格里的片段在第几行第几列(表头 row = -1 不进来);↑/↓ 在表格里按列走 */
cell: Map<string, { block: number; row: number; col: number }>
/** `块:行:列` → 那一格里第一个可点的片段 */
grid: Map<string, string>
}
function buildModel(blocks: EvidenceBlock[]): Model {
@@ -66,10 +71,13 @@ function buildModel(blocks: EvidenceBlock[]): Model {
const unitOf = new Map<string, number>()
const alerts: string[] = []
const chars: number[] = []
const cell = new Map<string, { block: number; row: number; col: number }>()
const grid = new Map<string, string>()
let total = 0
blocks.forEach((block, b) => {
for (const unit of block.units ?? []) {
let first = true
const loc = block.type === 'table' && unit.loc && unit.loc.row >= 0 ? unit.loc : null
for (const s of unit.segments ?? []) {
if (s.kind !== 'structural') total += s.text.length
const state = segmentState(s)
@@ -80,11 +88,47 @@ function buildModel(blocks: EvidenceBlock[]): Model {
if (first) { unitFirst.push(s.id); first = false }
unitOf.set(s.id, unitFirst.length - 1)
if (EVIDENCE_STATE[state].alert) alerts.push(s.id)
if (loc) {
cell.set(s.id, { block: b, row: loc.row, col: loc.col })
const key = `${b}:${loc.row}:${loc.col}`
if (!grid.has(key)) grid.set(key, s.id)
}
}
}
chars.push(total)
})
return { order, index, seg, unitFirst, unitOf, alerts, chars }
return { order, index, seg, unitFirst, unitOf, alerts, chars, cell, grid }
}
/**
* ↑/↓ 该去哪。表格里按列走:下一行同一列(那一格空着就找这一行离它最近的一格);
* 走出表格的上下边,接着按句子走到表格前后那一句——不在表格里一格一格地横着挪
*/
function verticalTarget(model: Model, id: string, down: boolean): string | null {
const n = model.unitFirst.length
if (!n) return null
const at = model.cell.get(id)
if (at) {
const rows = [...new Set([...model.cell.values()].filter((c) => c.block === at.block).map((c) => c.row))].sort((a, b) => a - b)
const next = rows[rows.indexOf(at.row) + (down ? 1 : -1)]
if (next !== undefined) {
const same = model.grid.get(`${at.block}:${next}:${at.col}`)
if (same) return same
const near = [...model.cell.entries()].filter(([, c]) => c.block === at.block && c.row === next)
.sort((a, b) => Math.abs(a[1].col - at.col) - Math.abs(b[1].col - at.col))[0]
if (near) return near[0]
}
// 出了表格:往下找表格之后的第一句,往上找表格之前的最后一句
const u = model.unitOf.get(id) ?? 0
const list = down ? model.unitFirst.slice(u + 1) : model.unitFirst.slice(0, u).reverse()
const out = list.find((sid) => model.seg.get(sid)?.block !== at.block)
if (out) return out
// 表格就是整份报告的首尾:和句子一样首尾相接
const wrap = down ? model.unitFirst : [...model.unitFirst].reverse()
return wrap.find((sid) => model.seg.get(sid)?.block !== at.block) ?? null
}
const u = model.unitOf.get(id) ?? 0
return model.unitFirst[(u + (down ? 1 : -1) + n) % n] ?? null
}
/** 片段的外观:线型走 data 属性(CSS 里只管线型),颜色写成两个变量交给 index.css */
@@ -246,9 +290,7 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
const to = rovingTarget(e, i, model.order.length, 'horizontal')
target = to >= 0 ? model.order[to] : null
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
const u = model.unitOf.get(id) ?? 0
const n = model.unitFirst.length
target = model.unitFirst[(u + (e.key === 'ArrowDown' ? 1 : -1) + n) % n] ?? null
target = verticalTarget(model, id, e.key === 'ArrowDown')
} else if (e.key === 'n' || e.key === 'N') {
target = step(model.alerts, id, e.shiftKey || e.key === 'N' ? -1 : 1)
if (!target) return
+295 -35
View File
@@ -1,24 +1,34 @@
import { useEffect, useMemo, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react'
import { ArrowLeft, ListChecks, X } from 'lucide-react'
import {
useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
} from 'react'
import { createPortal } from 'react-dom'
import { ArrowLeft, CornerDownRight, ListChecks, ShieldCheck, X } from 'lucide-react'
import clsx from 'clsx'
import { StatusBadge, isComposing } from '../components/ui'
import {
EVIDENCE_STATE, docForeign, graphDoc, integrityFailures, locatable, reasonOf, sealVerdict, segmentState, sourceOf,
type SealStatus,
EVIDENCE_STATE, caliberSourceText, caliberUpgradeText, docForeign, evidenceValue as valueText, graphDoc, inputSource,
integrityFailures, locatable, locatorText, notableInput, queryOf, queryWindow, reasonOf, sealVerdict, segmentState,
sourceOf, type SealStatus, type SourceTone,
} from '../lib/evidence'
import { formatNumber, NONE, shortId } from '../lib/format'
import { EVIDENCE_TEXT } from '../lib/terms'
import { useCatalog } from '../store/catalog'
import { segmentKey, useEvidence } from '../store/evidence'
import type {
EvidenceDocData, EvidenceInput, EvidenceSeal, EvidenceSegment, EvidenceStep, EvidenceUnit, EvidenceViolation,
} from '../types'
import { ArtifactViewer, ResultTable } from './AssistantStream'
import { CopyChip } from './Markdown'
/**
* 证据面板:点开报告里的一个片段,看它从哪来。
*
* 本期(数字层)展示:片段和它所在的句子;指标步骤——名称、值、口径与版本、原式、
* 代入式(每个输入是「值 ← 路径」的小标签)、复算结果;封存状态。没有证据的片段说清
* 为什么(裸数字、引用解析不了),另有一份违规清单:列表序号、代码块标签里的数字
* 展示:片段和它所在的句子;指标步骤——名称、值、口径与版本(钉在别的工作流上的写明来源
* 和升版处置)、原式、代入式(每个输入是「值 ← 路径」的小标签,点一下跳到对应的查询)、
* 复算结果;输入来源——agent 字段、cell() 取数和快照核对得上没有,代码节点的数醒目提醒;
* 查询步骤——SQL、被引用的行和格高亮的结果窗口、打开完整快照、遮罩;封存状态。没有证据
* 的片段说清为什么(裸数字、引用解析不了),另有一份违规清单:列表序号、代码块标签里的数字
* 在正文里画不了线,只能在清单里找到。
*
* 数据两层来源:文档自己记着的出处(doc.catalog,打开就有),和证据接口的证据链
@@ -104,7 +114,7 @@ export function EvidencePanel({ id, mode, doc, artifact, runId, view, onClose, o
{view.kind === 'violations'
? <ViolationList doc={doc} onLocate={onLocate} />
: found
? <SegmentBody doc={doc} artifact={artifact} runId={runId} seg={found.seg} unit={found.unit}
? <SegmentBody panelId={id} doc={doc} artifact={artifact} runId={runId} seg={found.seg} unit={found.unit}
onViolations={onViolations} />
: <p className="text-dim">{NONE}</p>}
</div>
@@ -132,16 +142,14 @@ function Part({ title, children, ...rest }: { title: string; children: ReactNode
)
}
/** 值怎么写:数带千分位、不丢小数;拿不到写「—」 */
function valueText(v: unknown): string {
if (v == null || v === '') return NONE
if (typeof v === 'number') return Number.isFinite(v) ? v.toLocaleString('en-US', { maximumFractionDigits: 20 }) : String(v)
if (typeof v === 'boolean') return v ? '是' : '否'
if (typeof v === 'object') return JSON.stringify(v)
return String(v)
/** 定位到的那一步描一下边(CSS 的 [data-flash],减少动效时由全局规则停掉) */
function flashOnce(el: HTMLElement) {
el.dataset.flash = 'focus'
setTimeout(() => { if (el.dataset.flash === 'focus') delete el.dataset.flash }, 1600)
}
function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
function SegmentBody({ panelId, doc, artifact, runId, seg, unit, onViolations }: {
panelId: string
doc: EvidenceDocData; artifact?: string; runId?: string; seg: EvidenceSegment; unit: EvidenceUnit
onViolations: () => void
}) {
@@ -172,11 +180,34 @@ function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
const state = segmentState(seg)
const cite = seg.cite
const entry = cite?.alias ? doc.catalog?.[cite.alias] : undefined
const chain: EvidenceStep[] = Array.isArray(detail?.chain) ? detail.chain : []
const chain: EvidenceStep[] = Array.isArray(detail?.chain) ? detail.chain.filter((s) => s && typeof s === 'object') : []
const metricStep = chain.find((s) => s.step === 'metric')
const inputStep = chain.find((s) => s.step === 'run_input')
const queries = chain.filter((s) => s.step === 'query')
const isMetric = cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep
const isInput = cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep
// 报告直接引用的查询单元格([[v:Q3.r5.amount]]、整表里的一格):证据链就是那一次查询
const isCell = !isMetric && !isInput && (cite?.kind === 'cell' || entry?.kind === 'query' || !!queries.length)
const inputs: EvidenceInput[] = metricStep?.inputs?.length
? metricStep.inputs
: chain.filter((s) => s.step === 'input').map((s) => s as EvidenceInput)
const masked = (Array.isArray(detail?.redacted?.columns) ? detail.redacted.columns : []).map(String).filter(Boolean)
const workflows = useCatalog((s) => s.workflows)
const workflowName = (id?: string) => (id ? workflows.find((w) => w.id === id)?.name : undefined)
// 输入标签、输入来源那一行点一下:焦点跳到对应的查询步骤,描一下边
const queryId = (i: number) => `${panelId}-q${i}`
const jumpTo = useCallback((i: number) => {
const part = document.getElementById(`${panelId}-q${i}`)
const head = part?.querySelector<HTMLElement>('[data-ev-query-head]')
if (!part || !head) return
head.focus({ preventScroll: true })
head.scrollIntoView({ block: 'nearest' })
flashOnce(part)
}, [panelId])
const linkOf = (inp: EvidenceInput) => {
const i = queryOf(inp, queries)
return i >= 0 ? { index: i, alias: queries[i].alias ?? '', go: () => jumpTo(i) } : undefined
}
const violations = (doc.violations ?? []).filter((v) => v.segment === seg.id)
const seal: EvidenceSeal | undefined = docIssue ? undefined : detail?.seal ?? graphData?.seal
const reason = reasonOf(seg) || detail?.note || ''
@@ -217,10 +248,16 @@ function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
)}
{isMetric && (
<MetricPart step={metricStep} entry={entry} chain={chain} runId={runId} seal={seal}
<MetricPart step={metricStep} entry={entry} inputs={inputs} runId={runId} seal={seal}
pending={!!runId && !docIssue && (!slot || slot.status === 'loading')}
failed={chainFailed}
resolved={state === 'deterministic'} />
resolved={state === 'deterministic'}
linkOf={linkOf}
workflowName={workflowName(pinnedWorkflow(metricStep))} />
)}
{isMetric && inputs.some(notableInput) && (
<SourcesPart inputs={inputs.filter(notableInput)} linkOf={linkOf} />
)}
{isInput && !isMetric && (
@@ -233,7 +270,20 @@ function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
</Part>
)}
{state === 'deterministic' && !isMetric && !isInput && (
{isCell && !queries.length && state === 'deterministic' && (
// 接口没给查询步骤(取不到、老后端、正在取):只说文档目录里记着的那次查询,不画假的行。
// 解析不了的单元格引用(行越界、没有这一列、受管没声明 cells)接口本来就不给链,上面已经说了原因,
// 再摆一块「这一次没取到」就像是接口出了错
<QueryFallback entry={entry} alias={cite?.alias} where={locatorText(cite?.locator)}
pending={!!runId && !docIssue && (!slot || slot.status === 'loading')}
failed={chainFailed} />
)}
{queries.map((q, i) => (
<QueryPart key={`${q.artifact ?? ''}-${i}`} id={queryId(i)} step={q} seal={seal} masked={masked} />
))}
{state === 'deterministic' && !isMetric && !isInput && !isCell && (
<p className="text-dim">{sourceOf(seg, doc) || detail?.note}</p>
)}
@@ -246,10 +296,25 @@ function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
<ListChecks size={11} aria-hidden /> {EVIDENCE_TEXT.violations}({formatNumber(doc.violations.length)})
</button>
)}
{!!masked.length && (
// 用户拍板:界面上写明遮罩不是安全边界。放在最后,读完证据再看到这句
<p className="border-t pt-2 text-2xs leading-relaxed text-faint" data-ev-mask-note="">
{EVIDENCE_TEXT.maskNote(masked)}
</p>
)}
</>
)
}
type InputLink = { index: number; alias: string; go: () => void } | undefined
/** 口径卡钉住的上游工作流 id:方案写在 caliber_from,接口给在 source 上 */
function pinnedWorkflow(step?: EvidenceStep): string | undefined {
const from = step?.caliber_from ?? (step?.source && typeof step.source === 'object' ? step.source : undefined)
return from?.workflow_id || undefined
}
/** 所在的句子:点开的那一段描底,句子里的数字加粗 */
function Sentence({ unit, active }: { unit: EvidenceUnit; active: string }) {
return (
@@ -271,11 +336,11 @@ function Sentence({ unit, active }: { unit: EvidenceUnit; active: string }) {
)
}
/** 指标步骤:名称、值、口径与版本、原式、代入式(输入标签)、复算 */
function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved }: {
/** 指标步骤:名称、值、口径与版本(来源、升版处置)、原式、代入式(输入标签)、复算 */
function MetricPart({ step, entry, inputs, runId, seal, pending, failed, resolved, linkOf, workflowName }: {
step?: EvidenceStep
entry?: Record<string, any>
chain: EvidenceStep[]
inputs: EvidenceInput[]
runId?: string
/** 封存状态:逐项复核里「在不在封存范围内」只在封存完好时单独报 */
seal?: EvidenceSeal
@@ -284,6 +349,10 @@ function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved
failed: string
/** 片段的引用解析成功了(有出处);解析不了的也画这一节,好说清缺的是哪个指标 */
resolved: boolean
/** 输入对应的查询步骤:有的话输入标签是按钮,点一下跳过去 */
linkOf: (input: EvidenceInput) => InputLink
/** 钉住的上游工作流在目录里的名字(接口没给名字时用) */
workflowName?: string
}) {
const name = step?.name ?? entry?.name ?? step?.metric ?? entry?.locator?.metric ?? NONE
const value = step?.value !== undefined ? step.value : entry?.value
@@ -291,9 +360,11 @@ function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved
const caliber = step?.caliber ?? entry?.caliber
const version = step?.version ?? entry?.version
const artifact = step?.artifact ?? entry?.artifact
const inputs: EvidenceInput[] = step?.inputs?.length
? step.inputs
: chain.filter((s) => s.step === 'input').map((s) => s as EvidenceInput)
// 钉在别的工作流上的口径卡:写明来自哪一版,上游有新版本时写处置
const pinned = step?.caliber_from ?? (step?.source && typeof step.source === 'object' ? step.source : undefined)
?? entry?.caliber_from ?? entry?.source
const from = caliberSourceText(caliber, version, typeof pinned === 'object' ? pinned : undefined, workflowName)
const upgrade = caliberUpgradeText(step?.caliber_upgrade ?? entry?.caliber_upgrade)
// 口径卡里 rendered 为「—」有两种:value 为 null 是缺输入,不为 null 是有值但按格式显示不出来
const dash = rendered === NONE || entry?.rendered === NONE
const missing = entry?.status === 'missing_input' || (value == null && (dash || !resolved))
@@ -305,12 +376,17 @@ function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved
<span className="font-medium">{name}</span>
{resolved && rendered && <span className="mono tnum text-sm" data-ev-value="">{rendered}</span>}
</div>
{(caliber || version || artifact) && (
{(caliber || version || artifact || from) && (
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-2xs text-dim">
{(caliber || version) && <span>口径卡「{caliber || NONE}」<span className="mono">{version}</span></span>}
{from
? <span data-ev-caliber-from="">{from}</span>
: (caliber || version) && <span>口径卡「{caliber || NONE}」<span className="mono">{version}</span></span>}
{artifact && <span className="mono text-faint" title={`口径卡工件 ${artifact}`}>工件 {shortId(artifact)}</span>}
</div>
)}
{upgrade && (
<p className="mt-0.5 text-2xs" style={{ color: 'var(--st-waiting)' }} data-ev-caliber-upgrade="">{upgrade}</p>
)}
<Integrity step={step} seal={seal} />
{missing && <p className="mt-1" style={{ color: 'var(--st-waiting)' }} data-ev-missing="">{EVIDENCE_TEXT.missingValue}</p>}
{unshowable && (
@@ -335,7 +411,7 @@ function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved
</code>
{!!inputs.length && (
<ul className="mt-1 flex flex-wrap gap-1" aria-label={EVIDENCE_TEXT.inputs}>
{inputs.map((inp, i) => <InputChip key={`${inp.path}-${i}`} input={inp} />)}
{inputs.map((inp, i) => <InputChip key={`${inp.path}-${i}`} input={inp} link={linkOf(inp)} />)}
</ul>
)}
</dd>
@@ -380,20 +456,204 @@ function IntegrityList({ code, items }: { code: string; items: string[] }) {
)
}
/** 「45,678.5 ← vars.kpi.gmv」:值从哪条路径取的。缺的写「—」、标成提醒色 */
function InputChip({ input }: { input: EvidenceInput }) {
/**
* 「45,678.5 ← vars.kpi.gmv」:值从哪条路径取的。缺的写「—」、标成提醒色。
* 能对到链里某一次查询的(agent 字段、cell() 取数)是按钮:点一下跳到那个查询步骤
*/
function InputChip({ input, link }: { input: EvidenceInput; link?: InputLink }) {
const missing = input.status === 'missing' || input.value == null
const from = [input.node_id && `来自节点 ${input.node_id}`, input.via && `(${input.via})`, input.role && ` · ${input.role}`]
.filter(Boolean).join('')
const style = missing ? { color: 'var(--st-waiting)', borderColor: 'var(--st-waiting)' } : { color: 'var(--text)' }
const body = <span className="truncate">{valueText(input.value)} ← {input.path ?? NONE}{missing ? '(缺)' : ''}</span>
return (
<li className="chip mono tnum max-w-full" data-ev-input={input.path ?? ''}
style={missing ? { color: 'var(--st-waiting)', borderColor: 'var(--st-waiting)' } : { color: 'var(--text)' }}
title={from || undefined}>
<span className="truncate">{valueText(input.value)} ← {input.path ?? NONE}{missing ? '(缺)' : ''}</span>
<li className="max-w-full">
{link ? (
<button type="button" className="chip mono tnum max-w-full transition-colors hover:bg-hover" style={style}
data-ev-input={input.path ?? ''} title={`${from ? `${from} · ` : ''}${EVIDENCE_TEXT.gotoQuery(link.alias)}`}
aria-label={`${valueText(input.value)} ← ${input.path ?? NONE},${EVIDENCE_TEXT.gotoQuery(link.alias)}`}
onClick={link.go}>
{body}<CornerDownRight size={9} className="shrink-0 opacity-60" aria-hidden />
</button>
) : (
<span className="chip mono tnum max-w-full" data-ev-input={input.path ?? ''} style={style} title={from || undefined}>
{body}
</span>
)}
</li>
)
}
const TONE: Record<SourceTone, { color: string; border: string; background?: string }> = {
ok: { color: 'var(--st-done)', border: 'var(--border)' },
warn: { color: 'var(--st-waiting)', border: 'var(--border)' },
// 计算角色的代码节点:沙箱里的算术绕开了口径卡,比别的提醒都醒目
alert: { color: 'var(--st-failed)', border: 'var(--st-failed)', background: 'var(--st-failed-soft)' },
muted: { color: 'var(--text-dim)', border: 'var(--border)' },
}
/**
* 输入来源:每个能核对到快照的输入(agent 字段、cell() 取数)、代码节点的输入、缺的输入各一行——
* 路径、从哪个节点哪一格来、核对结果。能对到查询步骤的给「看查询 Qn」
*/
function SourcesPart({ inputs, linkOf }: { inputs: EvidenceInput[]; linkOf: (input: EvidenceInput) => InputLink }) {
return (
<Part title={EVIDENCE_TEXT.sources} data-ev-sources="">
<ul className="space-y-1.5">
{inputs.map((inp, i) => {
const said = inputSource(inp)
const tone = TONE[said.tone]
const link = linkOf(inp)
// 查询编号写报告目录里的全局编号(接口补的 query、对上的查询步骤);agent 字段自己的 ref 是
// 那个节点内部的编号,和面板里的「查询 Qn」不是一回事,不拿来写
const alias = link?.alias || inp.query || (typeof inp.cell === 'string' ? inp.cell.split('.')[0] : '')
const where = [
inp.node_id && `节点 ${inp.node_id}`,
inp.field && (inp.via === 'agent_field' ? `字段 ${inp.field}` : inp.field),
[alias, locatorText(inp.locator)].filter(Boolean).join(' · '),
].filter(Boolean).join(' · ')
return (
<li key={`${inp.path}-${i}`} className="rounded border px-2 py-1"
style={{ borderColor: tone.border, background: tone.background }}
data-ev-source={inp.path ?? ''} data-ev-source-status={inp.status ?? ''}
data-ev-source-role={inp.via === 'code' ? inp.role || 'compute' : undefined}>
<div className="flex items-baseline gap-2">
<span className="mono min-w-0 flex-1 truncate" title={inp.path}>{inp.path ?? NONE}</span>
{link && (
<button type="button" className="btn btn-xs btn-ghost -mr-1 shrink-0" onClick={link.go} data-ev-goto="">
<CornerDownRight size={10} aria-hidden /> {EVIDENCE_TEXT.gotoQuery(link.alias)}
</button>
)}
</div>
{where && <div className="mono text-2xs text-faint [overflow-wrap:anywhere]">{where}</div>}
{said.text && <p className="mt-0.5" style={{ color: tone.color }}>{said.text}</p>}
{said.reason && <p className="mt-0.5 text-2xs text-dim">{said.reason}</p>}
</li>
)
})}
</ul>
</Part>
)
}
/**
* 查询步骤:SQL(带复制)、结果窗口(被引用的行和格高亮)、窗口说明、打开完整快照、复核。
*
* 接口只给被引用的行加前后各 2 行,窗口没盖住整份快照时写明;完整快照走工件接口(取回时
* 复验哈希),复用工件查看。被遮罩的列在表里写「已遮罩」。查询快照哈希对不上时用失败色写出来:
* 这时候这些行不能当证据,比「有出处」重要得多
*/
function QueryPart({ id, step, seal, masked }: { id: string; step: EvidenceStep; seal?: EvidenceSeal; masked: string[] }) {
const win = useMemo(() => queryWindow(step), [step])
const [open, setOpen] = useState(false)
const scroller = useRef<HTMLDivElement>(null)
const alias = step.alias ?? ''
const hidden = [...new Set([...masked, ...(Array.isArray(step.masked) ? step.masked.map(String) : [])])]
.filter((c) => win.columns.includes(c))
const bad = integrityFailures(step, seal)
// 完整快照只在这一步自己画得出行、复核也都过了时给:快照不在封存范围里(接口一行不给,工件 id 照样带着)、
// 哈希对不上时,按钮一点就绕过证据接口把整份快照打开,还挂着「哈希已校验」
const snapshot = !!step.artifact && step.sealed !== false && step.hash_ok !== false && !bad.length && win.rows.length > 0
// 知道每一行在快照里是第几行时,最前面加一列行号:窗口不连续(被引用的行隔得远)也看得出跳过了哪几行
const table = useMemo(() => (win.index
? { columns: [ROW_NO, ...win.columns], rows: win.rows.map((r, i) => [win.index![i] + 1, ...r]), truncated: false }
: { columns: win.columns, rows: win.rows, truncated: false }), [win])
// 被引用的格可能在右边几列:窄栏里表格横向滚到它,不让人以为没高亮
useLayoutEffect(() => {
const box = scroller.current
const cell = box?.querySelector<HTMLElement>('td[data-highlight="cell"]')
const inner = cell?.closest<HTMLElement>('.overflow-x-auto')
if (!cell || !inner) return
const left = cell.offsetLeft
if (left < inner.scrollLeft || left + cell.offsetWidth > inner.scrollLeft + inner.clientWidth) {
inner.scrollLeft = Math.max(0, left - 8)
}
}, [win])
return (
// 从输入标签跳过来时描一下边(flashOnce 设 data-flash):静态描边,减少动效时照样看得见
<div id={id} data-ev-query={step.artifact ?? ''} data-ev-query-alias={alias}
className="rounded data-[flash]:outline data-[flash]:outline-solid data-[flash]:outline-2 data-[flash]:outline-offset-2 data-[flash=focus]:outline-[color:var(--accent)]">
<div className="mb-1 flex items-center gap-2">
{/* 键盘跳过来时焦点落在这里:得看得见落在哪(不能 outline-none) */}
<span tabIndex={-1} data-ev-query-head=""
className="min-w-0 flex-1 truncate rounded-sm text-2xs font-medium text-faint focus:outline-none focus-visible:outline focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[color:var(--accent)]">
{EVIDENCE_TEXT.query(alias)}
{step.tool && <span className="mono ml-1.5 font-normal">{step.tool}</span>}
</span>
{step.sql && <CopyChip label={EVIDENCE_TEXT.copySql} text={() => step.sql ?? ''} />}
</div>
{step.sql && (
<pre className="mono mb-1.5 max-h-28 overflow-auto whitespace-pre-wrap rounded bg-bg px-1.5 py-1 text-2xs leading-relaxed text-dim [overflow-wrap:anywhere]"
data-ev-sql="">
{step.sql}
</pre>
)}
{bad.length > 0 && (
<IntegrityList code={bad.map((k) => (k === 'hash' ? 'query-hash' : k)).join(' ')}
items={bad.map((k) => (k === 'hash' ? EVIDENCE_TEXT.queryHash : EVIDENCE_TEXT.integrity[k]))} />
)}
{win.columns.length > 0 && win.rows.length > 0 && (
<div ref={scroller} className={clsx(bad.length > 0 && 'mt-1.5')}>
<ResultTable table={table} full title={EVIDENCE_TEXT.query(alias)}
highlight={win.marks.length || win.cells?.length ? { rows: win.marks, cols: win.cols, cells: win.cells } : undefined}
masked={hidden} />
</div>
)}
{!win.rows.length && (
// 没有行:快照不在封存范围里、哈希对不上、取不回来。接口说了原因就照原话
<p className="text-2xs text-dim" data-ev-query-note="">{step.note || EVIDENCE_TEXT.queryMissing}</p>
)}
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-2xs text-faint">
{win.windowed && win.total != null && (
<span data-ev-window="">
{EVIDENCE_TEXT.windowed}({win.span},共 {formatNumber(win.total)} 行)
</span>
)}
{step.window_truncated && <span style={{ color: 'var(--st-waiting)' }}>{EVIDENCE_TEXT.windowCut(win.rows.length)}</span>}
{step.truncated && <span style={{ color: 'var(--st-waiting)' }}>{EVIDENCE_TEXT.truncatedSnapshot}</span>}
{/* 数据源改名或删掉了:遮罩按查询当时记下的那份处理,行照样给。这句要看得见——
现在的数据源设置已经管不到这份快照了 */}
{step.mask_note && (
<span className="[overflow-wrap:anywhere]" style={{ color: 'var(--st-waiting)' }} data-ev-query-mask-note="">{step.mask_note}</span>
)}
<span className="flex-1" />
{snapshot && (
<button type="button" className="inline-flex items-center gap-1 rounded px-1 transition-colors hover:bg-hover hover:text-fg"
onClick={() => setOpen(true)} data-ev-snapshot="">
<ShieldCheck size={10} aria-hidden /> {EVIDENCE_TEXT.openSnapshot}
</button>
)}
</div>
{/* 弹窗挂到 body 上:侧边面板是 fixed 的一层,里面的遮罩盖不住整页 */}
{/* 完整快照里同样遮掉这几列:工件接口还是原值(面板底部写明了),面板自己的入口不多暴露 */}
{open && snapshot && step.artifact && createPortal(
<ArtifactViewer id={step.artifact} title={EVIDENCE_TEXT.snapshotTitle(alias)} masked={hidden} onClose={() => setOpen(false)} />,
document.body,
)}
</div>
)
}
/** 窗口表格最前面那一列:快照里的行号,从 1 数 */
const ROW_NO = '#'
/** 接口没给查询步骤时:文档目录里记着的那次查询(编号、工具、行数),并照实说行没取到 */
function QueryFallback({ entry, alias, where, pending, failed }: {
entry?: Record<string, any>; alias?: string; where: string; pending: boolean; failed: string
}) {
const rows = typeof entry?.rows === 'number' ? `${formatNumber(entry.rows)} 行` : ''
return (
<Part title={EVIDENCE_TEXT.query(alias ?? entry?.alias ?? '')} data-ev-query-missing={pending ? 'loading' : 'missing'}>
<p className="mono text-2xs text-dim [overflow-wrap:anywhere]">
{[entry?.tool ?? entry?.source, rows, where].filter(Boolean).join(' · ') || NONE}
</p>
<p className="mt-1 text-2xs text-faint">
{pending ? EVIDENCE_TEXT.queryPending : failed === EVIDENCE_TEXT.chainMissing ? EVIDENCE_TEXT.queryMissing : failed || EVIDENCE_TEXT.queryMissing}
</p>
</Part>
)
}
/**
* 封存状态:StatusBadge 的剪影 + 一句话。说什么由 lib/evidence 的 sealVerdict 定(顺序、
* 正文不是封存那份时的失败态都在那里);没有证据的片段封存的只是报告文档本身,
+23 -3
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { Link, useNavigate } from 'react-router-dom'
import { ChevronDown, Play } from 'lucide-react'
import clsx from 'clsx'
import { api } from '../api/client'
@@ -8,6 +8,7 @@ import { hintOf } from '../canvas/shortcuts'
import { isComposing, Kbd, Skeleton, Spinner, toast } from '../components/ui'
import { useLocalActor } from '../lib/actor'
import { errorMessage } from '../lib/errors'
import { explainStartError } from '../lib/explain'
import { matchShortcut } from '../lib/keys'
import { runClassLabel } from '../lib/terms'
import { useStudio, type FlowNode } from '../store/studio'
@@ -15,6 +16,23 @@ import type { ValidationIssue, WorkflowVersion } from '../types'
import { ClassDot, escapeRun, RunCapsule } from './RunHud'
import { isActivePhase } from './trace'
/**
* 发起就被拒。绑定的工具在本机不存在(run_tool_missing)时给直达入口:数据源工具去数据页接入,
* 自定义、MCP 工具去工具页——这次运行还没开始,没有「接着跑」可给。别的照通用的出错提示
*/
function startFailed(e: unknown, navigate: (to: string) => void) {
const x = explainStartError(e)
if (!x?.fixTo) {
toast.error(e)
return
}
const to = x.fixTo
toast.error(`${x.title}:${x.reason ?? ''}${x.action ?? ''}`, {
detail: x.raw, key: 'studio:run-tool-missing',
action: { label: x.fixLabel ?? '去接入', onClick: () => navigate(to) },
})
}
/**
* 工具栏上的运行控件。
*
@@ -154,13 +172,14 @@ function ExploreLauncher({ tight }: { tight: boolean }) {
const errors = issues.filter((i) => i.level === 'error')
const blocked = !!errors.length || !nodes.length
const navigate = useNavigate()
const launch = async () => {
setBusy(true)
try {
await startRun(payloadOf(fields, values))
setOpen(false)
} catch (e) {
toast.error(e)
startFailed(e, navigate)
} finally {
setBusy(false)
}
@@ -258,13 +277,14 @@ function FormalLauncher({ workflowId, version }: { workflowId: string; version:
const ahead = dirty || (canvasVersion != null && canvasVersion !== version)
const label = runClassLabel('formal', version)
const navigate = useNavigate()
const launch = async () => {
setBusy(true)
try {
await startFormalRun(payloadOf(fields ?? [], values))
setOpen(false)
} catch (e) {
toast.error(e)
startFailed(e, navigate)
} finally {
setBusy(false)
}
File diff suppressed because it is too large Load Diff
+42 -1
View File
@@ -644,6 +644,9 @@ function queryTitle(sql: string, source: string): string {
return clip(`查询 ${what}${how ? ` · ${how}` : ''}`)
}
/** agent 开了 cite_fields 时循环结束后那次结构化抽取 */
const EXTRACT_TITLE = '按出处抽取字段'
/** 审批行末尾:批的时候点了「始终允许」,这个工具之后不再问人 */
const ALWAYS_NOTE = ',并设为「始终允许 · 门控把关」'
@@ -700,6 +703,34 @@ function explainLog(code: string | undefined, message: string): Pick<Step, 'titl
sub: message.match(/没通过核对((.+?))/)?.[1],
}
}
case 'agent_field_mismatch': {
// 「有 1 个字段和查询快照对不上,已按快照取值:order_cnt 模型报 1240,快照是 1234」(llm.py _field_warnings)
const n = message.match(/有\s*(\d+)\s*个字段/)?.[1]
return {
title: `有${n ? ` ${n} 个` : ''}字段和查询快照对不上,已按快照取值`,
sub: message.match(/已按快照取值[::]\s*(.+)$/)?.[1]?.trim() || undefined,
next: '下游用的是查询快照里的值,不是模型报的。模型报的数多半是抄错、四舍五入或自己算的',
}
}
case 'agent_field_unverified': {
// 两种原话:「有 N 个字段核对不了出处,记为空值(没有兜底成 0):a(原因);b(原因)」;
// 抽取没成:「<原因>。N 个字段都记为空值(没有兜底成 0)」,原因是「结构化抽取没跑成:<调用的错>」
// 或者「抽取结果不是一个对象」(llm.py 的 failed)
const failed = message.match(/^(?:结构化抽取没跑成[::])?([\s\S]+?)。\s*(\d+)\s*个字段都记为空值/)
if (failed) {
return {
title: `按出处抽取字段没跑成,${failed[2]} 个字段记为空值(没有兜底成 0)`,
sub: failed[1].trim() || undefined,
next: '这些字段交给下游的是空值;口径卡按缺输入处理。原因解决后重跑',
}
}
const n = message.match(/有\s*(\d+)\s*个字段/)?.[1]
return {
title: `有${n ? ` ${n} 个` : ''}字段核对不了出处,记为空值(没有兜底成 0)`,
sub: message.match(/没有兜底成 0)[::]\s*(.+)$/)?.[1]?.trim() || undefined,
next: '模型说的出处在查询结果里找不到。让它先查到这些字段再交,查不到的就是空',
}
}
case 'repair_invented': {
// 「第 1 次修复作废:修复时出现了原文没有的值:total_count=0」
const values = message.match(/原文没有的值[::]\s*(.+)$/)?.[1]?.trim()
@@ -1356,9 +1387,12 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
// 一出现就成行:模型想的那几十秒里得有一行在走,而不是等 end 才冒出来。
// 团队成员和调度者的调用没有 start(它们的 end 只用来记账),不会走到这
closeLlm(nodeId, 'done', at)
// agent 开了 cite_fields:循环结束后多一次结构化抽取,按出处把字段交出来。它不是在「作答」
const extract = d.purpose === 'cite_fields'
const step: Step = {
id: `llm-${seq}`, seq, kind: 'llm', title: '思考并作答',
id: `llm-${seq}`, seq, kind: 'llm', title: extract ? EXTRACT_TITLE : '思考并作答',
status: 'running', nodeId, startedAt: at,
...(extract ? { code: 'cite_fields' } : {}),
...(d.model ? { detail: `模型:${d.model}` } : {}),
}
pendingLlm.set(nodeId ?? '_', step)
@@ -1388,6 +1422,13 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
step.ms = num(d.duration_ms)
step.meta = dur(step.ms)
if (d.model && !step.detail) step.detail = `模型:${d.model}`
if (d.purpose === 'cite_fields' && d.error) {
// 抽取没跑成:agent 的结论还在,字段记空值、接着发警告——节点不失败,这一行是提醒。
// 状态记成做完(琥珀色)而不是 failed:failed 会把这一行和「执行」那一栏的标头都画成红的
step.level = 'warn'
step.title = `${EXTRACT_TITLE}没跑成`
step.detail = [String(d.error), step.detail].filter(Boolean).join('\n')
}
pendingLlm.delete(nodeId ?? '_')
break
}
+23 -2
View File
@@ -4,7 +4,7 @@ import type { CopilotOp, FixKind, RunFinal } from '../run/decode'
import { decodeRun } from '../run/decode'
import { errorMessage, humanizeError, isNetworkError } from '../lib/errors'
import { guardReview, hasEvidence } from '../lib/evidence'
import { explainRunError } from '../lib/explain'
import { explainRunError, explainStartError } from '../lib/explain'
import { parseServerTime } from '../lib/format'
import { useCatalog } from './catalog'
import { useConversations } from './conversations'
@@ -484,6 +484,27 @@ function runFailure(error: string | null | undefined, detail?: string | null): F
const lineOf = (f: Failure) => (f.reason ? `${f.title}:${f.reason}` : f.title)
/**
* 发起运行那一下被拒(POST /runs 的 ApiError)的说明。绑定的工具在本机不存在(422 run_tool_missing)
* 按 lib/explain 讲,带上直达入口(数据源工具去数据页,自定义 / MCP 工具去工具页),和画布上
* 发起被拒(run/RunControl)同一套;这时还没有运行 id,流里的报错块不会再拿原话认一遍,
* 所以入口得在这里就记进 failure。别的照旧按一句报错拆
*/
function startFailure(e: unknown): Failure {
const x = explainStartError(e)
if (!x) return failureOf(e)
return {
title: x.title,
reason: x.reason,
hint: x.action,
detail: x.raw && x.raw !== x.title ? x.raw : undefined,
continuable: false,
...(x.fix ? { fix: x.fix } : {}),
...(x.fixTo ? { fixTo: x.fixTo } : {}),
...(e instanceof ApiError ? { source: e.message } : {}),
}
}
/** 运行记录被删了:没有断点可续,也补不回完整答案 */
const GONE: Failure = {
title: '上次没有跑完',
@@ -1437,7 +1458,7 @@ async function launch(
// 在这里不成立——这一页没有谁会替它重发
const failure: Failure = isNetworkError(e)
? { ...failureOf(e, { hint: '后端连上之后点「重跑这一轮」,搭好的工作流不用重来。' }), rerun: true }
: failureOf(e)
: startFailure(e)
patch(() => ({
phase: 'error', status: PHASE_TEXT.error, error: lineOf(failure), failure,
cancel: null, endedAt: Date.now(),
+50
View File
@@ -57,8 +57,23 @@ export function toFlow(graph: GraphSpec): { nodes: FlowNode[]; edges: Edge[] } {
}
}
/**
* 图上节点和连线以外的部分(全图默认 defaults、viewport)。画布只管节点和连线,以前 toGraph
* 只拼这两样,保存时 PATCH 整张图,defaults 被整个抹掉——其中审批默认 always 会悄悄放宽成
* 全局设置。打开工作流时记下来,toGraph 原样带回去;和 savedSig 一样只属于当前这张图
*/
let graphExtras: Pick<GraphSpec, 'defaults' | 'viewport'> = {}
const extrasOf = (graph: GraphSpec | null | undefined): Pick<GraphSpec, 'defaults' | 'viewport'> => {
const out: Pick<GraphSpec, 'defaults' | 'viewport'> = {}
if (graph?.defaults && Object.keys(graph.defaults).length) out.defaults = structuredClone(graph.defaults)
if (graph?.viewport && Object.keys(graph.viewport).length) out.viewport = structuredClone(graph.viewport)
return out
}
export function toGraph(nodes: FlowNode[], edges: Edge[]): GraphSpec {
return {
...structuredClone(graphExtras),
nodes: nodes.map((n) => ({
id: n.id,
type: n.data.nodeType,
@@ -560,6 +575,11 @@ interface StudioState {
load: (workflow: Workflow | null) => void
/** 整张换掉(自动排版)。画布锁着时不换、返回 false:调用方别再报「已换好」 */
setGraph: (graph: GraphSpec) => boolean
/**
* 发布前修复的预览落到画布上:记一步撤销(label),节点的位置和选中照旧、不重新取景——
* 改的只是几个配置项,镜头一跳人就找不到刚才在看的节点了。锁着时不落、返回 false
*/
applyFixes: (graph: GraphSpec, label: string) => boolean
onNodesChange: (changes: NodeChange[]) => void
onEdgesChange: (changes: EdgeChange[]) => void
onConnect: (conn: Connection) => void
@@ -1087,6 +1107,7 @@ export const useStudio = create<StudioState>((set, get) => ({
get().cancelCopilot?.()
dragOrigin = null
glideSeq++
graphExtras = extrasOf(workflow?.graph)
savedSig = graphSig(nodes, edges)
lastVarSignature = ''
set({
@@ -1120,6 +1141,8 @@ export const useStudio = create<StudioState>((set, get) => ({
setGraph: (graph) => {
if (locked(get)) return false
const { nodes, edges } = toFlow(graph)
// 整图替换(Copilot、导入)带了 defaults 才换;没带的不能当成「清空」
if (graph.defaults !== undefined) graphExtras = { ...graphExtras, ...extrasOf({ ...graph, viewport: undefined }) }
glideSeq++
commit(set, get, '替换整个画布')
set({ nodes, edges, selectedId: null, dirty: true, fitRequest: get().fitRequest + 1 })
@@ -1127,6 +1150,33 @@ export const useStudio = create<StudioState>((set, get) => ({
return true
},
applyFixes: (graph, label) => {
if (locked(get)) return false
const next = toFlow(graph)
// 发布前修复可能改的是全图默认(比如把 defaults.approval 从 never 改成 dangerous)。
// 后端回来的整张图总带着 defaults,照它换;viewport 留着画布自己的
if (graph.defaults !== undefined) {
const { viewport } = graphExtras
graphExtras = { ...extrasOf({ ...graph, viewport: undefined }), ...(viewport ? { viewport } : {}) }
}
const { nodes: cur, selectedId } = get()
const byId = new Map(cur.map((n) => [n.id, n]))
// 已有的节点只换名字和配置:位置、量好的尺寸、选中都留着,React Flow 不用重新量一遍
const nodes = next.nodes.map((n) => {
const old = byId.get(n.id)
return old ? { ...old, data: { ...old.data, label: n.data.label, config: n.data.config } } : n
})
glideSeq++
commit(set, get, label)
set({
nodes, edges: next.edges,
selectedId: selectedId && nodes.some((n) => n.id === selectedId) ? selectedId : null,
dirty: graphSig(nodes, next.edges) !== savedSig,
})
void get().validate()
return true
},
onNodesChange: (changes) => {
if (locked(get)) {
// 锁定期间只放行量尺寸和选中:前者是 React Flow 自己的,后者不改图
+150 -7
View File
@@ -304,6 +304,64 @@ export interface ValidationIssue {
message: string
/** 出问题的是节点配置里的哪一项:'prompt'、'tools'、'cases[1].condition'。老后端不给 */
field?: string | null
/** 机读编号(governed.agent_approval_never 这类),发布前检查按它认修复。老后端不给 */
code?: string | null
/** 这条问题对应的修复 id:publish-check 的 fixes 里同 id 的那一项。没有修复时为空 */
fix?: string | null
}
/** 发布等级:发布弹窗、问题面板的发布前检查共用 */
export type PublishLevel = 'published' | 'governed'
/**
* 发布前检查给的一项修复(POST /workflows/{id}/publish-check 的 fixes)。
* auto:答案唯一、不降低要求,预览后一键修;choice:要人拿主意,options 里挑(multiple 可多选);
* assist:结构性的,交给 Copilot 试着改,产出同样只是预览
*/
export interface PublishFix {
id: string
code: string
kind: 'auto' | 'choice' | 'assist'
node_id?: string | null
label: string
preview?: { field?: string | null; before?: unknown; after?: unknown } | null
options?: { value: unknown; label: string; hint?: string | null }[]
multiple?: boolean
/** 建议值:界面上标「建议」,仍然要人选 */
default?: unknown
}
export interface PublishCheck {
level: PublishLevel
ok: boolean
issues: ValidationIssue[]
fixes: PublishFix[]
}
/** 自动修复预览里给人看的一项改动:「节点 · 字段:原值 → 新值」 */
export interface AutofixChange {
fix_id: string
node_id?: string | null
node_title?: string | null
field?: string | null
before?: unknown
after?: unknown
label?: string | null
}
/** POST /workflows/{id}/autofix:只给预览,不改库、不发布 */
export interface AutofixResult {
/** 修复后的整张图;人确认后前端走保存接口存成草稿 */
graph: GraphSpec | null
changes: AutofixChange[]
applied: string[]
rejected: { fix_id: string; reason: string }[]
/** 修复后仍然存在的问题(带 code 和 fix) */
remaining: ValidationIssue[]
/** 交给 Copilot 的那一段:它认为要人拿主意的放进 questions,不硬改 */
assist: { ok: boolean; summary?: string; questions?: string[] } | null
/** 修复后是否已经没有 error */
ok: boolean
}
/** 单个节点在一次运行中的实时状态,驱动画布上的高亮。 */
@@ -675,23 +733,79 @@ export interface EvidenceGraph {
edges?: { from: string; to: string; rel: string }[]
}
/**
* 查询快照里的位置:单元格 {row, column};agent 的数组字段按行映射时是 {rows: [首, 尾], column | columns}
* (columns 是「字段 → 列」)。行号从 0 数
*/
export interface EvidenceLocator {
row?: number
column?: string
rows?: [number, number] | number[]
columns?: Record<string, string>
}
/** 指标的一个输入:值从哪来 */
export interface EvidenceInput {
path?: string
value?: unknown
node_id?: string
/**
* 一期:input / transform / agent / code / tool / llm …(产出节点的类型);
* 二期能追到查询快照那一格的两种:agent_field(agent 开了 cite_fields 的字段)、tool_cell(cell() 取数)
*/
via?: string
field?: string
/** 只有 code 节点有:source 取数 / compute 计算(缺省) */
role?: string
/** ok / missing */
/**
* 一期 ok / missing;agent_field、tool_cell 是核对状态:verified 与快照一致、mismatch 对不上、
* unresolved 核对不了、missing 模型照实说没查到(from 为 null)
*/
status?: string
/** agent 字段的出处,agent 节点内的编号(Q1.r0.gmv)。和报告目录的全局编号不是一回事,靠 artifact 对应 */
ref?: string | null
/** 查询快照的工件 id:跳到哪一个查询步骤按它认 */
artifact?: string
locator?: EvidenceLocator
eid?: string
/** agent_field mismatch:模型报的值(value 是快照里的) */
model_value?: unknown
/** tool_cell mismatch:快照里的值(value 是算的时候用的) */
snapshot_value?: unknown
/** unresolved 的原因(人话) */
reason?: string
/** 输入对到的查询在报告目录里的编号(Q3):接口按工件补的全局编号 */
query?: string | null
/** 输入落在哪一格,全局编号(Q3.r5.amount) */
cell?: string
}
/** 口径卡钉在另一个已发布工作流某个版本里的口径卡上 */
export interface EvidenceCaliberSource {
workflow_id?: string
workflow_version?: number | string
node_id?: string
/** 接口顺手给的工作流名;没给时前端按工作流目录找 */
workflow_name?: string
}
/** 口径卡上游有新版本时声明的处置(和子工作流的升版处置同一套) */
export interface EvidenceCaliberUpgrade {
node_id?: string
workflow_id?: string
pinned?: number
latest?: number
/** recompute / dual / incomparable */
policy?: string
policy_label?: string
}
/**
* 片段证据链的一步。本期有三种:metric(指标)、input(指标的一个输入,也可能挂在
* metric.inputs 里)、run_input(报告直接引用的运行输入)
* 片段证据链的一步:metric(指标)、input(指标的一个输入,也可能挂在 metric.inputs 里)、
* run_input(报告直接引用的运行输入)、query(查询快照:被引用的行加前后各 2 行)。
* input 步骤同时带着 EvidenceInput 的字段(via、status、model_value、ref、locator、artifact)
*/
export interface EvidenceStep {
export interface EvidenceStep extends Omit<EvidenceInput, 'status'> {
step: string
metric?: string
decimals?: number | null
@@ -720,9 +834,36 @@ export interface EvidenceStep {
recompute_ok?: boolean | null
status?: string
inputs?: EvidenceInput[]
path?: string
field?: string
via?: string
/** 口径卡钉在哪个工作流的哪一版(metric;方案第 5 节的写法,接口实际给在 source 上) */
caliber_from?: EvidenceCaliberSource | null
/** 上游有新版本时的处置(metric);没有升版是 null */
caliber_upgrade?: EvidenceCaliberUpgrade | null
// ---- query:查询快照的一个窗口 ----
tool?: string
/** query:数据源名;metric:口径卡钉住的来源 {workflow_id, workflow_version, node_id, workflow_name} */
source?: string | EvidenceCaliberSource | null
sql?: string
columns?: string[]
/** 只有被引用的行加前后各 2 行;遮罩列的值已经换成「已遮罩」 */
rows?: unknown[][]
/** rows[0] 在快照里是第几行(从 0 数) */
row_offset?: number
/** rows 里每一行在快照里是第几行:被引用的行隔得远时窗口不连续,按它认 */
row_index?: number[]
/** 快照一共几行 */
total_rows?: number | null
/** 查询撞了行数上限,库里还有更多 */
truncated?: boolean | null
/** 被引用的行太多,窗口只给了前面一截 */
window_truncated?: boolean
/** 被引用的行(快照里的行号)和列;cells 是精确到格的 [行, 列],有它就只高亮这几格 */
highlight?: { rows?: number[]; cols?: string[]; cells?: [number, string][] }
/** 这一步里被遮罩的列 */
masked?: string[]
/** 这一步为什么没有行(快照不在封存范围里、哈希对不上、取不回来) */
note?: string
/** 数据源改名或删掉了、按查询当时记下的遮罩处理时的那句说明。行照样有 */
mask_note?: string
}
/** GET /runs/{id}/evidence/segments/{sid}:点开一个片段 */
@@ -737,4 +878,6 @@ export interface EvidenceSegmentDetail {
/** 落在这个片段(或这一句、没有片段的)上的违规 */
violations?: EvidenceViolation[]
seal?: EvidenceSeal
/** 查询步骤里被遮罩的列(数据源 options.mask_columns)。遮罩只减少暴露,不是安全边界 */
redacted?: { columns?: string[] }
}