mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-21 23:02:01 +00:00
可点击证据第五期:老工作流一键升级为可追溯结构;受管问数据图的 cells 一键选;pytest 并行
一、一键升级(只给预览,不自动保存)
- engine/upgrade.py:确定性改写,纯函数、重复执行结果不变
- R1 契约的叙述指向模型调用节点 → 换成报告撰写节点(system 和 prompt 合成写作要求,模型配置照搬),契约改成 report_from
- R2 没有契约、但模型写的文字进了出口,而且上游有取数 → 同样换成报告撰写
- R3 input → 智能体 → 出口(问数据的典型图)→ 中间插入报告撰写节点,出口字段接报告的正文;
只改直接相连的出口,经过别的节点读它的出口原样保留并写明原因
- R4 配了 output_schema 的智能体 → 打开 cite_fields
- R5 代码节点的产出被口径卡读 → 不改,只建议标成取数,等人确认
- 一个叙述里混了几个写作者的,不猜,整步不做并写明原因
- POST /api/copilot/upgrade-evidence:返回改动、说明和改完的检查结果;assist 时再交给 Copilot 把纯算术的代码节点
改写成口径卡表达式,不是纯算术的保留并给警告
- 升级和发布前修复走同一道「不许降低要求」的检查,只多两个由升级点名的例外:模型调用换成报告撰写、R3 改接的那条连线;
改完不能更糟
- 校验对符合 R1–R4 的旧结构给一条建议「可以升级为可追溯结构」,不算提示、不挡发布
- Copilot 自查:报告撰写节点上游没有任何能引用数字的来源时打回
二、界面
- 问题面板的快速修复「升级为可追溯结构(预览改动)」:逐项写「节点 · 字段:原值 → 新值」,节点类型的变化写成
「模型调用 → 报告撰写」,新插的节点和改接的连线另外写明;「应用」后走现有的保存,全图默认不丢
- 画布改过、存失败、画布被锁都有明确状态;保存失败后手动存成功会清掉「没存上」的提示,
画布和预览对不上时「重试保存」不再盲存;校验接口失败时升级块照样在
- 记录页里没有逐段证据的运行给横幅「这次的报告没有逐段证据 → 升级这张图」,跳到编排页并打开升级预览
- 修掉一处旧缺陷:应用修复时只换配置、不换节点类型,模型调用换成报告撰写后存下去的还是模型调用
三、受管门禁:cells 一键选
- 图里没有口径卡、契约又没写 cells: true 的受管图,以前能过门禁、正式运行却每次失败;现在门禁拦下,
发布弹窗给两个选项:写 cells: true,或交给 Copilot 改成口径卡指标(人亲手选的不算替人打开,Copilot 自己打开照样拦)
- 「修完要更好」的复核不再把改完才冒出来、只能由人拍板的这一处算作改坏:Copilot 补上契约、把 cells 留给人问,
这一步会被采用,不再被判「冒出新的问题」作废
四、测试
- 开发依赖加上 pytest-xdist(锁文件只多了 pytest-xdist 和 execnet):全量后端测试 -n auto 约 16 秒,原来串行约 2 分钟
- 修掉并行下暴露的一处测试竞态:运行先落终态、再另一个事务封存,测试改成等封存完成再核对
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
Approval, AutofixResult, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
|
||||
EvidenceAudit, EvidenceJudgeResult, EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, PublishCheck, PublishLevel, ReviewResult, Run,
|
||||
RunEvent, RunStatus, Skill, ToolChange, ToolInfo, ToolTrust, ValidationIssue, VarIssue, Variable, Workflow,
|
||||
RunEvent, RunStatus, Skill, ToolChange, ToolInfo, ToolTrust, UpgradeResult, ValidationIssue, VarIssue, Variable, Workflow,
|
||||
WorkflowVersion,
|
||||
} from '../types'
|
||||
import { localActor } from '../lib/actor'
|
||||
@@ -786,6 +786,13 @@ export const api = {
|
||||
/** 跑完之后复核一次。干净的运行后端直接返回 verdict='ok',不调模型 */
|
||||
review: (body: { run_id: string; question: string }) =>
|
||||
post<ReviewResult>('/copilot/review', body),
|
||||
/**
|
||||
* 一键升级为可追溯结构:先按确定的规则改写(llm 换成报告撰写、问数据的图插入报告节点……),
|
||||
* assist 时再交给 Copilot 改语义层。level 是复核门禁用的发布级别(受管的图,新写出的报告节点按受管的要求配)。
|
||||
* 只给预览,不改库。老后端没有这个接口(404),调用方按「不支持」处理
|
||||
*/
|
||||
upgradeEvidence: (body: { graph: GraphSpec; assist?: boolean; level?: PublishLevel }, opts?: RequestOptions) =>
|
||||
request<UpgradeResult>('/copilot/upgrade-evidence', { method: 'POST', body: JSON.stringify(body), ...opts }),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, CheckCircle2, CornerDownRight, ListChecks, Plus, RotateCw, ShieldCheck, Trash2, Unlink, Workflow, XCircle,
|
||||
AlertTriangle, ArrowRight, Check, CheckCircle2, CornerDownRight, ListChecks, Plus, RotateCw, ShieldCheck, Sparkles,
|
||||
Trash2, Unlink, Wand2, Workflow, XCircle,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS } from './nodeDefs'
|
||||
import { problemsOf, unboundToolOf, withToolBound, type FieldRef, type Problem } from './issues'
|
||||
import {
|
||||
fixFieldLabel, fixValueLines, fixValueText, isUpgradeAdvice, problemsOf, unboundToolOf, upgradeChangeKind,
|
||||
upgradeChangesFromDiff, upgradeEdgeText, upgradeGroups, upgradeNodeText, upgradeRuleText, upgradeStepText, upgradeSummary,
|
||||
upgradeTypeText, withToolBound, type FieldRef, type NodeNameOf, type Problem,
|
||||
} from './issues'
|
||||
import { PublishPreflightPane } from './PublishDialog'
|
||||
import { humanizeError } from '../lib/errors'
|
||||
import { formatShortcut } from '../lib/keys'
|
||||
import { PUBLISH_FIX_TEXT } from '../lib/terms'
|
||||
import { PUBLISH_FIX_TEXT, UPGRADE_TEXT } from '../lib/terms'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { useEditLock, useStudio } from '../store/studio'
|
||||
import { EDIT_LOCK_TEXT, upgradeUnsaved, useEditLock, useStudio, type UpgradeFlow } from '../store/studio'
|
||||
import { Spinner, useRadioGroup } from '../components/ui'
|
||||
import type { UpgradeChange, ValidationIssue } from '../types'
|
||||
|
||||
/**
|
||||
* 问题面板:图级、节点、边上的 error 和 warning,一条一行,点一下定位。
|
||||
@@ -31,6 +38,9 @@ export function ProblemsPane({ problems, activeId, onLocate, onDeleteEdge }: {
|
||||
const [mode, setMode] = useState<'lint' | 'publish'>('lint')
|
||||
const radio = useRadioGroup(MODES, mode, setMode)
|
||||
const hasWorkflow = useStudio((s) => !!s.workflow)
|
||||
// 又开了一次升级预览(记录页的横幅跳过来、点了快速修复):它画在「校验」这一页,停在发布前检查上就看不见
|
||||
const upgradeSeq = useStudio((s) => s.upgrade?.seq)
|
||||
useEffect(() => { if (upgradeSeq != null) setMode('lint') }, [upgradeSeq])
|
||||
const errors = problems.filter((p) => p.level === 'error').length
|
||||
return (
|
||||
<>
|
||||
@@ -74,6 +84,10 @@ function LintPane({ problems, activeId, onLocate, onDeleteEdge }: {
|
||||
const analyzeNow = useStudio((s) => s.analyzeNow)
|
||||
const offline = useCatalog((s) => s.backend === 'down')
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
// 「可以升级为可追溯结构」:校验给的建议,不是问题。预览开着时建议可能已经没了(又校验过一次),预览照样留着
|
||||
const upgradeAdvice = useStudio((s) => s.advice.find(isUpgradeAdvice))
|
||||
const upgrading = useStudio((s) => !!s.upgrade)
|
||||
const upgrade = upgradeAdvice || upgrading ? <UpgradeBlock advice={upgradeAdvice} /> : null
|
||||
|
||||
// F8 跳到的那一条要在视野里
|
||||
useEffect(() => {
|
||||
@@ -86,8 +100,9 @@ function LintPane({ problems, activeId, onLocate, onDeleteEdge }: {
|
||||
// 不会有人替你再试,这时候承诺「会自动重新校验」就是在让人干等
|
||||
const retryHint = offline ? '连上后端之后会自动重新校验' : '点「重试」再校验一次'
|
||||
if (analysis === 'failed' && !problems.length) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center text-2xs">
|
||||
const failed = (
|
||||
<div className={clsx('flex flex-col items-center justify-center gap-2 px-6 text-center text-2xs', upgrade ? 'py-3' : 'flex-1')}
|
||||
data-analysis-failed="">
|
||||
<span style={{ color: 'var(--warn)' }}>分析失败{analysisError ? `:${analysisError}` : ''}</span>
|
||||
<span className="text-faint">问题清单暂时拿不到,画布照常能编辑。{retryHint}</span>
|
||||
<button type="button" className="btn btn-sm" onClick={() => void analyzeNow()}>
|
||||
@@ -95,15 +110,30 @@ function LintPane({ problems, activeId, onLocate, onDeleteEdge }: {
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
// 升级块照样摆着:后端断开时保存和校验一起失败,这时候最要紧的正是「没存上 → 重试保存」
|
||||
if (!upgrade) return failed
|
||||
return (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto py-1">
|
||||
{upgrade}
|
||||
{failed}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!problems.length) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center gap-1.5 text-2xs text-faint">
|
||||
const idle = (
|
||||
<div className={clsx('flex items-center justify-center gap-1.5 text-2xs text-faint', upgrade ? 'py-3' : 'flex-1')}>
|
||||
{analysis === 'pending'
|
||||
? <><Spinner size={11} /> 正在校验…</>
|
||||
: <><CheckCircle2 size={12} style={{ color: 'var(--ok)' }} /> 没有发现问题</>}
|
||||
</div>
|
||||
)
|
||||
if (!upgrade) return idle
|
||||
return (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto py-1">
|
||||
{upgrade}
|
||||
{idle}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const byNode = new Map(nodes.map((n) => [n.id, n]))
|
||||
@@ -150,19 +180,22 @@ function LintPane({ problems, activeId, onLocate, onDeleteEdge }: {
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div ref={list} className="min-h-0 flex-1 overflow-y-auto py-1" role="list" aria-label="问题">
|
||||
{groups.map((g) => (
|
||||
<div key={g.key} className="mb-1">
|
||||
<div className="sticky top-0 z-[1] flex items-center gap-1.5 bg-panel px-3 py-1 text-2xs font-medium">
|
||||
{g.title}
|
||||
<span className="tnum ml-auto shrink-0 text-faint">{g.items.length}</span>
|
||||
<div ref={list} className="min-h-0 flex-1 overflow-y-auto py-1">
|
||||
{upgrade}
|
||||
<div role="list" aria-label="问题">
|
||||
{groups.map((g) => (
|
||||
<div key={g.key} className="mb-1">
|
||||
<div className="sticky top-0 z-[1] flex items-center gap-1.5 bg-panel px-3 py-1 text-2xs font-medium">
|
||||
{g.title}
|
||||
<span className="tnum ml-auto shrink-0 text-faint">{g.items.length}</span>
|
||||
</div>
|
||||
{g.items.map((p) => (
|
||||
<ProblemRow key={p.id} problem={p} active={p.id === activeId}
|
||||
onLocate={() => onLocate(p)} onDeleteEdge={onDeleteEdge} />
|
||||
))}
|
||||
</div>
|
||||
{g.items.map((p) => (
|
||||
<ProblemRow key={p.id} problem={p} active={p.id === activeId}
|
||||
onLocate={() => onLocate(p)} onDeleteEdge={onDeleteEdge} />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
))}
|
||||
</div>
|
||||
<div className="px-3 pb-1 pt-0.5 text-2xs text-faint">
|
||||
{formatShortcut('F8')} 下一个 · {formatShortcut('Shift+F8')} 上一个
|
||||
</div>
|
||||
@@ -221,6 +254,367 @@ function ProblemRow({ problem: p, active, onLocate, onDeleteEdge }: {
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 一键升级为可追溯结构:校验给了建议(evidence.upgrade_available)才有入口。老后端不给这条建议,
|
||||
// 入口也就不出现。和发布前修复同一套规矩:先出预览,人点「应用」才走现有的保存存成草稿
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
const reasonOf = (e: unknown) => {
|
||||
const h = humanizeError(e)
|
||||
return h.reason ? `${h.title}:${h.reason}` : h.title
|
||||
}
|
||||
|
||||
/** 建议那一行加上预览。画布锁着(正式运行在跑、助手在改)不给入口,说清为什么 */
|
||||
function UpgradeBlock({ advice }: { advice?: ValidationIssue }) {
|
||||
const upgrade = useStudio((s) => s.upgrade)
|
||||
const previewUpgrade = useStudio((s) => s.previewUpgrade)
|
||||
const lock = useEditLock()
|
||||
// 预览出来、换了状态(算完、出错)时滚到眼前:连同上面那句建议一起,别只露出半截预览
|
||||
const ref = useRef<HTMLElement>(null)
|
||||
const seq = upgrade?.seq
|
||||
const status = upgrade?.status
|
||||
useEffect(() => {
|
||||
if (seq != null) ref.current?.scrollIntoView({ block: 'nearest' })
|
||||
}, [seq, status])
|
||||
return (
|
||||
<section ref={ref} className="mx-2 mb-1.5 mt-0.5 rounded-md border px-2.5 py-1.5 text-2xs" aria-label={UPGRADE_TEXT.advice}
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--accent) 35%, var(--border))' }} data-upgrade="">
|
||||
<div className="flex flex-wrap items-start gap-x-2 gap-y-1">
|
||||
<Sparkles size={11} className="mt-px shrink-0" style={{ color: 'var(--accent)' }} aria-hidden />
|
||||
<span className="min-w-0 flex-1 leading-snug">
|
||||
<span className="text-fg" data-upgrade-advice="">{advice?.message || UPGRADE_TEXT.advice}</span>
|
||||
{/* 后端的建议多半已经说了要改哪里、先预览;只有一句光秃秃的标题时才补这句说明 */}
|
||||
{(!advice?.message || advice.message === UPGRADE_TEXT.advice) && (
|
||||
<span className="block text-faint">{UPGRADE_TEXT.adviceHint}</span>
|
||||
)}
|
||||
</span>
|
||||
{!lock && !upgrade && (
|
||||
<button type="button" className="btn btn-xs shrink-0" data-upgrade-action="" onClick={() => void previewUpgrade()}>
|
||||
<Wand2 size={10} aria-hidden /> {UPGRADE_TEXT.action}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{lock && <div className="mt-1 text-faint" data-upgrade-locked="">{UPGRADE_TEXT.locked(EDIT_LOCK_TEXT[lock])}</div>}
|
||||
{upgrade && <UpgradePreview flow={upgrade} locked={!!lock} />}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 预览里念节点和字段要用的几样:名字、升级前后的类型、升级前的配置 */
|
||||
interface UpgradeNames {
|
||||
nameOf: NodeNameOf
|
||||
/** 升级后的类型(新插入的节点也有) */
|
||||
typeOf: (id?: string | null) => string | undefined
|
||||
/** 升级前的类型:换成报告撰写之后去掉的那几项(用户提示、角色设定)按原来的叫法念 */
|
||||
wasTypeOf: (id?: string | null) => string | undefined
|
||||
configOf: (id?: string | null) => Record<string, any> | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点 id → 名字和类型:先认画布上的,再认升级后的图里的(新插入的报告节点只在那里)。跟着 issues
|
||||
* 和预览换新,不订阅 nodes:拖一下节点这一块不必跟着重渲染
|
||||
*/
|
||||
function useUpgradeNames(flow: UpgradeFlow): UpgradeNames {
|
||||
const tick = useStudio((s) => s.issues)
|
||||
const after = flow.status === 'ready' ? flow.result.graph : null
|
||||
const map = useMemo(() => {
|
||||
const m = new Map<string, { label: string; type: string }>()
|
||||
for (const n of after?.nodes ?? []) m.set(n.id, { label: n.data?.label || n.id, type: n.type })
|
||||
// 画布上的名字优先,类型取升级后的:改的是「写报告」这个节点,字段按报告撰写的叫法念
|
||||
for (const n of useStudio.getState().nodes) {
|
||||
m.set(n.id, { label: n.data.label || n.id, type: m.get(n.id)?.type ?? n.data.nodeType })
|
||||
}
|
||||
return m
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tick, after])
|
||||
const nameOf = useCallback<NodeNameOf>((id) => map.get(id)?.label, [map])
|
||||
const typeOf = useCallback((id?: string | null) => (id ? map.get(id)?.type : undefined), [map])
|
||||
// 列表项(成果字段第几项)按改之前的配置认名字:改的正是它
|
||||
const base = flow.status === 'ready' ? flow.base : null
|
||||
const before = useCallback((id?: string | null) => (id ? base?.nodes.find((n) => n.id === id) : undefined), [base])
|
||||
const configOf = useCallback((id?: string | null) => before(id)?.data?.config, [before])
|
||||
const wasTypeOf = useCallback((id?: string | null) => before(id)?.type, [before])
|
||||
return { nameOf, typeOf, wasTypeOf, configOf }
|
||||
}
|
||||
|
||||
/** 升级预览:逐项「节点 · 字段:原值 → 新值」,节点类型的变化写成「模型调用 → 报告撰写」,说明原样列出 */
|
||||
function UpgradePreview({ flow, locked }: { flow: UpgradeFlow; locked: boolean }) {
|
||||
const dirty = useStudio((s) => s.dirty)
|
||||
const previewUpgrade = useStudio((s) => s.previewUpgrade)
|
||||
const applyUpgrade = useStudio((s) => s.applyUpgrade)
|
||||
const retryUpgradeSave = useStudio((s) => s.retryUpgradeSave)
|
||||
const discard = useStudio((s) => s.discardUpgrade)
|
||||
const names = useUpgradeNames(flow)
|
||||
const { nameOf } = names
|
||||
const T = UPGRADE_TEXT
|
||||
const P = PUBLISH_FIX_TEXT
|
||||
const box = 'mt-1.5 rounded-md border px-2.5 py-2'
|
||||
const apply = async () => {
|
||||
if (await applyUpgrade()) void useCatalog.getState().refresh()
|
||||
}
|
||||
const retrySave = async () => {
|
||||
if (await retryUpgradeSave()) void useCatalog.getState().refresh()
|
||||
}
|
||||
|
||||
if (flow.status === 'loading') {
|
||||
return (
|
||||
<div className={clsx(box, 'flex items-center gap-2')} data-upgrade-preview="loading" aria-live="polite">
|
||||
<Spinner size={11} />
|
||||
<span className="min-w-0 flex-1 text-dim">{flow.assist ? T.assisting : T.previewing}</span>
|
||||
<button type="button" className="btn btn-xs" onClick={discard}>{P.stop}</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (flow.status === 'unsupported' || flow.status === 'error') {
|
||||
return (
|
||||
<div className={clsx(box, 'flex flex-wrap items-center gap-2')} style={{ borderColor: 'var(--warn)' }}
|
||||
data-upgrade-preview={flow.status} role="alert">
|
||||
<AlertTriangle size={11} className="shrink-0" style={{ color: 'var(--warn)' }} aria-hidden />
|
||||
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]" style={{ color: 'var(--warn)' }}>
|
||||
{flow.status === 'unsupported' ? T.unsupported : `${T.failed}:${reasonOf(flow.error)}`}
|
||||
</span>
|
||||
{flow.status === 'error' && !locked && (
|
||||
<button type="button" className="btn btn-xs" onClick={() => void previewUpgrade({ assist: flow.assist })}>
|
||||
<RotateCw size={10} aria-hidden /> {P.retry}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-xs" onClick={discard}>{P.discard}</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const { result, base } = flow
|
||||
// 后端没给逐项改动时,按前后两张图自己列:照样逐项写,不替它编原因
|
||||
const changes = result.changes.length ? result.changes : result.graph ? upgradeChangesFromDiff(base, result.graph) : []
|
||||
const summary = result.graph ? upgradeSummary(base, result.graph) : []
|
||||
const left = result.issues.filter((i) => i.level === 'error').length
|
||||
const usable = !!result.graph && changes.length > 0
|
||||
// 没采用的那几步,后端往往也在说明里写了一句「……:没有采用,原因」:说明里已经有这个原因的不再列一遍
|
||||
const rejected = result.rejected.filter((r) => !result.notes.some((n) => n.text.includes(r.reason)))
|
||||
const a = flow.apply
|
||||
const saving = a?.status === 'saving'
|
||||
const unsaved = upgradeUnsaved(a)
|
||||
return (
|
||||
<section className={clsx(box, 'space-y-1.5')} style={{ borderColor: 'var(--accent)' }}
|
||||
data-upgrade-preview="ready" aria-label="升级预览">
|
||||
<div className="font-medium">{changes.length ? T.title(changes.length) : T.noChange}</div>
|
||||
{summary.length > 0 && <div className="text-faint" data-upgrade-summary="">{T.summary(summary)}</div>}
|
||||
{changes.length > 0 && (
|
||||
<div className="space-y-1.5" data-upgrade-changes="">
|
||||
{upgradeGroups(changes).map((g) => (
|
||||
<div key={g.key} data-upgrade-step={g.rule ?? ''}>
|
||||
{g.label && (
|
||||
<div className="flex items-start gap-1 text-dim [overflow-wrap:anywhere]" data-upgrade-step-label="">
|
||||
{g.rule && <RuleTag rule={g.rule} />}
|
||||
<span className="min-w-0">{g.label}</span>
|
||||
</div>
|
||||
)}
|
||||
<ul className={clsx('space-y-0.5', g.label && 'mt-0.5 border-l pl-2.5')}>
|
||||
{g.items.map((c, i) => (
|
||||
<UpgradeChangeRow key={i} change={c} names={names} showRule={!g.label} showLabel={c.label !== g.label} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{result.notes.length > 0 && (
|
||||
<div className="rounded border px-2 py-1" style={{ borderColor: 'var(--st-waiting)' }} data-upgrade-notes="">
|
||||
<div style={{ color: 'var(--st-waiting)' }}>{T.notes}</div>
|
||||
<ul className="list-disc space-y-0.5 pl-4">
|
||||
{result.notes.map((n, i) => (
|
||||
<li key={i} className="[overflow-wrap:anywhere]" data-upgrade-note={n.rule ?? ''} data-upgrade-note-level={n.level ?? 'info'}
|
||||
style={n.level === 'warning' ? { color: 'var(--warn)' } : undefined}>
|
||||
{n.node_id && !n.text.includes(`「${nameOf(n.node_id) ?? n.node_id}」`) && (
|
||||
<b className="font-semibold">「{nameOf(n.node_id) ?? n.node_id}」</b>
|
||||
)}
|
||||
<span data-upgrade-note-text="">{n.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{rejected.length > 0 && (
|
||||
<div data-upgrade-rejected="">
|
||||
<div className="text-faint">{T.rejected}</div>
|
||||
<ul className="space-y-0.5">
|
||||
{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">{upgradeStepText(r.fix_id, nameOf)}:{r.reason}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{result.assist && (result.assist.summary || !!result.assist.questions?.length || !!result.assist.warnings?.length) && (
|
||||
<div className="space-y-1" data-upgrade-assist-said="">
|
||||
{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">{P.assistSaid}:</span>{result.assist.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
{!!result.assist.warnings?.length && (
|
||||
<div data-upgrade-assist-warnings="">
|
||||
<div className="text-faint">{T.assistWarnings}</div>
|
||||
<ul className="space-y-0.5">
|
||||
{result.assist.warnings.map((w, 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">{w}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{!!result.assist.questions?.length && (
|
||||
<div className="rounded border px-2 py-1" style={{ borderColor: 'var(--st-waiting)' }} data-upgrade-questions="">
|
||||
<div style={{ color: 'var(--st-waiting)' }}>{P.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: left ? 'var(--warn)' : 'var(--ok)' }} data-upgrade-after-check="">
|
||||
{left ? T.afterLeft(left) : T.afterOk}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{a?.status === 'stale' && (
|
||||
<div role="alert" className="flex flex-wrap items-center gap-2" style={{ color: 'var(--warn)' }} data-upgrade-stale="">
|
||||
<span className="min-w-0 flex-1">{T.stale}</span>
|
||||
{!locked && (
|
||||
<button type="button" className="btn btn-xs" onClick={() => void previewUpgrade({ assist: flow.assist })}>
|
||||
<RotateCw size={10} aria-hidden /> {T.again}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{a?.status === 'locked' && !a.unsaved && <div role="alert" style={{ color: 'var(--warn)' }}>{T.locked(a.why)}</div>}
|
||||
{unsaved && (
|
||||
<div role="alert" className="flex flex-wrap items-center gap-2" data-upgrade-save-failed={a?.status === 'failed' ? '' : 'locked'}
|
||||
style={{ color: a?.status === 'failed' ? 'var(--err)' : 'var(--warn)' }}>
|
||||
<span className="min-w-0 flex-1">
|
||||
{a?.status === 'failed' ? `${P.saveFailed}:${reasonOf(a.error)}` : a?.status === 'locked' ? `${P.saveFailed}(${a.why})` : ''}。
|
||||
{T.saveFailedHint}
|
||||
</span>
|
||||
{/* 放弃只收起这份预览:画布上的升级留着(要退回就撤销),之后按平常的保存来存 */}
|
||||
<button type="button" className="btn btn-xs" onClick={discard} title={T.discardUnsavedHint} data-upgrade-discard="unsaved">
|
||||
{P.discard}
|
||||
</button>
|
||||
<button type="button" className="btn btn-xs" onClick={() => void retrySave()}>
|
||||
<RotateCw size={10} aria-hidden /> {P.retrySave}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!unsaved && (
|
||||
<div className="flex flex-wrap items-center gap-2 pt-0.5">
|
||||
<span className="min-w-0 flex-1 text-faint">
|
||||
{saving ? P.saving : locked ? '' : usable ? `${T.applyNote}${dirty ? `。${P.dirtyNote}` : ''}` : ''}
|
||||
</span>
|
||||
{!flow.assist && !locked && (
|
||||
<button type="button" className="btn btn-xs" data-upgrade-assist="" disabled={saving} title={T.assistHint}
|
||||
onClick={() => void previewUpgrade({ assist: true })}>
|
||||
<Sparkles size={10} aria-hidden /> {T.assist}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-xs" onClick={discard} disabled={saving} data-upgrade-discard="">{P.discard}</button>
|
||||
{usable && !locked && (
|
||||
<button type="button" className="btn btn-xs btn-primary" data-upgrade-apply="" disabled={saving || a?.status === 'stale'}
|
||||
onClick={() => void apply()}>
|
||||
{saving ? <Spinner size={10} /> : <Check size={10} aria-hidden />} {T.apply}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 命中的改写规则:R1–R5 或 Copilot */
|
||||
function RuleTag({ rule }: { rule: string }) {
|
||||
return <span className="mono shrink-0 rounded border px-1 text-faint" title="命中的改写规则">{upgradeRuleText(rule)}</span>
|
||||
}
|
||||
|
||||
/** 这个字段按哪种节点的叫法念:升级后的类型认得就用它,认不得(换类型时去掉的用户提示)用原来的 */
|
||||
function ownerType(field: string | null | undefined, id: string | null | undefined, names: UpgradeNames): string | undefined {
|
||||
const now = names.typeOf(id)
|
||||
const key = (field ?? '').split('.')[0].replace(/\[\d+\]$/, '')
|
||||
const has = (type?: string) => !!type && !!NODE_DEFS[type as keyof typeof NODE_DEFS]?.fields.some((f) => f.key === key)
|
||||
if (has(now)) return now
|
||||
const was = names.wasTypeOf(id)
|
||||
return has(was) ? was : now
|
||||
}
|
||||
|
||||
/** 一项改动。改接的连线、新插入的节点、换了的类型各有写法,其余和发布前修复的预览一样 */
|
||||
function UpgradeChangeRow({ change: c, names, showRule, showLabel }: {
|
||||
change: UpgradeChange; names: UpgradeNames; showRule: boolean; showLabel: boolean
|
||||
}) {
|
||||
const { nameOf } = names
|
||||
const kind = upgradeChangeKind(c)
|
||||
const T = UPGRADE_TEXT
|
||||
const where = c.node_title || (c.node_id ? nameOf(c.node_id) ?? c.node_id : '') || PUBLISH_FIX_TEXT.whole
|
||||
const arrow = <ArrowRight size={10} className="mx-1 inline align-[-1px] text-faint" aria-label="改成" />
|
||||
let body: React.ReactNode
|
||||
if (kind === 'type') {
|
||||
body = (
|
||||
<>
|
||||
<b className="font-semibold">「{where}」</b> · {T.typeField}:
|
||||
<span className="text-faint line-through" data-upgrade-before="">{upgradeTypeText(c.before)}</span>
|
||||
{arrow}
|
||||
<span className="font-medium" data-upgrade-after="">{upgradeTypeText(c.after)}</span>
|
||||
</>
|
||||
)
|
||||
} else if (kind === 'node') {
|
||||
body = <>{T.added}:<span className="font-medium" data-upgrade-after="">{upgradeNodeText(c.after)}</span></>
|
||||
} else if (kind === 'edge') {
|
||||
// 连线本身带一个箭头,改接不再用箭头图标,写「改接为」,免得两种箭头混在一行里
|
||||
const from = c.before != null ? upgradeEdgeText(c.before, nameOf) : ''
|
||||
const to = c.after != null ? upgradeEdgeText(c.after, nameOf) : ''
|
||||
body = from && to
|
||||
? <>{T.edge}:<span className="text-faint line-through" data-upgrade-before="">{from}</span>
|
||||
<span className="mx-1 text-faint">{T.rewired}</span><span className="font-medium" data-upgrade-after="">{to}</span></>
|
||||
: to ? <>{T.addedEdge}:<span className="font-medium" data-upgrade-after="">{to}</span></>
|
||||
: <>{T.removedEdge}:<span className="text-faint line-through" data-upgrade-before="">{from}</span></>
|
||||
} else {
|
||||
const field = fixFieldLabel(c.field, ownerType(c.field, c.node_id, names), names.configOf(c.node_id))
|
||||
body = (
|
||||
<>
|
||||
<b className="font-semibold">「{where}」</b>{field && ` · ${field}`}:
|
||||
<UpgradeValue value={c.before} field={c.field} nameOf={nameOf} className="text-faint line-through" data-upgrade-before="" />
|
||||
{arrow}
|
||||
<UpgradeValue value={c.after} field={c.field} nameOf={nameOf} className="font-medium" data-upgrade-after="" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<li className="leading-snug" data-upgrade-change={kind} data-upgrade-rule={c.rule ?? undefined}>
|
||||
<span className="[overflow-wrap:anywhere]">
|
||||
{showRule && c.rule && <span className="mr-1"><RuleTag rule={c.rule} /></span>}
|
||||
{body}
|
||||
</span>
|
||||
{showLabel && c.label && <span className="block text-faint">{c.label}</span>}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** 预览里的一个值:整份契约一键一行,别的压成一行;节点引用写节点名。和发布前修复的写法相同 */
|
||||
function UpgradeValue({ value, field, nameOf, className, ...data }: {
|
||||
value: unknown; field?: string | null; nameOf: NodeNameOf; className?: string
|
||||
'data-upgrade-before'?: string; 'data-upgrade-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>
|
||||
)
|
||||
}
|
||||
|
||||
const SUB_LABEL: Record<string, string> = { condition: '的条件', key: '的标识', tools: '的工具', system: '的角色设定' }
|
||||
|
||||
function fieldLabel(field: FieldRef | null | undefined, type?: string, config?: Record<string, any>): string {
|
||||
|
||||
+207
-10
@@ -11,10 +11,13 @@
|
||||
* 那一栏,定位落到工具上(见 toolBindingOf)。
|
||||
*/
|
||||
import { ApiError } from '../api/client'
|
||||
import { APPROVAL_POLICY_LABEL, JUDGE_FIELD_LABEL, JUDGE_ON_UNSUPPORTED_LABEL } from '../lib/terms'
|
||||
import { APPROVAL_POLICY_LABEL, JUDGE_FIELD_LABEL, JUDGE_ON_UNSUPPORTED_LABEL, nodeTypeLabel } from '../lib/terms'
|
||||
import { NODE_DEFS } from './nodeDefs'
|
||||
import type { FlowNode } from '../store/studio'
|
||||
import type { AutofixResult, GraphSpec, PublishCheck, PublishFix, PublishLevel, ValidationIssue } from '../types'
|
||||
import type {
|
||||
AutofixResult, GraphEdge, GraphNode, GraphSpec, PublishCheck, PublishFix, PublishLevel, UpgradeChange, UpgradeNote, UpgradeResult,
|
||||
ValidationIssue,
|
||||
} from '../types'
|
||||
|
||||
export interface FieldRef {
|
||||
/** 顶层配置键:prompt、cases、fields… 'label' 表示节点名称 */
|
||||
@@ -171,9 +174,12 @@ export function problemsOf(
|
||||
issues: ValidationIssue[], nodes: FlowNode[], rank?: Record<string, number>,
|
||||
): Problem[] {
|
||||
const byId = new Map(nodes.map((n, i) => [n.id, { n, i }]))
|
||||
const list: Problem[] = issues.map((issue, i) => {
|
||||
// info 是建议(可以升级为可追溯结构),不是问题:不进清单、不占 F8 的跳转。编号按原下标,
|
||||
// 过滤前后同一条问题的 id 不变
|
||||
const list: Problem[] = issues.flatMap((issue, i) => {
|
||||
if (issue.level === 'info') return []
|
||||
const hit = issue.node_id ? byId.get(issue.node_id) : undefined
|
||||
return {
|
||||
return [{
|
||||
id: `${issue.node_id ?? issue.edge_id ?? 'graph'}:${i}`,
|
||||
level: issue.level,
|
||||
message: issue.message,
|
||||
@@ -181,7 +187,7 @@ export function problemsOf(
|
||||
nodeId: issue.node_id ?? undefined,
|
||||
edgeId: issue.edge_id ?? undefined,
|
||||
field: hit ? fieldOfIssue(issue, hit.n) : null,
|
||||
}
|
||||
}]
|
||||
})
|
||||
const order = (p: Problem) => {
|
||||
if (p.scope !== 'node') return -1
|
||||
@@ -203,6 +209,8 @@ const asText = (v: unknown): string => (typeof v === 'string' ? v : v == null ?
|
||||
|
||||
function normalizeIssue(raw: any): ValidationIssue | null {
|
||||
if (!raw || typeof raw !== 'object' || !raw.message) return null
|
||||
// 建议(info,比如「可以升级为可追溯结构」)不会让发布被拦,也不是要修的提示:不算进「另有 N 条提示」
|
||||
if (raw.level === 'info') return null
|
||||
return {
|
||||
level: raw.level === 'error' ? 'error' : 'warning',
|
||||
message: asText(raw.message),
|
||||
@@ -353,9 +361,10 @@ const CONTRACT_KEYS: Record<string, string> = {
|
||||
const EXTRA_FIELDS: Record<string, string> = {
|
||||
workflow_version: '钉住版本', upgrade_policy: '上游发了新版本时', defaults: '全图默认',
|
||||
}
|
||||
/** 点号后面那一段的叫法:契约里的键,全图默认里的审批策略 */
|
||||
/** 点号后面那一段的叫法:契约里的键,全图默认里的审批策略,列表项里的名称、取值、表达式 */
|
||||
const SUB_KEYS: Record<string, string> = {
|
||||
...CONTRACT_KEYS, approval: '审批策略', claims: '没挂依据的结论句', on_uncited: '没挂依据时',
|
||||
name: '名称', value: '取值', expression: '表达式',
|
||||
}
|
||||
/** 契约 claims 的 on_uncited:没挂依据的结论句怎么算 */
|
||||
const ON_UNCITED_LABEL: Record<string, string> = {
|
||||
@@ -370,15 +379,24 @@ export type NodeNameOf = (id: string) => string | undefined
|
||||
|
||||
const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
|
||||
|
||||
/** 修复改的是哪个字段:顶层键用节点定义里的叫法,契约里的键另有一张表,结论句裁判(judge.*)另一张,其余原样 */
|
||||
export function fixFieldLabel(field: string | null | undefined, nodeType?: string): string {
|
||||
/**
|
||||
* 修复改的是哪个字段:顶层键用节点定义里的叫法,契约里的键另有一张表,结论句裁判(judge.*)另一张,其余原样。
|
||||
* 列表里的某一项(fields[0].value)写成「成果字段 · 「answer」 · 取值」:给了节点配置就认那一项的名字,
|
||||
* 没给写「第 1 项」
|
||||
*/
|
||||
export function fixFieldLabel(field: string | null | undefined, nodeType?: string, config?: Record<string, any>): string {
|
||||
if (!field) return ''
|
||||
const [head, ...rest] = field.split('.')
|
||||
if (head === 'label') return '节点名称'
|
||||
const at = /^([^[]+)\[(\d+)\]$/.exec(head)
|
||||
const key = at ? at[1] : head
|
||||
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
|
||||
const base = def?.fields.find((f) => f.key === key)?.label ?? EXTRA_FIELDS[key] ?? key
|
||||
const item = at ? config?.[key]?.[Number(at[2])] : undefined
|
||||
const name = item && typeof item === 'object' ? item.name ?? item.id ?? item.key : undefined
|
||||
const which = at ? [typeof name === 'string' && name ? `「${name}」` : `第 ${Number(at[2]) + 1} 项`] : []
|
||||
const sub = head === 'judge' ? JUDGE_FIELD_LABEL : SUB_KEYS
|
||||
return [base, ...rest.map((k) => sub[k] ?? k)].join(' · ')
|
||||
return [base, ...which, ...rest.map((k) => sub[k] ?? k)].join(' · ')
|
||||
}
|
||||
|
||||
/** judge 里写 null 表示不限的三项上限:预览里 null 写「不限」,不写「(空)」——没写和不限是两回事 */
|
||||
@@ -445,6 +463,10 @@ export function fixValueLines(value: unknown, field?: string | null, nameOf?: No
|
||||
return (x < 0 ? order.length : x) - (y < 0 ? order.length : y)
|
||||
}).map((k) => `${JUDGE_FIELD_LABEL[k] ?? k}:${fixValueText(value[k], `judge.${k}`, nameOf)}`)
|
||||
}
|
||||
// 成果 / 输入字段整列(一键升级把成果字段改取报告的正文):一项一行,「answer:{{ nodes.write.text }}」
|
||||
if (field === 'fields' && Array.isArray(value) && value.length && value.every((f) => isRecord(f) && 'name' in f)) {
|
||||
return value.map((f) => `${asText(f.name) || '(没名字)'}:${fixValueText(f.value)}`)
|
||||
}
|
||||
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) => {
|
||||
@@ -453,3 +475,178 @@ export function fixValueLines(value: unknown, field?: string | null, nameOf?: No
|
||||
})
|
||||
return keys.map((k) => `${CONTRACT_KEYS[k] ?? k}:${fixValueText(value[k], `contract.${k}`, nameOf)}`)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 一键升级为可追溯结构(POST /copilot/upgrade-evidence)
|
||||
//
|
||||
// 和发布前修复同一套收法:回来的东西收成确定的形状,缺字段就当没有。改动逐项给人看,
|
||||
// 另认三种自动修复里没有的:节点类型的变化、新插入的节点、改接的连线。
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** validate 给的那条建议:旧结构(符合 R1–R4 任一条),可以升级 */
|
||||
export const UPGRADE_ADVICE = 'evidence.upgrade_available'
|
||||
export const isUpgradeAdvice = (issue: Pick<ValidationIssue, 'code'>): boolean => issue.code === UPGRADE_ADVICE
|
||||
|
||||
function normalizeNote(raw: any): UpgradeNote | null {
|
||||
if (typeof raw === 'string') return raw.trim() ? { text: raw } : null
|
||||
if (!isRecord(raw)) return null
|
||||
const text = asText(raw.text ?? raw.message ?? raw.note)
|
||||
if (!text) return null
|
||||
return {
|
||||
text, node_id: typeof raw.node_id === 'string' ? raw.node_id : null,
|
||||
rule: raw.rule ? asText(raw.rule) : null, level: raw.level === 'warning' ? 'warning' : 'info',
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeUpgrade(raw: any): UpgradeResult {
|
||||
const graph = raw?.graph && typeof raw.graph === 'object' && Array.isArray(raw.graph.nodes) ? raw.graph as GraphSpec : null
|
||||
const assist = isRecord(raw?.assist)
|
||||
? {
|
||||
ok: !!raw.assist.ok, summary: asText(raw.assist.summary),
|
||||
questions: asArray(raw.assist.questions).map(asText).filter(Boolean),
|
||||
warnings: asArray(raw.assist.warnings).map(asText).filter(Boolean),
|
||||
}
|
||||
: null
|
||||
return {
|
||||
graph,
|
||||
changes: asArray<any>(raw?.changes).filter(isRecord).map((c) => ({
|
||||
fix_id: asText(c.fix_id ?? c.rule), rule: c.rule ? asText(c.rule) : null,
|
||||
node_id: typeof c.node_id === 'string' ? c.node_id : null, node_title: c.node_title ? asText(c.node_title) : null,
|
||||
field: typeof c.field === 'string' ? c.field : null, before: c.before, after: c.after, label: c.label ? asText(c.label) : null,
|
||||
})),
|
||||
notes: asArray(raw?.notes).map(normalizeNote).filter((n): n is UpgradeNote => !!n),
|
||||
issues: asArray(raw?.issues).map(normalizeIssue).filter((i): i is ValidationIssue => !!i),
|
||||
rejected: asArray<any>(raw?.rejected).filter(isRecord)
|
||||
.map((r) => ({ fix_id: asText(r.fix_id), reason: asText(r.reason) || '没说原因' })),
|
||||
assist,
|
||||
}
|
||||
}
|
||||
|
||||
const isNodeLike = (v: unknown): v is Partial<GraphNode> =>
|
||||
isRecord(v) && typeof v.type === 'string' && (typeof v.id === 'string' || isRecord(v.data))
|
||||
const isEdgeLike = (v: unknown): v is Pick<GraphEdge, 'source' | 'target'> =>
|
||||
isRecord(v) && typeof v.source === 'string' && typeof v.target === 'string'
|
||||
|
||||
/** 一项改动是哪一种:换了节点类型、新插入的节点、改接的连线,其余是改了某个配置 */
|
||||
export type UpgradeChangeKind = 'type' | 'node' | 'edge' | 'value'
|
||||
|
||||
export function upgradeChangeKind(c: UpgradeChange): UpgradeChangeKind {
|
||||
const f = c.field ?? ''
|
||||
if (f === 'type' || f === 'node_type') return 'type'
|
||||
if (f === 'node' || (!f && c.before == null && isNodeLike(c.after))) return 'node'
|
||||
if (f === 'edge' || f === 'edges' || isEdgeLike(c.after) || isEdgeLike(c.before)) return 'edge'
|
||||
return 'value'
|
||||
}
|
||||
|
||||
/** 节点类型写界面上的叫法:「模型调用」「报告撰写」;认不出的照写原码 */
|
||||
export const upgradeTypeText = (type: unknown): string => (typeof type === 'string' && type ? nodeTypeLabel(type) : '(空)')
|
||||
|
||||
/** 新插入的节点:「「写报告」(报告撰写)」。后端的节点可能是图里的形状(data.label),也可能是操作流的(label) */
|
||||
export function upgradeNodeText(node: unknown): string {
|
||||
if (!isNodeLike(node)) return fixValueText(node)
|
||||
const label = asText((node as { label?: unknown }).label) || asText(node.data?.label) || asText(node.id)
|
||||
return `「${label}」(${upgradeTypeText(node.type)})`
|
||||
}
|
||||
|
||||
/** 改写规则在界面上的叫法:R1–R5 照写,Copilot 那一段写 Copilot */
|
||||
export const upgradeRuleText = (rule?: string | null): string => (rule === 'assist' ? 'Copilot' : rule ?? '')
|
||||
|
||||
/**
|
||||
* 逐项改动按「哪一步」分组:同一步(同一个 fix_id,比如把「写周报」换成报告撰写)的几项改动放在一起,
|
||||
* 这一步的说明只写一次。后端没给 fix_id 的(前端按两张图自己列的)各自一组、没有说明
|
||||
*/
|
||||
export function upgradeGroups(changes: UpgradeChange[]): { key: string; rule: string | null; label: string | null; items: UpgradeChange[] }[] {
|
||||
const out: { key: string; rule: string | null; label: string | null; items: UpgradeChange[] }[] = []
|
||||
changes.forEach((c, i) => {
|
||||
const key = c.fix_id || `#${i}`
|
||||
const last = out[out.length - 1]
|
||||
if (last && c.fix_id && last.key === key) {
|
||||
last.items.push(c)
|
||||
return
|
||||
}
|
||||
out.push({ key, rule: c.rule ?? null, label: c.label ?? null, items: [c] })
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 没采用的那一步是谁:「R1 · 「写周报」」「Copilot」。后端的 fix_id 是「规则:节点 id」,
|
||||
* 认不出的照写
|
||||
*/
|
||||
export function upgradeStepText(fixId: string, nameOf?: NodeNameOf): string {
|
||||
if (!fixId || fixId === 'assist') return 'Copilot'
|
||||
const m = /^(R\d+):(.+)$/.exec(fixId)
|
||||
return m ? `${m[1]} · 「${nameOf?.(m[2]) ?? m[2]}」` : fixId
|
||||
}
|
||||
|
||||
/** 一条连线:「「取数」→「写报告」」。两头的节点名先在画布上找,再在升级后的图里找 */
|
||||
export function upgradeEdgeText(edge: unknown, nameOf?: NodeNameOf): string {
|
||||
if (!isEdgeLike(edge)) return fixValueText(edge)
|
||||
const name = (id: string) => `「${nameOf?.(id) ?? id}」`
|
||||
return `${name(edge.source)} → ${name(edge.target)}`
|
||||
}
|
||||
|
||||
const edgeKey = (e: Pick<GraphEdge, 'source' | 'target' | 'sourceHandle'>) => `${e.source}\u0000${e.target}\u0000${e.sourceHandle ?? ''}`
|
||||
|
||||
/**
|
||||
* 后端没给逐项改动(或者老一点的形状只给了图)时,按前后两张图自己列:新插入的节点、换了类型的节点、
|
||||
* 改了的名字和每个顶层配置、加上和去掉的连线。和后端给的一样逐项写,不替它编原因
|
||||
*/
|
||||
export function upgradeChangesFromDiff(before: GraphSpec, after: GraphSpec): UpgradeChange[] {
|
||||
const out: UpgradeChange[] = []
|
||||
const old = new Map((before.nodes ?? []).map((n) => [n.id, n]))
|
||||
for (const n of after.nodes ?? []) {
|
||||
const o = old.get(n.id)
|
||||
const title = n.data?.label ?? o?.data?.label ?? n.id
|
||||
if (!o) {
|
||||
out.push({ fix_id: '', node_id: n.id, node_title: title, field: 'node', before: null, after: n })
|
||||
continue
|
||||
}
|
||||
if (o.type !== n.type) out.push({ fix_id: '', node_id: n.id, node_title: title, field: 'type', before: o.type, after: n.type })
|
||||
if ((o.data?.label ?? '') !== (n.data?.label ?? '')) {
|
||||
out.push({ fix_id: '', node_id: n.id, node_title: title, field: 'label', before: o.data?.label, after: n.data?.label })
|
||||
}
|
||||
const a = o.data?.config ?? {}
|
||||
const b = n.data?.config ?? {}
|
||||
for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])]) {
|
||||
if (JSON.stringify(a[key]) !== JSON.stringify(b[key])) {
|
||||
out.push({ fix_id: '', node_id: n.id, node_title: title, field: key, before: a[key], after: b[key] })
|
||||
}
|
||||
}
|
||||
}
|
||||
const was = new Set((before.edges ?? []).map(edgeKey))
|
||||
const now = new Set((after.edges ?? []).map(edgeKey))
|
||||
for (const e of before.edges ?? []) {
|
||||
if (!now.has(edgeKey(e))) out.push({ fix_id: '', node_id: null, field: 'edge', before: { source: e.source, target: e.target }, after: null })
|
||||
}
|
||||
for (const e of after.edges ?? []) {
|
||||
if (!was.has(edgeKey(e))) out.push({ fix_id: '', node_id: null, field: 'edge', before: null, after: { source: e.source, target: e.target } })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 升级前后差在哪,合成一句:「新增 1 个节点、1 个节点换了类型、改了 2 个节点的配置、连线变动 2 处」 */
|
||||
export function upgradeSummary(before: GraphSpec, after: GraphSpec): string[] {
|
||||
const old = new Map((before.nodes ?? []).map((n) => [n.id, n]))
|
||||
let added = 0
|
||||
let typed = 0
|
||||
let changed = 0
|
||||
for (const n of after.nodes ?? []) {
|
||||
const o = old.get(n.id)
|
||||
if (!o) { added += 1; continue }
|
||||
if (o.type !== n.type) typed += 1
|
||||
else if ((o.data?.label ?? '') !== (n.data?.label ?? '')
|
||||
|| JSON.stringify(o.data?.config ?? {}) !== JSON.stringify(n.data?.config ?? {})) changed += 1
|
||||
}
|
||||
const removed = (before.nodes ?? []).filter((n) => !(after.nodes ?? []).some((x) => x.id === n.id)).length
|
||||
const was = new Set((before.edges ?? []).map(edgeKey))
|
||||
const now = new Set((after.edges ?? []).map(edgeKey))
|
||||
const edges = [...now].filter((k) => !was.has(k)).length + [...was].filter((k) => !now.has(k)).length
|
||||
return [
|
||||
added && `新增 ${added} 个节点`,
|
||||
typed && `${typed} 个节点换了类型`,
|
||||
changed && `改了 ${changed} 个节点的配置`,
|
||||
removed && `删掉 ${removed} 个节点`,
|
||||
edges && `连线变动 ${edges} 处`,
|
||||
].filter((x): x is string => !!x)
|
||||
}
|
||||
|
||||
@@ -636,6 +636,52 @@ export const PUBLISH_FIX_TEXT = {
|
||||
whole: '整张工作流',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* 一键升级为可追溯结构(问题面板的快速修复、记录页的横幅)。和发布前修复同一套规矩:
|
||||
* 只出预览,人点「应用」才走现有的保存存成草稿;不发布
|
||||
*/
|
||||
export const UPGRADE_TEXT = {
|
||||
advice: '可以升级为可追溯结构',
|
||||
adviceHint: '报告会改由「报告撰写」节点来写,每个数字、表名都能点开看出处。先看预览,确认了才改',
|
||||
action: '升级为可追溯结构(预览改动)',
|
||||
previewing: '正在算升级要改哪些地方…',
|
||||
assisting: 'Copilot 正在改语义层,可能要几十秒…',
|
||||
title: (n: number) => `升级预览 · ${n} 处改动`,
|
||||
noChange: '这张工作流没有需要升级的地方',
|
||||
summary: (parts: string[]) => `合计:${parts.join('、')}`,
|
||||
added: '新增节点',
|
||||
edge: '连线',
|
||||
rewired: '改接为',
|
||||
addedEdge: '新连线',
|
||||
removedEdge: '去掉的连线',
|
||||
typeField: '节点类型',
|
||||
notes: '需要你确认的',
|
||||
assist: '再交给 Copilot 改语义层',
|
||||
assistHint: '把只做加减乘除的代码节点改写成口径卡的表达式;不是纯算术的保留原样并给出警告。它改的同样只是预览;会调用模型,可能要几十秒',
|
||||
assistWarnings: '保留没改的',
|
||||
rejected: '没有采用',
|
||||
afterOk: '升级后校验和门禁都没有新的错误',
|
||||
afterLeft: (n: number) => `升级后还有 ${n} 处错误,应用之后在问题面板里接着改`,
|
||||
apply: '应用并保存',
|
||||
applyNote: '应用后存成新的草稿版本;不会发布,正式运行要重新发布之后才用上',
|
||||
saveFailedHint: '升级已经放到画布上(可以撤销),还没存进草稿',
|
||||
discardUnsavedHint: '只收起这份预览:已经放到画布上的升级留着,要退回就撤销;之后按平常的保存来存',
|
||||
stale: '预览之后画布又改过了,这份预览对不上了:按现在的画布重新预览一次',
|
||||
again: '重新预览',
|
||||
applied: (version?: number) => `已升级为可追溯结构${version != null ? `,存为草稿 v${version}` : ''}`,
|
||||
appliedDraft: '已升级为可追溯结构:画布还没存成工作流,保存之后才算数',
|
||||
saveNote: '升级为可追溯结构',
|
||||
undoLabel: '升级为可追溯结构',
|
||||
unsupported: '这个后端还不支持一键升级:打开助手描述一遍,或者照提示手动改',
|
||||
failed: '升级预览没算出来',
|
||||
locked: (why: string) => `${why}。现在不能升级`,
|
||||
runBanner: '这次的报告没有逐段证据',
|
||||
runAction: '升级这张图',
|
||||
runHint: '打开编排页,先看升级要改哪些地方;确认了才改,改的是草稿',
|
||||
runFormal: '正式运行跑的是已发布的版本:升级之后要重新发布,下一次正式运行才用得上',
|
||||
runLocked: (why: string) => `${why}。现在不能升级这张图`,
|
||||
} as const
|
||||
|
||||
/** 证据的种类怎么叫:aria-label、面板标题、出处那一句 */
|
||||
export const EVIDENCE_KIND_LABEL: Record<string, string> = {
|
||||
metric: '口径卡指标',
|
||||
|
||||
@@ -88,7 +88,7 @@ const PHASE_TEXT: Record<string, string> = {
|
||||
|
||||
export function StudioPage() {
|
||||
const { workflowId } = useParams()
|
||||
const [params] = useSearchParams()
|
||||
const [params, setParams] = useSearchParams()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
// 逐个取:整个 catalog 订阅下来,连接心跳、待审批轮询每跳一次整页(连同检查器里每个字段)都要重渲染
|
||||
@@ -276,6 +276,25 @@ export function StudioPage() {
|
||||
})()
|
||||
}, [workflow, workflowId, runParam, focusParam, attachRun, focusNode])
|
||||
|
||||
// ?upgrade=1:记录页「这次的报告没有逐段证据 → 升级这张图」跳过来的。图打开之后打开问题面板、
|
||||
// 要一份升级预览(只读,要人点应用才存)。读完就摘掉:留着的话刷新、后退回来都会再要一次,
|
||||
// 应用过之后再要,回来的是「没有需要升级的地方」。画布锁着(正式运行在跑、助手在改)不要,说清为什么
|
||||
const upgradeParam = params.get('upgrade')
|
||||
const upgraded = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (!upgradeParam || !workflow || workflow.id !== workflowId) return
|
||||
// 同一次跳转只要一次(开发模式下 effect 会被连跑两遍,摘参数的那次替换还没落地)
|
||||
if (upgraded.current === location.key) return
|
||||
upgraded.current = location.key
|
||||
setParams((prev) => {
|
||||
const next = new URLSearchParams(prev)
|
||||
next.delete('upgrade')
|
||||
return next
|
||||
}, { replace: true })
|
||||
setDock('problems')
|
||||
void useStudio.getState().previewUpgrade()
|
||||
}, [upgradeParam, workflow, workflowId, setParams, location.key])
|
||||
|
||||
// 开始跑图或生成时,属性面板让开——不然进展发生在一块被盖住的地方。
|
||||
// (选中节点即滑出属性面板,取消选中即收起,不再需要手动切 tab)
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
import {
|
||||
useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent,
|
||||
} from 'react'
|
||||
import { ChevronRight, Download, FileText } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ArrowRight, ChevronRight, Download, FileText, Sparkles } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { ApiError, api } from '../../api/client'
|
||||
import { isUpgradeAdvice } from '../../canvas/issues'
|
||||
import { ErrorState, Skeleton, Spinner, StatusBadge, rovingTarget, toast, useRadioGroup } from '../../components/ui'
|
||||
import {
|
||||
EVIDENCE_STATE, PROBLEM_GROUPS, auditCsv, auditFromApi, auditRows, groupRows, guessRows, guessesOf, issuanceMarks,
|
||||
segmentState, type AuditFilter, type AuditGroup, type AuditRow,
|
||||
} from '../../lib/evidence'
|
||||
import { formatNumber } from '../../lib/format'
|
||||
import { EVIDENCE_AUDIT_TEXT as T } from '../../lib/terms'
|
||||
import { EVIDENCE_AUDIT_TEXT as T, UPGRADE_TEXT } from '../../lib/terms'
|
||||
import { EvidenceDoc, type EvidenceDocHandle } from '../../run/EvidenceDoc'
|
||||
import { EvidenceGuessView } from '../../run/EvidenceGuess'
|
||||
import { Markdown, inlineStyles } from '../../run/Markdown'
|
||||
import { useEvidence } from '../../store/evidence'
|
||||
import type { EvidenceAudit, EvidenceDocData, EvidenceGraph, Run } from '../../types'
|
||||
import { useCatalog } from '../../store/catalog'
|
||||
import { EDIT_LOCK_TEXT, editLockOf, useStudio } from '../../store/studio'
|
||||
import type { EvidenceAudit, EvidenceDocData, EvidenceGraph, GraphSpec, Run } from '../../types'
|
||||
|
||||
/**
|
||||
* 记录页的「证据」页签(方案 6.4):左边报告,右边常驻的证据面板,报告下面是整张审计表。
|
||||
@@ -129,6 +133,7 @@ export function EvidencePane({ run, output, labelOf, refreshKey }: {
|
||||
<div className="space-y-4 px-4 py-3">
|
||||
<SummaryBar mode={mode} seal={seal} message={audit.data?.seal?.message}
|
||||
reports={graph.reports ?? []} labelOf={labelOf} />
|
||||
<UpgradeBanner run={run} mode={mode} />
|
||||
|
||||
{mode === 'cited' && reports.map((r) => {
|
||||
const doc = docOf(r.node_id)
|
||||
@@ -183,6 +188,72 @@ export function EvidencePane({ run, output, labelOf, refreshKey }: {
|
||||
)
|
||||
}
|
||||
|
||||
/** 已经收尾的运行:还在跑、停在审批上的,报告可能还没写,说「这次的报告没有逐段证据」太早 */
|
||||
const SETTLED = new Set(['succeeded', 'failed', 'cancelled'])
|
||||
|
||||
/**
|
||||
* 工作流现在的图能不能一键升级:拿它去校验,看有没有 evidence.upgrade_available 这条建议。老后端不给
|
||||
* 这条建议,横幅也就不出现(它也没有升级接口)。按工作流 id 和版本记住答案:同一张图的几条运行不重复问;
|
||||
* 问失败了不记,下次打开再问
|
||||
*/
|
||||
const upgradable = new Map<string, Promise<boolean>>()
|
||||
function useUpgradable(workflowId: string | null, version: number | undefined, graph: GraphSpec | undefined, enabled: boolean) {
|
||||
const [yes, setYes] = useState(false)
|
||||
useEffect(() => {
|
||||
setYes(false)
|
||||
if (!enabled || !workflowId || !graph?.nodes?.length) return
|
||||
let alive = true
|
||||
const key = `${workflowId}@${version ?? ''}`
|
||||
let ask = upgradable.get(key)
|
||||
if (!ask) {
|
||||
ask = api.workflows.validate(graph).then((r) => (r.issues ?? []).some(isUpgradeAdvice))
|
||||
ask.catch(() => { if (upgradable.get(key) === ask) upgradable.delete(key) })
|
||||
upgradable.set(key, ask)
|
||||
}
|
||||
ask.then((v) => { if (alive) setYes(v) }, () => undefined)
|
||||
return () => { alive = false }
|
||||
// graph 跟着版本走:同一个版本的图不会变
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [workflowId, version, enabled])
|
||||
return yes
|
||||
}
|
||||
|
||||
/**
|
||||
* 没有逐段证据的运行(none、旧版出具、没有契约的旧运行):工作流现在的图可以升级的,给一条横幅,
|
||||
* 跳到编排页打开升级预览。画布正锁着这张工作流(正式运行在跑、助手在改)时不给入口,说清为什么
|
||||
*/
|
||||
function UpgradeBanner({ run, mode }: { run: Run; mode?: string }) {
|
||||
const wf = useCatalog((s) => (run.workflow_id ? s.workflows.find((w) => w.id === run.workflow_id) : undefined))
|
||||
const legacy = mode === 'none' || !!mode?.startsWith('legacy')
|
||||
const yes = useUpgradable(wf?.id ?? null, wf?.version, wf?.graph, legacy && SETTLED.has(run.status))
|
||||
const lock = useStudio((s) => (wf && s.workflow?.id === wf.id ? editLockOf(s) : null))
|
||||
if (!yes || !wf) return null
|
||||
return (
|
||||
<section className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-lg border px-3 py-2" data-upgrade-banner=""
|
||||
aria-label={UPGRADE_TEXT.runBanner}
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--accent) 35%, var(--border))',
|
||||
background: 'color-mix(in srgb, var(--accent) 5%, var(--bg-panel))' }}>
|
||||
<Sparkles size={13} className="shrink-0" style={{ color: 'var(--accent)' }} aria-hidden />
|
||||
<span className="min-w-0 flex-1 text-xs">
|
||||
<span className="font-medium text-fg">{UPGRADE_TEXT.runBanner}</span>
|
||||
<span className="mt-0.5 block text-2xs leading-relaxed text-faint">
|
||||
{UPGRADE_TEXT.runHint}{run.run_class === 'formal' ? `。${UPGRADE_TEXT.runFormal}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
{lock ? (
|
||||
<span className="text-2xs" style={{ color: 'var(--st-waiting)' }} data-upgrade-banner-locked="">
|
||||
{UPGRADE_TEXT.runLocked(EDIT_LOCK_TEXT[lock])}
|
||||
</span>
|
||||
) : (
|
||||
<Link className="btn btn-sm shrink-0" to={`/studio/${encodeURIComponent(wf.id)}?upgrade=1`} data-upgrade-link=""
|
||||
title={UPGRADE_TEXT.runHint}>
|
||||
<ArrowRight size={11} aria-hidden /> {UPGRADE_TEXT.runAction}
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 详情栏宽到能放下右栏吗:按容器量,不按屏幕(左边还有运行列表) */
|
||||
function useWide(el: HTMLElement | null, min: number): boolean {
|
||||
const [wide, setWide] = useState(true)
|
||||
|
||||
@@ -5,10 +5,12 @@ import {
|
||||
} from '@xyflow/react'
|
||||
import { api, streamCopilot, streamRun } from '../api/client'
|
||||
import { copilotReceipt, mergeNodeConfig, toolChangesOf } from '../canvas/copilotMerge'
|
||||
import { contentSig, isMissingEndpoint, normalizeUpgrade } from '../canvas/issues'
|
||||
import { NODE_DEFS, sourceHandles } from '../canvas/nodeDefs'
|
||||
import { toast } from '../components/ui'
|
||||
import { humanizeError } from '../lib/errors'
|
||||
import { formatShortcut } from '../lib/keys'
|
||||
import { UPGRADE_TEXT } from '../lib/terms'
|
||||
import type { CopilotOp } from '../run/decode'
|
||||
import { endingOf, reduceTeam, settleTeam } from '../run/decode'
|
||||
import { activeEdgesOf, applyDerived } from '../run/derive'
|
||||
@@ -18,7 +20,7 @@ import {
|
||||
} from '../run/trace'
|
||||
import type {
|
||||
ConversationTurn, CopilotCheckEntry, CopilotCheckIssue, CopilotCheckOp, GraphEdge, GraphSpec, NodeRuntime, NodeType, Run,
|
||||
RunEvent, ToolChange, ValidationIssue, VarIssue, Variable, Workflow,
|
||||
RunEvent, ToolChange, UpgradeResult, ValidationIssue, VarIssue, Variable, Workflow,
|
||||
} from '../types'
|
||||
|
||||
export type FlowNode = Node<{ nodeType: NodeType; label: string; config: Record<string, any> }>
|
||||
@@ -210,6 +212,30 @@ export const EDIT_LOCK_TEXT: Record<Exclude<EditLock, null>, string> = {
|
||||
/** 组件里订阅锁:只在锁的原因变了时重渲染 */
|
||||
export const useEditLock = (): EditLock => useStudio(editLockOf)
|
||||
|
||||
/**
|
||||
* 一键升级为可追溯结构:预览摆着之后「应用」的那一段。saving 存草稿中;stale 预览之后画布又改过;
|
||||
* locked 画布锁着没落下去(unsaved:已经落到画布上、要存时锁着);failed 落到画布上了、没存上
|
||||
*/
|
||||
export type UpgradeApply =
|
||||
| { status: 'saving' | 'stale' }
|
||||
| { status: 'locked'; why: string; unsaved?: boolean }
|
||||
| { status: 'failed'; error: unknown }
|
||||
|
||||
/** 升级已经落到画布上、没存上:存失败,或者要存时画布锁着。面板给「重试保存」「放弃」,平常的保存存上了就清掉 */
|
||||
export function upgradeUnsaved(a: UpgradeApply | undefined): boolean {
|
||||
return a?.status === 'failed' || (a?.status === 'locked' && !!a.unsaved)
|
||||
}
|
||||
|
||||
/**
|
||||
* 升级预览的状态。seq 是第几次请求:面板据此认出「又开了一次预览」(切回校验页、滚到眼前)。
|
||||
* base 是发请求那一刻的图(后端没给逐项改动时按它和升级后的图自己列),sig 是它的内容签名
|
||||
*/
|
||||
export type UpgradeFlow =
|
||||
| { status: 'loading'; assist: boolean; seq: number }
|
||||
| { status: 'ready'; assist: boolean; seq: number; result: UpgradeResult; sig: string; base: GraphSpec; apply?: UpgradeApply }
|
||||
| { status: 'error'; assist: boolean; seq: number; error: unknown }
|
||||
| { status: 'unsupported'; assist: boolean; seq: number }
|
||||
|
||||
/** 两张图差在哪。只看节点的名字和配置,挪位置不算改动 */
|
||||
export interface GraphDiff {
|
||||
added: string[]
|
||||
@@ -480,7 +506,15 @@ interface StudioState {
|
||||
edges: Edge[]
|
||||
selectedId: string | null
|
||||
dirty: boolean
|
||||
/** 校验出来的 error / warning。info 级的建议不在这里,在 advice */
|
||||
issues: ValidationIssue[]
|
||||
/**
|
||||
* 校验给的建议(info 级,比如 evidence.upgrade_available「可以升级为可追溯结构」)。它们不是问题:
|
||||
* 不点亮节点卡、不算进工具栏的计数,只在问题面板里给一个快速修复
|
||||
*/
|
||||
advice: ValidationIssue[]
|
||||
/** 一键升级的预览和应用。换图时清掉 */
|
||||
upgrade: UpgradeFlow | null
|
||||
/** 这张图里有哪些变量:谁产出、谁引用。结构不变就不重新请求 */
|
||||
variables: Variable[]
|
||||
/** 变量层面的提示(含"产出了没人用"这类 info,不进 issues) */
|
||||
@@ -580,6 +614,19 @@ interface StudioState {
|
||||
* 改的只是几个配置项,镜头一跳人就找不到刚才在看的节点了。锁着时不落、返回 false
|
||||
*/
|
||||
applyFixes: (graph: GraphSpec, label: string) => boolean
|
||||
/**
|
||||
* 一键升级:拿画布上此刻的图(连同全图默认)去要一份预览,只读。画布锁着时不要、说清为什么。
|
||||
* assist 时后端再交给 Copilot 改语义层
|
||||
*/
|
||||
previewUpgrade: (opts?: { assist?: boolean }) => Promise<void>
|
||||
/**
|
||||
* 应用预览:预览之后画布没改过才落(applyFixes,记一步撤销、全图默认照带),再走现有的保存存成草稿。
|
||||
* 返回存上了没有
|
||||
*/
|
||||
applyUpgrade: () => Promise<boolean>
|
||||
/** 升级已经落到画布上、没存上(存失败、或者要存时画布锁着):再存一次 */
|
||||
retryUpgradeSave: () => Promise<boolean>
|
||||
discardUpgrade: () => void
|
||||
onNodesChange: (changes: NodeChange[]) => void
|
||||
onEdgesChange: (changes: EdgeChange[]) => void
|
||||
onConnect: (conn: Connection) => void
|
||||
@@ -879,7 +926,7 @@ async function runAnalysis(
|
||||
): Promise<void> {
|
||||
const { nodes, edges } = get()
|
||||
if (!nodes.length) {
|
||||
set({ issues: [], variables: [], varIssues: [], analysis: 'ok', analysisError: null })
|
||||
set({ issues: [], advice: [], variables: [], varIssues: [], analysis: 'ok', analysisError: null })
|
||||
return
|
||||
}
|
||||
const epoch = ++analyzeEpoch
|
||||
@@ -895,7 +942,12 @@ async function runAnalysis(
|
||||
// 图在请求飞行期间又改了,这份结果已经不对应眼前的图——丢掉,
|
||||
// 别用旧答案覆盖新答案(校验结果闪回是最难查的那种 UI bug)
|
||||
if (epoch !== analyzeEpoch) return
|
||||
set({ issues: validation.issues ?? [], analysis: 'ok', analysisError: null })
|
||||
// 建议(info)另放:节点卡、检查器、运行按钮只认 error / warning,混进来会被当成提示点亮
|
||||
const all = validation.issues ?? []
|
||||
set({
|
||||
issues: all.filter((i) => i.level !== 'info'), advice: all.filter((i) => i.level === 'info'),
|
||||
analysis: 'ok', analysisError: null,
|
||||
})
|
||||
if (vars) {
|
||||
lastVarSignature = signature
|
||||
set({ variables: vars.variables ?? [], varIssues: vars.issues ?? [] })
|
||||
@@ -954,6 +1006,42 @@ function afterJump(set: SetFn, get: () => StudioState, nodes: FlowNode[], edges:
|
||||
void get().validate()
|
||||
}
|
||||
|
||||
/** 在途的升级预览请求:换图、放弃、再开一次时掐掉 */
|
||||
let upgradeCtl: AbortController | null = null
|
||||
let upgradeSeq = 0
|
||||
|
||||
/**
|
||||
* 升级已经落到画布上,存草稿。和页面自己的保存同一套规矩:画布锁着(助手在改、正式运行在跑)不存;
|
||||
* 恢复旧版本留下的「回滚到 vN」不能被这一句盖掉,两句接着写
|
||||
*/
|
||||
async function saveUpgrade(set: SetFn, get: () => StudioState): Promise<boolean> {
|
||||
const u = get().upgrade
|
||||
if (u?.status !== 'ready') return false
|
||||
const lock = editLockOf(get())
|
||||
if (lock) {
|
||||
set({ upgrade: { ...u, apply: { status: 'locked', why: EDIT_LOCK_TEXT[lock], unsaved: true } } })
|
||||
return false
|
||||
}
|
||||
// 还没存成工作流的画布(问数据页「在画布里打开」的草稿)没有地方存:落到画布上就算完,照实说还没保存
|
||||
if (!get().workflow) {
|
||||
set({ upgrade: null })
|
||||
toast.info(UPGRADE_TEXT.appliedDraft, { key: 'studio:upgrade' })
|
||||
return false
|
||||
}
|
||||
set({ upgrade: { ...u, apply: { status: 'saving' } } })
|
||||
const pending = get().pendingNote.trim()
|
||||
try {
|
||||
await get().save(pending ? `${pending};${UPGRADE_TEXT.saveNote}` : UPGRADE_TEXT.saveNote)
|
||||
} catch (error) {
|
||||
const cur = get().upgrade
|
||||
if (cur?.status === 'ready' && cur.seq === u.seq) set({ upgrade: { ...cur, apply: { status: 'failed', error } } })
|
||||
return false
|
||||
}
|
||||
if (get().upgrade?.seq === u.seq) set({ upgrade: null })
|
||||
toast.ok(UPGRADE_TEXT.applied(get().workflow?.version), { key: 'studio:upgrade' })
|
||||
return true
|
||||
}
|
||||
|
||||
/** 上次保存(或打开)时的图。撤销回这个样子时「未保存」要消失 */
|
||||
let savedSig = ''
|
||||
|
||||
@@ -1065,6 +1153,8 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
selectedId: null,
|
||||
dirty: false,
|
||||
issues: [],
|
||||
advice: [],
|
||||
upgrade: null,
|
||||
variables: [],
|
||||
varIssues: [],
|
||||
run: null,
|
||||
@@ -1110,8 +1200,11 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
graphExtras = extrasOf(workflow?.graph)
|
||||
savedSig = graphSig(nodes, edges)
|
||||
lastVarSignature = ''
|
||||
// 上一张图的升级预览:套到这张图上就错了
|
||||
upgradeCtl?.abort()
|
||||
upgradeCtl = null
|
||||
set({
|
||||
workflow, nodes, edges, selectedId: null, dirty: false, issues: [],
|
||||
workflow, nodes, edges, selectedId: null, dirty: false, issues: [], advice: [], upgrade: null,
|
||||
// 变量表也清掉:不清的话切图后抽屉会先显示上一张图的变量
|
||||
variables: [], varIssues: [], analysis: workflow ? 'pending' : 'idle', analysisError: null,
|
||||
...runReset(), run: null, streaming: false, unsubscribe: null,
|
||||
@@ -1161,10 +1254,13 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
}
|
||||
const { nodes: cur, selectedId } = get()
|
||||
const byId = new Map(cur.map((n) => [n.id, n]))
|
||||
// 已有的节点只换名字和配置:位置、量好的尺寸、选中都留着,React Flow 不用重新量一遍
|
||||
// 已有的节点只换类型、名字和配置:位置、量好的尺寸、选中都留着,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
|
||||
return old
|
||||
? { ...old, data: { ...old.data, nodeType: n.data.nodeType, label: n.data.label, config: n.data.config } }
|
||||
: n
|
||||
})
|
||||
glideSeq++
|
||||
commit(set, get, label)
|
||||
@@ -1177,6 +1273,69 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
return true
|
||||
},
|
||||
|
||||
previewUpgrade: async ({ assist = false } = {}) => {
|
||||
const lock = editLockOf(get())
|
||||
if (lock) {
|
||||
toast.warn(EDIT_LOCK_TEXT[lock], { key: 'studio:readonly' })
|
||||
return
|
||||
}
|
||||
upgradeCtl?.abort()
|
||||
const ctl = new AbortController()
|
||||
upgradeCtl = ctl
|
||||
const seq = ++upgradeSeq
|
||||
const { nodes, edges, workflow } = get()
|
||||
const graph = toGraph(nodes, edges)
|
||||
// 受管的图升级完还要按受管重新发布:新写出来的报告节点直接按受管门禁的要求配
|
||||
const level = workflow?.status === 'governed' ? 'governed' : 'published'
|
||||
set({ upgrade: { status: 'loading', assist, seq } })
|
||||
try {
|
||||
const raw = await api.copilot.upgradeEvidence({ graph, level, ...(assist ? { assist: true } : {}) }, { signal: ctl.signal })
|
||||
if (ctl.signal.aborted || get().upgrade?.seq !== seq) return
|
||||
set({ upgrade: { status: 'ready', assist, seq, result: normalizeUpgrade(raw), sig: contentSig(graph), base: graph } })
|
||||
} catch (e) {
|
||||
if (ctl.signal.aborted || get().upgrade?.seq !== seq || (e as { name?: string } | null)?.name === 'AbortError') return
|
||||
set({ upgrade: isMissingEndpoint(e) ? { status: 'unsupported', assist, seq } : { status: 'error', assist, seq, error: e } })
|
||||
}
|
||||
},
|
||||
|
||||
applyUpgrade: async () => {
|
||||
const u = get().upgrade
|
||||
if (u?.status !== 'ready' || !u.result.graph || u.apply?.status === 'saving') return false
|
||||
const { nodes, edges } = get()
|
||||
// 预览是按发请求那一刻的画布算的:之后又改过的话,套上去会把那几下盖掉
|
||||
if (contentSig(toGraph(nodes, edges)) !== u.sig) {
|
||||
set({ upgrade: { ...u, apply: { status: 'stale' } } })
|
||||
return false
|
||||
}
|
||||
if (!get().applyFixes(u.result.graph, UPGRADE_TEXT.undoLabel)) {
|
||||
const lock = editLockOf(get())
|
||||
set({ upgrade: { ...u, apply: { status: 'locked', why: EDIT_LOCK_TEXT[lock ?? 'formal'] } } })
|
||||
return false
|
||||
}
|
||||
return saveUpgrade(set, get)
|
||||
},
|
||||
|
||||
retryUpgradeSave: async () => {
|
||||
const u = get().upgrade
|
||||
if (u?.status !== 'ready' || !upgradeUnsaved(u.apply) || !u.result.graph) return false
|
||||
// 画布上得还是升级完的样子才替它存:撤销过升级、或者之后又改过,再存下去的就不是这次升级了,
|
||||
// 版本说明却还写着「升级为可追溯结构」。对不上就说这份预览过时了,要存按平常的保存来
|
||||
const { nodes, edges } = get()
|
||||
// 升级后的图按 applyFixes 落画布的同一套换算一遍再比(没写名字的节点会补上默认名)
|
||||
const applied = toFlow(u.result.graph)
|
||||
if (contentSig(toGraph(nodes, edges)) !== contentSig(toGraph(applied.nodes, applied.edges))) {
|
||||
set({ upgrade: { ...u, apply: { status: 'stale' } } })
|
||||
return false
|
||||
}
|
||||
return saveUpgrade(set, get)
|
||||
},
|
||||
|
||||
discardUpgrade: () => {
|
||||
upgradeCtl?.abort()
|
||||
upgradeCtl = null
|
||||
set({ upgrade: null })
|
||||
},
|
||||
|
||||
onNodesChange: (changes) => {
|
||||
if (locked(get)) {
|
||||
// 锁定期间只放行量尺寸和选中:前者是 React Flow 自己的,后者不改图
|
||||
@@ -1440,6 +1599,11 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
savedSig = JSON.stringify(graph)
|
||||
// 请求在途时又改了的话,那部分还没存:不能把「未保存」清掉
|
||||
set({ workflow: updated, dirty: graphSig(get().nodes, get().edges) !== savedSig, pendingNote: '' })
|
||||
// 升级落到画布上之后没存上(存失败、要存时锁着),这回平常的保存(⌘S、工具栏)存上了:画布上是什么就存了什么,
|
||||
// 升级要么跟着存进去了、要么已经撤销掉了,「草稿没保存上」都不再是真的。留着的话再点「重试保存」
|
||||
// 会多存一版,版本说明还写着「升级为可追溯结构」
|
||||
const u = get().upgrade
|
||||
if (u?.status === 'ready' && upgradeUnsaved(u.apply)) set({ upgrade: null })
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1456,7 +1620,7 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
validate: async () => {
|
||||
const { nodes, analysis } = get()
|
||||
if (!nodes.length) {
|
||||
set({ issues: [], variables: [], varIssues: [], analysis: 'ok', analysisError: null })
|
||||
set({ issues: [], advice: [], variables: [], varIssues: [], analysis: 'ok', analysisError: null })
|
||||
return
|
||||
}
|
||||
// 已经有一份结论时不翻回「校验中」:连续打字会让工具栏的标签一直闪。
|
||||
|
||||
+37
-1
@@ -298,7 +298,11 @@ export interface KbDocument {
|
||||
}
|
||||
|
||||
export interface ValidationIssue {
|
||||
level: 'error' | 'warning'
|
||||
/**
|
||||
* info 是建议,不是问题(比如 evidence.upgrade_available「可以升级为可追溯结构」):store 在校验回来时
|
||||
* 就把它分到 advice 里,issues 里只有 error / warning——节点卡、检查器、运行按钮都只认这两档
|
||||
*/
|
||||
level: 'error' | 'warning' | 'info'
|
||||
node_id?: string | null
|
||||
edge_id?: string | null
|
||||
message: string
|
||||
@@ -366,6 +370,38 @@ export interface AutofixResult {
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 一键升级预览里的一项改动。形状同自动修复的 AutofixChange,另认这几种:
|
||||
* field 为 type 是节点类型的变化(llm → report);field 为 node 是新插入的节点(after 是节点);
|
||||
* field 为 edge 是连线的改接(before / after 是 {source, target})。rule 是命中的改写规则(R1–R4;Copilot 那一段是 assist)。
|
||||
* 同一步(同一个 fix_id)的几项改动共用一句 label
|
||||
*/
|
||||
export interface UpgradeChange extends AutofixChange {
|
||||
rule?: string | null
|
||||
}
|
||||
|
||||
/** 升级给的说明:不改、只建议的(R5:代码节点要不要标成 source),原样给人看 */
|
||||
export interface UpgradeNote {
|
||||
text: string
|
||||
node_id?: string | null
|
||||
rule?: string | null
|
||||
level?: 'info' | 'warning'
|
||||
}
|
||||
|
||||
/** POST /copilot/upgrade-evidence:只给预览,不自动保存 */
|
||||
export interface UpgradeResult {
|
||||
/** 升级后的整张图;人确认后走现有的保存 */
|
||||
graph: GraphSpec | null
|
||||
changes: UpgradeChange[]
|
||||
notes: UpgradeNote[]
|
||||
/** 升级后的图重跑 validate 和门禁剩下的问题 */
|
||||
issues: ValidationIssue[]
|
||||
/** 没有采用的改动(Copilot 的改写冒出新问题、碰了禁止规则),写明原因 */
|
||||
rejected: { fix_id: string; reason: string }[]
|
||||
/** assist 时 Copilot 的那一段:非纯算术、保留没改的代码节点在 warnings 里 */
|
||||
assist: { ok: boolean; summary?: string; questions?: string[]; warnings?: string[] } | null
|
||||
}
|
||||
|
||||
/** 单个节点在一次运行中的实时状态,驱动画布上的高亮。 */
|
||||
export interface NodeRuntime {
|
||||
/** cancelled / suspended 是终态清扫时收的:运行被取消或服务重启时还没跑完的节点 */
|
||||
|
||||
Reference in New Issue
Block a user