From eb578cad3470a803c4f744e115f9e17980c26e53 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 19:30:47 +0800 Subject: [PATCH 1/8] =?UTF-8?q?=E9=A9=B3=E5=9B=9E=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E7=9A=84=E7=94=BB=E6=B3=95=EF=BC=88=E5=90=8E=E7=AB=AF=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E8=A2=AB=E9=A9=B3=E5=9B=9E=E7=9A=84=E9=82=A3=E4=B8=80?= =?UTF-8?q?=E6=AD=A5=E7=9A=84=20node.failed=20=E5=B8=A6=20reason=3Drejecte?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第 1 波把人的驳回收成 cancelled + end_reason=rejected,但节点层仍只发一条和故障一模一样的 node.failed: 复核规则把它说成「执行失败」、还当成「重跑一次大概率能好」(重跑只会把同一件事再问一遍人),实例进度里 没开待办的驳回(工具调用审批、代码执行审批)落成「失败」(05-已知遗留 (a)、总方案 X9)。 - engine/compiler:NodeRejected 时照旧发 node.failed(时间线、实例进度按它收尾这一步),数据里多带 reason=rejected(和 run.cancelled 同一个字段名)、kind、decision、actor、note;真的出错的 node.failed 一字不变,没有这几个键 - engine/review:认 reason=rejected,记 node_rejected(DEGRADED,不进 RETRYABLE),说「被驳回」不说「执行失败」; 没有 reason 的老运行照旧 node_failed - apps/resolve 的实例进度:按 node.failed 上的 reason 画「被驳回」(结论写已驳回 / 超时驳回 / 未确认(被驳回)), 老运行照旧按待办认 - 测试:六种关卡的 node.failed 都带上这几个键;普通失败没有;复核与实例进度的新旧两种形状(去掉修复回跑会失败) --- backend/app/apps/resolve.py | 16 ++++++++-- backend/app/engine/compiler.py | 16 ++++++++-- backend/app/engine/review.py | 7 +++++ backend/tests/test_review.py | 16 ++++++++++ backend/tests/test_run_rejected.py | 49 ++++++++++++++++++++++++++++++ 5 files changed, 100 insertions(+), 4 deletions(-) diff --git a/backend/app/apps/resolve.py b/backend/app/apps/resolve.py index f8963718..ae394c3b 100644 --- a/backend/app/apps/resolve.py +++ b/backend/app/apps/resolve.py @@ -1738,24 +1738,36 @@ async def _timeline(session: AsyncSession, ctx: _Page) -> dict[str, Any]: if run is None: return {"state": "empty", "steps": []} titles = {k: v["title"] for k, v in node_map(run.graph).items()} - rows = (await session.execute(select(RunEvent.type, RunEvent.node_id, RunEvent.ts).where( + rows = (await session.execute(select(RunEvent.type, RunEvent.node_id, RunEvent.ts, RunEvent.data).where( RunEvent.run_id == run.id, RunEvent.type.in_(tuple(_STEP_STATE))).order_by(RunEvent.seq))).all() trail = (await _trails(session, [run]))[run.id] steps: dict[str, dict[str, Any]] = {} - for etype, node_id, ts in rows: + #: 被驳回的那一步:node.failed 上带着 reason=rejected 和结论(engine/compiler,总方案 X9)。工具调用审批、代码执行审批 + #: 这类驳回没开待办,以前只能落成「失败」;老运行的 node.failed 没有 reason,照旧按待办认 + rejected: dict[str, dict[str, Any]] = {} + for etype, node_id, ts, data in rows: if not node_id: continue step = steps.setdefault(node_id, {"node": node_id, "title": titles.get(node_id, node_id), "state": "running", "started_at": datetime.fromtimestamp(ts, timezone.utc).isoformat()}) step["state"] = _STEP_STATE[etype] step["at"] = datetime.fromtimestamp(ts, timezone.utc).isoformat() + if etype == "node.failed" and isinstance(data, dict) and data.get("reason") == "rejected": + rejected[node_id] = data + elif etype == "node.started": + rejected.pop(node_id, None) for node_id, step in steps.items(): text = None record = next((a for a in reversed(trail.actions) if a.node_id == node_id), None) kind, decision = _decision(trail, node_id) pending = [t for t in trail.tasks if t.node_id == node_id and t.status == "pending"] + said = rejected.get(node_id) if step["state"] == "failed" else None if record is not None and record.state in ("sent", "unknown"): step["state"] = "unknown" + elif said is not None: + step["state"] = "rejected" + text = "未确认(被驳回)" if said.get("kind") == "action_confirm" and said.get("decision") == "reject" \ + else _DECISION_TEXT.get(str(said.get("decision") or ""), _STEP_TEXT["rejected"]) elif step["state"] == "waiting" and pending: text = WAITING_TEXT.get(pending[-1].kind) elif step["state"] == "failed" and kind == "action_confirm" and decision == "reject": diff --git a/backend/app/engine/compiler.py b/backend/app/engine/compiler.py index d0599d58..9d6fbcdc 100644 --- a/backend/app/engine/compiler.py +++ b/backend/app/engine/compiler.py @@ -171,9 +171,12 @@ def _wrap( elapsed = int((time.perf_counter() - started) * 1000) message = _describe(last_error) # node_id 要带上:前端靠它把出错的节点从"转圈"收敛成"失败"。 - # error 是给人看的那句,原始异常放 detail,排查的人照样拿得到 + # error 是给人看的那句,原始异常放 detail,排查的人照样拿得到。 + # 被驳回的这一步照旧发 node.failed(时间线、实例进度按它收尾这一步),另带 reason=rejected(和 run.cancelled 同一个 + # 字段名)、哪种关卡、结论、谁、备注:画布、航迹、时间线、问数据过程、复核规则、实例进度都按这一个字段认「被驳回」, + # 不再画成失败、也不再各自去猜报错原文(总方案 X9)。真的出错的 node.failed 一字不变,没有这几个键 ctx.emit(EventType.NODE_FAILED, error=message, duration_ms=elapsed, node_id=node.id, - detail=_detail(last_error)) + detail=_detail(last_error), **_rejected(last_error)) # 容错模式:记下错误继续往下走,而不是让整张图挂掉。驳回不算错误,不走这里(见上) if node.config.get("on_error") == "continue" and not isinstance(last_error, NodeRejected): @@ -204,6 +207,15 @@ def _describe(error: BaseException | None) -> str: return f"执行出错:{describe_exception(error)}" +def _rejected(error: BaseException | None) -> dict[str, Any]: + """被人驳回的那一步,node.failed 上多带的几个键(同 runner.rejected_data 的说法,节点 id、名字事件本身就有); + 别的失败为空。""" + if not isinstance(error, NodeRejected): + return {} + return {"reason": "rejected", "kind": error.kind, "decision": error.decision, "actor": error.actor, + "note": error.note} + + def _detail(error: BaseException | None) -> str | None: """原始异常。NodeError 自己是人话,真正的原因在它包住的那个异常里。""" if isinstance(error, NodeError): diff --git a/backend/app/engine/review.py b/backend/app/engine/review.py index f2017874..98f349ee 100644 --- a/backend/app/engine/review.py +++ b/backend/app/engine/review.py @@ -219,6 +219,13 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list else: add("tool_error", f"工具 {tool} 调用失败:{err}", BROKEN) + elif etype == EventType.NODE_FAILED and data.get("reason") == "rejected": + # 人的驳回(engine/compiler 给被驳回的那一步的 node.failed 带 reason=rejected,总方案 X9):不是故障,不说「执行 + # 失败」;也不进 RETRYABLE——重跑只会把同一件事再问一遍人。答案没走完是缺口,记 DEGRADED(没有成果时 + # empty_output 另按 BROKEN 说) + err = str(data.get("error") or "").strip()[:200] + add("node_rejected", f"节点「{titles.get(node_id) or node_id}」被驳回:{err}", DEGRADED) + elif etype == EventType.NODE_FAILED: err = str(data.get("error") or "").strip()[:200] add("node_failed", f"节点「{titles.get(node_id) or node_id}」执行失败:{err}", BROKEN) diff --git a/backend/tests/test_review.py b/backend/tests/test_review.py index 0b895435..90cd3e56 100644 --- a/backend/tests/test_review.py +++ b/backend/tests/test_review.py @@ -95,6 +95,22 @@ def test_node_and_run_failures_are_broken(): assert all(s.severity == rv.BROKEN for s in signals) +def test_a_rejected_node_is_a_human_decision_not_a_fault(): + """被驳回的那一步节点层照旧发 node.failed,数据里带 reason=rejected(总方案 X9、05 (a)):复核不能把它说成「执行失败」, + 更不能当成「重跑一次大概率能好」——重跑只会把同一件事再问一遍人。没有 reason 的老运行照旧按失败算。""" + signals = rv.scan([ + ev(EventType.NODE_STARTED, node_id="gate", label="把关"), + ev(EventType.NODE_FAILED, node_id="gate", error="人工驳回:不对", reason="rejected", kind="approve", + decision="reject"), + ], OK_OUTPUT) + [signal] = signals + assert signal.kind == "node_rejected" and signal.severity == rv.DEGRADED + assert signal.detail == "节点「把关」被驳回:人工驳回:不对" and "失败" not in signal.detail + assert not rv.should_retry(signals) + legacy = rv.scan([ev(EventType.NODE_FAILED, node_id="gate", error="人工驳回:不对")], OK_OUTPUT) + assert [s.kind for s in legacy] == ["node_failed"] and rv.should_retry(legacy) + + def test_warn_classified_by_code_not_by_message(): """分类挂在 code 上。消息是给人读的,随时会改。""" assert rv.scan([warn("agent 用满了 8 步还没给出结论。", "step_limit")], OK_OUTPUT)[0] \ diff --git a/backend/tests/test_run_rejected.py b/backend/tests/test_run_rejected.py index bf00fda6..1da7e538 100644 --- a/backend/tests/test_run_rejected.py +++ b/backend/tests/test_run_rejected.py @@ -107,6 +107,55 @@ async def test_a_rejection_ends_the_run_as_cancelled_with_who_and_why(kind): assert row.manifest_hash and row.manifest_seq == cancelled.seq +@pytest.mark.parametrize("kind", list(GATES)) +async def test_the_rejected_step_says_so_on_its_node_failed(kind): + """节点层照旧发 node.failed(时间线、实例进度按它收尾这一步),数据里带上 reason=rejected(和 run.cancelled 同一个字段名)、 + 哪种关卡、结论、谁、备注:画布、航迹、时间线、问数据过程据此画「被驳回」,不画成失败(05 (a)、总方案 X9)。原话照旧。""" + run_id = await _rejected_run(kind) + await _wait(run_id, ("cancelled", "failed", "succeeded")) + [failed] = [e for e in await _events(run_id, "node.failed") if e.node_id == "gate"] + data = failed.data + assert data["error"] == GATES[kind][1] + assert {k: data.get(k) for k in ("reason", "kind", "decision", "actor", "note")} == { + "reason": "rejected", "kind": kind, "decision": "reject", "actor": "张工", "note": "不对"} + + +async def test_a_plain_node_failure_carries_no_reason(): + """真的出错(这里是工具不存在):node.failed 和以前一字不差,没有 reason 这个键。""" + bad = node("gate", "tool", label="查一下", tool="no_such_tool_here", args={}) + run = await run_manager.start(graph=chain(START, bad, OUT), input_payload={"q": "x"}) + final = await _wait(run.id, ("cancelled", "failed", "succeeded")) + assert final.status == "failed" + [failed] = [e for e in await _events(run.id, "node.failed") if e.node_id == "gate"] + assert "reason" not in failed.data and "decision" not in failed.data + + +async def test_the_instance_timeline_says_rejected_without_a_task(): + """实例进度:被驳回的那一步按 node.failed 上的 reason 画「被驳回」——工具调用审批这类没开待办的驳回,以前落成「失败」。 + 老运行(node.failed 没有 reason、也没有待办)照旧写失败。""" + from types import SimpleNamespace + + from app.apps.resolve import _timeline + + run_id = await _rejected_run("tool") + await _wait(run_id, ("cancelled",)) + async with SessionLocal() as session: + new = await session.get(Run, run_id) + legacy = Run(workflow_name="老的失败", status="failed", graph=new.graph, input={}, error="出错了", + error_node_id="gate") + session.add(legacy) + await session.flush() + session.add_all([ + RunEvent(run_id=legacy.id, seq=1, type="node.started", node_id="gate", ts=1.0, data={}), + RunEvent(run_id=legacy.id, seq=2, type="node.failed", node_id="gate", ts=2.0, data={"error": "出错了"}), + ]) + await session.commit() + steps = {s["node"]: s for s in (await _timeline(session, SimpleNamespace(instance=new)))["steps"]} + old = {s["node"]: s for s in (await _timeline(session, SimpleNamespace(instance=legacy)))["steps"]} + assert (steps["gate"]["state"], steps["gate"]["text"]) == ("rejected", "已驳回") + assert (old["gate"]["state"], old["gate"]["text"]) == ("failed", "失败") + + async def test_a_timeout_rejection_is_recorded_as_expired_reject(): from app.process import tasks From 4c7c0cf283ef62f582345e6e793dd7cb617658a9 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 19:42:11 +0800 Subject: [PATCH 2/8] =?UTF-8?q?=E9=A9=B3=E5=9B=9E=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E7=9A=84=E7=94=BB=E6=B3=95=EF=BC=88=E5=89=8D=E7=AB=AF=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E8=A2=AB=E9=A9=B3=E5=9B=9E=E7=9A=84=E9=82=A3=E4=B8=80?= =?UTF-8?q?=E6=AD=A5=E7=94=BB=E6=88=90=E3=80=8C=E8=A2=AB=E9=A9=B3=E5=9B=9E?= =?UTF-8?q?=E3=80=8D=EF=BC=8C=E4=B8=8D=E7=94=BB=E6=88=90=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端给被驳回的那一步的 node.failed 带上了 reason=rejected(上一个提交)。界面上读 node.failed 的几处都认它 (05-已知遗留 (a)、总方案 X9:驳回是人的决定,不是故障),没有 reason 的老运行照旧画失败: - run/decode:问数据过程、记录页、画布右栏的时间线里,这一步状态 rejected(StepStatus 加一种),副标题写谁驳回、 备注(REJECTED_TEXT.step),原话放展开里;不是 error 级别,不当成出错 - run/trace、run/derive:NodeState 加 rejected;那一段收成 rejected,不记成「失败的节点」,下游是「未到达」不是 「被阻断」;回放投影同样是 rejected - 画布节点卡:rejected 一种读数(耗时 + 原话第一句,整句悬停),中性色、停止剪影,不挂失败红框、不抖动;小地图、 运行胶囊的计数、时间轴泳道认得它;记录页航迹的节点卡写「被驳回:原话」 - check-decode、check-run-states 各加一段:新旧两种形状 --- frontend/src/canvas/FlowCanvas.tsx | 2 + frontend/src/canvas/NodeCard.tsx | 10 ++++- frontend/src/canvas/surface.css | 2 + frontend/src/index.css | 9 +++++ frontend/src/lib/terms.ts | 12 ++++++ frontend/src/pages/runs/TracePane.tsx | 2 + frontend/src/run/RunHud.tsx | 2 +- frontend/src/run/decode.ts | 30 +++++++++++++-- frontend/src/run/derive.ts | 2 +- frontend/src/run/trace.ts | 15 ++++++-- frontend/src/run/useNodeView.ts | 2 +- frontend/src/types.ts | 3 +- scripts/check-decode.mjs | 49 ++++++++++++++++++++++++ scripts/check-run-states.mjs | 54 +++++++++++++++++++++++++++ 14 files changed, 181 insertions(+), 13 deletions(-) diff --git a/frontend/src/canvas/FlowCanvas.tsx b/frontend/src/canvas/FlowCanvas.tsx index 4f6f714e..013f9108 100644 --- a/frontend/src/canvas/FlowCanvas.tsx +++ b/frontend/src/canvas/FlowCanvas.tsx @@ -196,6 +196,8 @@ const MINI_FILL: Partial> = { done: 'color-mix(in srgb, var(--st-done) 70%, transparent)', skipped: 'var(--st-skipped)', cancelled: 'var(--st-cancelled)', + // 被驳回:人的决定,和取消同一种中性色(不画失败色) + rejected: 'var(--st-cancelled)', suspended: 'var(--st-suspended)', blocked: 'var(--st-blocked)', unreached: 'color-mix(in srgb, var(--st-unreached) 45%, transparent)', diff --git a/frontend/src/canvas/NodeCard.tsx b/frontend/src/canvas/NodeCard.tsx index 624024f9..00747e0a 100644 --- a/frontend/src/canvas/NodeCard.tsx +++ b/frontend/src/canvas/NodeCard.tsx @@ -18,7 +18,7 @@ import { explainRunError } from '../lib/explain' import { formatDuration, formatLapse, formatNumber, formatTokens, NONE, shortId } from '../lib/format' import { statusMeta } from '../lib/status' import { - CHALLENGE_TEXT, claimTally, DUAL_CHECK_TEXT, issuanceLabel, reportStampText, RUN_CLASS_LABEL, UPGRADE_POLICY_LABEL, + CHALLENGE_TEXT, claimTally, DUAL_CHECK_TEXT, issuanceLabel, REJECTED_TEXT, reportStampText, RUN_CLASS_LABEL, UPGRADE_POLICY_LABEL, } from '../lib/terms' import { useReportStamp, type ReportStamp } from './reportStamp' import { ApprovalCard } from '../run/RunPanel' @@ -559,6 +559,14 @@ function readingOf({ state, view, type, config, skewMs, timed, fanIn, facts, sin noteTitle: why.title, } } + case 'rejected': + // 被人驳回(node.failed 带 reason=rejected):人的决定,不是失败。状态字已经写了「被驳回」,槽里写原话的第一句 + // (「人工驳回:数字对不上」),整句放悬停;不按失败去归类、讲处理建议 + return { + main: formatDuration(n?.lastDurationMs ?? runtime?.durationMs), + note: error ? firstSentence(error) : REJECTED_TEXT.card, + noteTitle: error || undefined, + } case 'queued': return { main: '', note: fanIn > 1 ? '等待其余上游完成' : '上游已交付,等待开始' } case 'skipped': diff --git a/frontend/src/canvas/surface.css b/frontend/src/canvas/surface.css index f010c52d..bc36fc27 100644 --- a/frontend/src/canvas/surface.css +++ b/frontend/src/canvas/surface.css @@ -1443,6 +1443,8 @@ background: color-mix(in srgb, var(--st-failed) 45%, transparent); } .tl-s-cancelled { --c: var(--st-cancelled); } +/* 被驳回的那一段:人的决定,和取消同一种中性色 */ +.tl-s-rejected { --c: var(--st-cancelled); } .tl-s-suspended { --c: var(--st-suspended); } .tl-s-waiting { --c: var(--st-waiting); } .tl-s-waited { --c: var(--st-waiting); opacity: 0.8; } diff --git a/frontend/src/index.css b/frontend/src/index.css index 70aa7a52..ac5af16e 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -830,6 +830,15 @@ .node-cancelled .nc-slot { background: var(--st-cancelled); } +/* 被人驳回的那一步(node.failed 带 reason=rejected):人的决定,不是故障。和取消同一种中性色,不画失败的红框、不抖动 */ +.nc.node-rejected { + --st-c: var(--st-cancelled); + border-color: color-mix(in srgb, var(--st-cancelled) 70%, var(--border)); +} +.node-rejected .nc-slot { + width: 5px; + background: var(--st-cancelled); +} .nc.node-suspended { --st-c: var(--st-suspended); border-color: color-mix(in srgb, var(--st-suspended) 70%, var(--border)); diff --git a/frontend/src/lib/terms.ts b/frontend/src/lib/terms.ts index c3744e5b..b7d8723c 100644 --- a/frontend/src/lib/terms.ts +++ b/frontend/src/lib/terms.ts @@ -5439,6 +5439,18 @@ export const REJECTED_TEXT = { }, /** 问数据:这一轮的运行被驳回结束时,补救区的那一句 */ chatReason: '这一轮的运行被审批人驳回,已经结束。这是人的决定,不是故障;改好内容后可以重新运行。', + /** + * 被驳回的那一步自己(node.failed 带 reason=rejected):时间线、问数据过程里这一步的副标题。步骤名就是节点名,不再写一遍 + * 「在哪一步」;谁、备注照写,超时驳回写按设置驳回 + */ + step: (d: { actor?: unknown; note?: unknown; decision?: unknown }): string => { + const who = typeof d.actor === 'string' ? d.actor.trim() : '' + const note = typeof d.note === 'string' ? d.note.trim() : '' + if (d.decision === 'expired_reject') return '超过时限,按设置驳回' + return `${who ? `${who} 驳回` : '被驳回'}${note ? `:${note}` : ''}` + }, + /** 画布节点卡上被驳回的那一步:一句话,悬停写原话 */ + card: '被驳回', } /** 来源标签:老运行没有来源时写「来源未记录」 */ diff --git a/frontend/src/pages/runs/TracePane.tsx b/frontend/src/pages/runs/TracePane.tsx index 73dbbbdb..c165b23c 100644 --- a/frontend/src/pages/runs/TracePane.tsx +++ b/frontend/src/pages/runs/TracePane.tsx @@ -612,6 +612,8 @@ function NodeCard({ id, trace, proj, state, graph, facts, at, labelOf, href, gon if (n?.takenHandle && (state === 'done' || state === 'failed')) rows.push(['出口', {n.takenHandle}]) if (n?.reason) rows.push(['理由', n.reason]) if (state === 'skipped' && n?.skippedReason) rows.push(['跳过', n.skippedReason]) + // 被人驳回的那一步(node.failed 带 reason=rejected):写原话(谁驳回、为什么),不按失败去讲原因和处理建议 + if (state === 'rejected' && n?.error) rows.push([REJECTED_TEXT.title, n.error]) // 卡片说的是游标那一刻所在的那一次执行(和画布卡片同一个划分):循环上一轮、接着跑之前 // 的事不挂到这一次干净的执行上;回放到更早的一次时,也不因为后面还有一件就看不到这一次的 const since = execStart(n, at, facts) diff --git a/frontend/src/run/RunHud.tsx b/frontend/src/run/RunHud.tsx index f18e3837..b90bbc43 100644 --- a/frontend/src/run/RunHud.tsx +++ b/frontend/src/run/RunHud.tsx @@ -458,7 +458,7 @@ function Cells({ cells, onPick }: { cells: RunGlance['cells']; onPick: (id: stri } const COUNT_ORDER: NodeState[] = [ - 'running', 'waiting', 'failed', 'suspended', 'done', 'queued', 'blocked', 'unreached', 'skipped', 'cancelled', + 'running', 'waiting', 'failed', 'rejected', 'suspended', 'done', 'queued', 'blocked', 'unreached', 'skipped', 'cancelled', ] // ------------------------------------------------------------------------- diff --git a/frontend/src/run/decode.ts b/frontend/src/run/decode.ts index 6e2eeeb7..ba6d6a92 100644 --- a/frontend/src/run/decode.ts +++ b/frontend/src/run/decode.ts @@ -93,7 +93,8 @@ export type StepKind = * suspended:服务重启时还在跑的步骤,断点还在,可以接着跑。 * skipped:skip_if 成立、这一步没有执行。和"根本没轮到"是两回事,得留痕。 */ -export type StepStatus = 'running' | 'done' | 'failed' | 'waiting' | 'cancelled' | 'suspended' | 'skipped' +/** rejected:这一步被人驳回(node.failed 带 reason=rejected)。人的决定,不是失败:不画红、不算出错 */ +export type StepStatus = 'running' | 'done' | 'failed' | 'waiting' | 'cancelled' | 'suspended' | 'skipped' | 'rejected' /** 节点的某一次执行。循环体、轮询类节点一次运行里会执行几十上百次 */ export interface Exec { @@ -394,7 +395,7 @@ export function decodePhase(events: RunEvent[], final?: RunFinal): RunPhase { const STEP_OF: Partial> = { done: 'done', failed: 'failed', waiting: 'waiting', cancelled: 'cancelled', - suspended: 'suspended', running: 'running', skipped: 'skipped', + suspended: 'suspended', running: 'running', skipped: 'skipped', rejected: 'rejected', } const stepStatusOf = (state: NodeState): StepStatus => STEP_OF[state] ?? 'done' @@ -2018,10 +2019,31 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt } case 'node.failed': { - // 节点失败时还在进行中的那次调用就是出错的那次,跟节点一起算失败,不留给清扫写成已取消 - closeLlm(nodeId, 'failed', at) const step = nodeId ? nodeSteps.get(nodeId) : undefined const ms = num(d.duration_ms) + if (d.reason === 'rejected') { + // 人的驳回(服务端给被驳回的那一步的 node.failed 带 reason=rejected,总方案 X9):这一步写「被驳回」,副标题写谁、 + // 备注,原话放展开里;不画红、不当成出错(老运行的 node.failed 没有 reason,照旧按失败画) + closeLlm(nodeId, 'cancelled', at) + const sub = REJECTED_TEXT.step(d) + if (step) { + const cur = execOf(nodeId) + if (cur) { cur.status = 'rejected'; if (ms != null) cur.ms = ms } + step.status = 'rejected' + step.level = undefined + step.sub = sub + step.detail = String(d.error ?? '') + step.ms = ms + step.meta = dur(ms) + } else { + push({ id: `nr-${seq}`, seq, kind: 'lifecycle', status: 'rejected', title: REJECTED_TEXT.title, sub, + ...(d.error ? { detail: String(d.error) } : {}), nodeId }, nodeId) + } + trackTeam(event) + break + } + // 节点失败时还在进行中的那次调用就是出错的那次,跟节点一起算失败,不留给清扫写成已取消 + closeLlm(nodeId, 'failed', at) // detail 是原始异常:给排查用,不给人读,折起来 const raw = typeof d.detail === 'string' && d.detail ? d.detail : undefined if (step) { diff --git a/frontend/src/run/derive.ts b/frontend/src/run/derive.ts index 5313c375..3d669e68 100644 --- a/frontend/src/run/derive.ts +++ b/frontend/src/run/derive.ts @@ -224,7 +224,7 @@ export function heldEdgesOf(trace: Trace, graph: GraphLike): string[] { return out } -const STARTED = new Set(['running', 'waiting', 'done', 'failed', 'skipped', 'cancelled', 'suspended']) +const STARTED = new Set(['running', 'waiting', 'done', 'failed', 'skipped', 'cancelled', 'suspended', 'rejected']) /** * 这次运行实际走过的边:源放行过这条出口(循环里任何一轮都算),目标也确实开跑过。 diff --git a/frontend/src/run/trace.ts b/frontend/src/run/trace.ts index d0aedd17..b9a29860 100644 --- a/frontend/src/run/trace.ts +++ b/frontend/src/run/trace.ts @@ -21,9 +21,13 @@ import { applyDerived, type GraphLike } from './derive' export type RunPhase = | 'idle' | 'queued' | 'running' | 'waiting' | 'succeeded' | 'failed' | 'cancelled' | 'suspended' +/** + * rejected:这一步被人驳回(node.failed 带 reason=rejected,总方案 X9)。是人的决定、不是故障:不画失败色,不算「失败于 X」, + * 下游也不是「被阻断」(运行收成了 cancelled,没走到的照旧是未到达)。老运行的 node.failed 没有 reason,照旧是 failed + */ export type NodeState = | 'idle' | 'queued' | 'running' | 'waiting' | 'done' | 'failed' | 'skipped' - | 'cancelled' | 'suspended' | 'blocked' | 'unreached' + | 'cancelled' | 'suspended' | 'blocked' | 'unreached' | 'rejected' export interface Segment { start: number @@ -568,6 +572,8 @@ export function foldEvent(t: Trace, ev: RunEvent): Trace { if (!nodeId) break const n = node(nodeId) const failed = type === 'node.failed' + // 被人驳回的那一步(服务端在 node.failed 上带 reason=rejected):这一段收成「被驳回」,不是失败 + const rejected = failed && d.reason === 'rejected' // 节点跑完了,决定已经生效(兜底 human.resolved 没发出来的老运行) if (!failed && next.book.asking[nodeId]) delete book().asking[nodeId] const ms = num(d.duration_ms) @@ -583,7 +589,7 @@ export function foldEvent(t: Trace, ev: RunEvent): Trace { if (open >= 0) { const seg = n.segments[open] if (!tsOk && ms != null) end = seg.start + ms - patchSeg(n, open, { end, status: failed ? 'failed' : 'done' }) + patchSeg(n, open, { end, status: rejected ? 'rejected' : failed ? 'failed' : 'done' }) } // 容器里还开着的成员、调度段:节点都结束了,它们不可能还在跑 n.segments.forEach((s, i) => { @@ -597,10 +603,11 @@ export function foldEvent(t: Trace, ev: RunEvent): Trace { // 漏了 tool.end 的工具随节点一起收掉;记一条刻度,下一轮回放时不带着上一轮的「在跑」 if (n.toolsRunning) { n.toolsRunning = 0; mark(n) } n.looping = looping - n.state = failed ? 'failed' : looping ? 'running' : 'done' + n.state = rejected ? 'rejected' : failed ? 'failed' : looping ? 'running' : 'done' if (failed) { + // 驳回的原话照样留着(卡片、航迹悬停写得出是谁驳回、为什么),但它不是「最近一次失败」:不拿它当失败的节点 n.error = String(d.error ?? '') - book().lastFailed = nodeId + if (!rejected) book().lastFailed = nodeId } else { n.attempt = num(d.attempt) ?? n.attempt } diff --git a/frontend/src/run/useNodeView.ts b/frontend/src/run/useNodeView.ts index 73ddba82..7bfc74cc 100644 --- a/frontend/src/run/useNodeView.ts +++ b/frontend/src/run/useNodeView.ts @@ -91,7 +91,7 @@ export function replayTraceCached(trace: Trace, at: number, graph: GraphLike): T } const state = p?.state ?? 'idle' // 人工审批的通过 / 驳回只记在节点上,不在段上:它结束了就用节点上的 - const finished = state === 'done' || state === 'failed' + const finished = state === 'done' || state === 'failed' || state === 'rejected' const decided = taken.length ? taken : finished ? n.taken ?? [] : [] nodes[id] = { ...n, state, count: p?.count ?? 0, iteration: p?.iteration, taken: decided, diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 49163c1d..742ac45a 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -1506,7 +1506,8 @@ export interface UpgradeResult { /** 单个节点在一次运行中的实时状态,驱动画布上的高亮。 */ export interface NodeRuntime { /** cancelled / suspended 是终态清扫时收的:运行被取消或服务重启时还没跑完的节点 */ - status: 'idle' | 'running' | 'done' | 'failed' | 'waiting' | 'skipped' | 'cancelled' | 'suspended' + /** rejected:这一步被人驳回(node.failed 带 reason=rejected,run/trace 的 NodeState 同名) */ + status: 'idle' | 'running' | 'done' | 'failed' | 'waiting' | 'skipped' | 'cancelled' | 'suspended' | 'rejected' durationMs?: number preview?: any error?: string diff --git a/scripts/check-decode.mjs b/scripts/check-decode.mjs index 77af3970..dd165d1d 100644 --- a/scripts/check-decode.mjs +++ b/scripts/check-decode.mjs @@ -2842,5 +2842,54 @@ await section('人的驳回 run.cancelled reason=rejected(05-已知遗留 (a) check('老事件(没有 reason)照旧「已取消」', legacy?.title === '已取消', legacy?.title) }) +await section('被驳回的那一步:node.failed 带 reason=rejected 时画「被驳回」,不画成失败;没有 reason 的老运行照旧失败(05 (a)、X9)', async () => { + const trace = await import(await load('/src/run/trace.ts')) + const derive = await import(await load('/src/run/derive.ts')) + const E = (seq, type, node_id, data = {}) => ({ seq, type, node_id, ts: seq, data }) + const start = [E(1, 'run.started', null, { nodes: 3 }), E(2, 'node.started', 'pay', { label: '付款' }), + E(3, 'human.requested', 'pay', { title: '确认发送:付款' }), E(4, 'human.resolved', 'pay', { approved: false, note: '金额不对', actor: '张工' })] + const rejectedFail = E(5, 'node.failed', 'pay', { error: '「付款」未确认(被驳回),没有发送:金额不对', duration_ms: 1200, + reason: 'rejected', kind: 'action_confirm', decision: 'reject', actor: '张工', note: '金额不对' }) + const legacyFail = E(5, 'node.failed', 'pay', { error: '人工驳回:金额不对', duration_ms: 1200 }) + const end = E(6, 'run.cancelled', null, { reason: 'rejected', node_id: 'pay', label: '付款', kind: 'action_confirm', + decision: 'reject', actor: '张工', note: '金额不对' }) + const node = (events) => flatten(mod.decodeRun(events)).find((s) => s.kind === 'node' && s.nodeId === 'pay') + + const step = node([...start, rejectedFail, end]) + check('这一步写「被驳回」:状态 rejected,不是 failed、不是 error', step?.status === 'rejected' && step?.level !== 'error', + `${step?.status} / ${step?.level}`) + check('副标题写谁驳回、备注(步骤名就是节点名,不再写一遍)', step?.sub === '张工 驳回:金额不对', step?.sub) + check('原话放展开里,一字不改', step?.detail === '「付款」未确认(被驳回),没有发送:金额不对', step?.detail) + check('这一次执行也记成被驳回', step?.execs?.at(-1)?.status === 'rejected', step?.execs?.at(-1)?.status) + const expired = node([...start, { ...rejectedFail, data: { ...rejectedFail.data, decision: 'expired_reject', actor: null, + note: '超过时限,按设置驳回' } }, end]) + check('超时驳回:写按设置驳回,备注不重复', expired?.sub === '超过时限,按设置驳回', expired?.sub) + const legacy = node([...start, legacyFail, end]) + check('老运行(node.failed 没有 reason)照旧画失败', legacy?.status === 'failed' && legacy?.level === 'error', + `${legacy?.status} / ${legacy?.level}`) + + // 航迹:节点状态是 rejected,不是「失败于 X」,下游是「未到达」不是「被阻断」 + const graph = { nodes: [{ id: 'start', type: 'input' }, { id: 'pay', type: 'tool' }, { id: 'out', type: 'output' }], + edges: [{ source: 'start', target: 'pay' }, { source: 'pay', target: 'out' }] } + const fold = (events) => derive.applyDerived(events.reduce(trace.foldEvent, trace.emptyTrace()), graph) + // 航迹照真实的先后:停在确认上(run.interrupted)→ 人回复后恢复(run.resumed、重放的 node.started)→ 驳回 + const real = [E(1, 'run.started', null, { nodes: 3 }), E(2, 'node.started', 'pay', { label: '付款' }), + E(3, 'human.requested', 'pay', { title: '确认发送:付款' }), E(4, 'run.interrupted', 'pay', { payload: { node_id: 'pay' } }), + E(5, 'run.resumed', null, {}), E(6, 'node.started', 'pay', { label: '付款', resumed: true }), + E(7, 'human.resolved', 'pay', { approved: false, note: '金额不对', actor: '张工' })] + const at = (e, seq) => ({ ...e, seq, ts: seq }) + const t = fold([...real, at(rejectedFail, 8), at(end, 9)]) + check('航迹:被驳回的节点状态是 rejected', t.nodes.pay?.state === 'rejected', t.nodes.pay?.state) + check('航迹:不记成失败的节点(没有「失败于 付款」)', t.failedNodeId === undefined, t.failedNodeId) + check('航迹:那一段也收成 rejected', t.nodes.pay?.segments?.at(-1)?.status === 'rejected', t.nodes.pay?.segments?.at(-1)?.status) + check('航迹:下游是「未到达」,不是「被阻断」', t.nodes.out?.state === 'unreached', t.nodes.out?.state) + check('航迹:原话留着(卡片悬停写得出谁、为什么)', t.nodes.pay?.error === '「付款」未确认(被驳回),没有发送:金额不对') + check('回放到驳回之后那一刻:投影也是 rejected', trace.project(t, 8500).nodes.pay?.state === 'rejected', + trace.project(t, 8500).nodes.pay?.state) + const old = fold([...real, at(legacyFail, 8), E(9, 'run.failed', null, { error: '人工驳回:金额不对', node_id: 'pay' })]) + check('老运行照旧:失败、失败于付款、下游被阻断', old.nodes.pay?.state === 'failed' && old.failedNodeId === 'pay' + && old.nodes.out?.state === 'blocked', `${old.nodes.pay?.state} / ${old.failedNodeId} / ${old.nodes.out?.state}`) +}) + console.log(failed ? `\n✗ ${failed} 项未通过` : '\n✓ 解码器全部通过') process.exit(failed ? 1 : 0) diff --git a/scripts/check-run-states.mjs b/scripts/check-run-states.mjs index 798b5c08..64afc46f 100644 --- a/scripts/check-run-states.mjs +++ b/scripts/check-run-states.mjs @@ -1508,6 +1508,60 @@ await section('exits', async () => { } }) +// ---------------------------------------------------------------- 被驳回的那一步 + +await section('rejected', async () => { + // 驳回是人的决定,不是故障(05 (a)、总方案 X9):被驳回的那一步节点层仍发 node.failed,但带 reason=rejected。画布上它画成 + // 「被驳回」——中性色、停止的剪影,不是失败的三角、红框、抖动;下游是「未到达」,不是「被阻断」;运行胶囊的计数写被驳回。 + // 没有 reason 的老运行照旧画失败 + console.log('\n=== 被驳回的那一步 ===') + const REJECT_TAIL = [ + [3, 'human.resolved', 'human', { approved: false, note: '数字对不上', actor: '李工' }], + [0.05, 'run.resumed', null, { actor: '李工' }], + [0.05, 'node.started', 'human', { resumed: true }], + [0.1, 'node.failed', 'human', { duration_ms: 40, error: '人工驳回:数字对不上', reason: 'rejected', kind: 'approve', + decision: 'reject', actor: '李工', note: '数字对不上' }], + [0.05, 'run.cancelled', null, { reason: 'rejected', node_id: 'human', label: '班长审批', kind: 'approve', decision: 'reject', + actor: '李工', note: '数字对不上', timing: { wall_ms: 60000, active_ms: 40000, wait_ms: 20000 } }], + ] + const REJECTED = script([...HEAD, ...TEAM_ROUND0, ...TEAM_DONE, ...LOOP_DONE, ...TO_GATE, ...REJECT_TAIL]) + const LEGACY = script([...HEAD, ...TEAM_ROUND0, ...TEAM_DONE, ...LOOP_DONE, ...TO_GATE, + ...REJECT_TAIL.slice(0, 3), + [0.1, 'node.failed', 'human', { duration_ms: 40, error: '人工驳回:数字对不上' }], + [0.05, 'run.failed', null, { error: '人工驳回:数字对不上', node_id: 'human', timing: { wall_ms: 60000, active_ms: 40000, wait_ms: 20000 } }]]) + const { browser, page, errors } = await open({ theme: 'dark' }) + await setLod(page, 'full') + await feed(page, REJECTED(Date.now())) + await page.waitForTimeout(400) + const all = await cards(page) + check('被驳回的那一步:卡片状态是 rejected', all.human?.state === 'rejected', all.human?.state) + check('……剪影是停止(和取消同一个),不是失败的三角', all.human?.shape === 'stop', all.human?.shape) + check('……槽里写「被驳回」和原话的第一句', /被驳回/.test(all.human?.text ?? '') && /数字对不上/.test(all.human?.text ?? ''), + JSON.stringify(all.human?.text)) + check('……不写「失败」', !/失败/.test(all.human?.text ?? ''), JSON.stringify(all.human?.text)) + const look = await page.evaluate(() => { + const card = document.querySelector('.react-flow__node[data-id="human"] .nc') + const note = card?.querySelector('.nc-tele-note') + return { failedClass: card?.classList.contains('node-failed'), rejectedClass: card?.classList.contains('node-rejected'), + noteTitle: note?.getAttribute('title') ?? '' } + }) + check('……不挂失败的红框(node-failed),挂 node-rejected', !look.failedClass && look.rejectedClass, JSON.stringify(look)) + check('……悬停写原话(谁驳回、为什么)', look.noteTitle.includes('数字对不上'), look.noteTitle) + check('下游是「未到达」,不是「被阻断」', all.out?.state === 'unreached', all.out?.state) + const failedId = await page.evaluate(() => window.__studio.getState().trace.failedNodeId ?? null) + check('航迹里没有「失败的节点」', failedId === null, String(failedId)) + check('运行收成 cancelled(不是 failed)', await page.evaluate(() => window.__studio.getState().runPhase) === 'cancelled') + shots.push(await shot(page, 'dark-rejected')) + + await feed(page, LEGACY(Date.now())) + await page.waitForTimeout(400) + const old = await cards(page) + check('老运行(node.failed 没有 reason)照旧画失败、下游被阻断', old.human?.state === 'failed' && old.out?.state === 'blocked', + `${old.human?.state} / ${old.out?.state}`) + check('没有运行时报错', errors.length === 0, errors.slice(0, 3).join(' | ')) + await browser.close() +}) + // ---------------------------------------------------------------- 关掉动效 await section('reduced', async () => { From a43224fd9aacc5ae4d18dee2f394c0a691b2e7bf Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 19:46:03 +0800 Subject: [PATCH 3/8] =?UTF-8?q?=E8=B4=A6=E6=9C=AC=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E8=A1=A5=E5=87=A0=E6=A0=B7=E7=95=8C=E9=9D=A2=E8=A6=81=E7=94=BB?= =?UTF-8?q?=E7=9A=84=E4=B8=9C=E8=A5=BF=EF=BC=9A=E5=AF=B9=E8=B4=A6=E7=9A=84?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E5=AD=97=E6=AE=B5=E3=80=81=E9=85=8D=E5=88=97?= =?UTF-8?q?=E9=80=89=E9=A1=B9=E3=80=81=E5=AF=B9=E8=B4=A6=E5=8D=A1=E7=9A=84?= =?UTF-8?q?=E5=88=86=E7=BB=84=EF=BC=8C=E5=88=9A=E8=B7=91=E5=AE=8C=E6=9C=AA?= =?UTF-8?q?=E5=B0=81=E5=AD=98=E6=97=B6=E7=AD=94=20pending?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 账本前端(第 4 波 W4-c)照「界面层不放逻辑」只照服务端给的画,这几样以前接口不给,界面只能自己猜: - 「看差多少」那一项(reconcile.actions_of)带上口径的入口字段 fields(名字、必填、有没有缺省值,比对工件里记的那一份): 核对参数的表单照它画,缺的参数也写得出是哪一项 - 认不出列怎么配(409 ledger_reconcile_needs_pairs)另带 options:这次结果里是数、没遮罩的列,口径卡上的指标(id、名字、 单位);ReconcileRefused 加 extra,api/ledger 的对账接口把它并进返回体(CodedHTTPException 的 extra,改一行) - 对过的账(reconciled_view)带 card 和 groups:每一组对照的这次 / 口径 / 差值 / 相对差各是哪个指标、这一组怎么称呼 (从对账运行的图里读,不按命名规则拼),界面按 /evidence/metrics/{card}/{指标} 取值、三个数各自点得开 - GET /api/runs/{id}/ledger:runner 先发 run.finished、落库,再封存、再排比对,页面收到 run.finished 立刻来取时 还没封存。成功结束、要比对的运行这时答 pending(不另排按需比对),不再说成「运行还没有封存,不比对」 - 测试:对账的三样(单行、多行),刚跑完未封存答 pending、不排按需比对,失败的照旧 ineligible --- backend/app/api/ledger.py | 2 +- backend/app/ledger/reconcile.py | 62 +++++++++++++++++++++++--- backend/app/ledger/view.py | 5 +++ backend/tests/test_ledger_api.py | 24 ++++++++++ backend/tests/test_ledger_reconcile.py | 32 +++++++++++++ 5 files changed, 117 insertions(+), 8 deletions(-) diff --git a/backend/app/api/ledger.py b/backend/app/api/ledger.py index 5c8baa41..05ce37a3 100644 --- a/backend/app/api/ledger.py +++ b/backend/app/api/ledger.py @@ -159,7 +159,7 @@ async def reconcile_answer(run_id: str, payload: ReconcileIn) -> dict[str, Any]: query=payload.query, workflow_id=payload.workflow_id, version=payload.version, inputs=payload.inputs, confirm=payload.confirm, pairs=payload.pairs), principal=current_principal()) except ledger_reconcile.ReconcileRefused as e: - raise CodedHTTPException(e.status_code, e.message, e.code) from e + raise CodedHTTPException(e.status_code, e.message, e.code, extra=e.extra) from e return {"run_id": run.id, "reconciled": ledger_reconcile.reconciled_view(run)} diff --git a/backend/app/ledger/reconcile.py b/backend/app/ledger/reconcile.py index 89cf56de..dc997743 100644 --- a/backend/app/ledger/reconcile.py +++ b/backend/app/ledger/reconcile.py @@ -77,11 +77,16 @@ ROWS_CALIBER_COLUMNS = "认不出口径取数的结果列,按位置对不上" class ReconcileRefused(Exception): - def __init__(self, status_code: int, message: str, code: str = REFUSED) -> None: + """不能对账。extra 是给界面的几样(并进 409 的返回体):认不出列怎么配时的 options(可选的列、口径卡上的指标),界面 + 照它画「选要对照的指标」那一步,不自己去猜有哪些列。""" + + def __init__(self, status_code: int, message: str, code: str = REFUSED, *, + extra: dict[str, Any] | None = None) -> None: super().__init__(message) self.status_code = status_code self.message = message self.code = code + self.extra = dict(extra or {}) # ========================================================================== @@ -106,7 +111,8 @@ def _needs_check(cand: dict[str, Any], fields: list[dict[str, Any]], hide: Any) def actions_of(content: dict[str, Any], names: dict[str, str], hide: Any = None) -> list[dict[str, Any]]: """比对工件里每条有相关口径的查询、每份相关口径一项「看差多少」:{kind: reconcile, query, workflow_id, version, node_id, - needs_check, check_reason?, binding(遮过的)}。界面据此摆按钮、要不要先核对参数。""" + needs_check, check_reason?, binding(遮过的), fields}。界面据此摆按钮、要不要先核对参数;fields 是那一版口径的入口字段 + (名字、必填、有没有缺省值,比对工件里记的那一份),核对参数的表单照它画(缺的参数也写得出是哪一项)。""" from app.ledger.labels import LEVEL_TEXT, binding_view hide = hide or (lambda _value: False) @@ -124,7 +130,10 @@ def actions_of(content: dict[str, Any], names: dict[str, str], hide: Any = None) "node_id": cand.get("node_id"), "workflow_name": names.get(str(cand.get("workflow_id") or "")), "level_text": LEVEL_TEXT.get(str(cand.get("level") or ""), ""), "needs_check": why is not None, "binding": binding_view(cand.get("binding"), hide), - "fallback": bool((cand.get("diff") or {}).get("fallback"))} + "fallback": bool((cand.get("diff") or {}).get("fallback")), + "fields": [{"name": str(f.get("name")), "required": bool(f.get("required")), + "has_default": bool(f.get("has_default"))} + for f in fields.get(cand.get("caliber")) or [] if f.get("name")]} if why is not None: item["check_reason"] = why out.append(item) @@ -141,11 +150,45 @@ async def reconciled_runs(session: Any, run_id: str) -> list[Run]: return list(rows) +#: 对账卡上一组对照的四个指标:id 的前缀(tail_nodes 的 _four)和名字的后缀 +_FOUR = (("ours", "这次"), ("caliber", "口径"), ("diff", "差值"), ("rel", "相对差")) +_PREFIX = {"ours": "ours_", "caliber": "cal_", "diff": "diff_", "rel": "rel_"} + + +def reconcile_groups(graph: Any) -> list[dict[str, str]]: + """对账运行的图里,对账卡上的每一组对照:{label, ours, caliber, diff, rel}(后四个是指标 id)。按卡上的先后;名字 + 是「<这一组的说法> · 这次」那样写的,label 去掉后缀。认不出的(不是派生的对账图)为空。""" + from app.ledger.derive import RECONCILE_CARD + + nodes = (graph or {}).get("nodes") if isinstance(graph, dict) else None + card = next((n for n in nodes or [] if isinstance(n, dict) and n.get("id") == RECONCILE_CARD + and n.get("type") == "metrics"), None) + metrics = (((card or {}).get("data") or {}).get("config") or {}).get("metrics") or [] + by_id = {str(m.get("id")): m for m in metrics if isinstance(m, dict) and m.get("id")} + out: list[dict[str, str]] = [] + for mid, metric in by_id.items(): + if not mid.startswith(_PREFIX["ours"]): + continue + n = mid[len(_PREFIX["ours"]):] + ids = {role: f"{_PREFIX[role]}{n}" for role, _ in _FOUR} + if not all(i in by_id for i in ids.values()): + continue + name = str(metric.get("name") or "") + label = name[:-len(" · 这次")] if name.endswith(" · 这次") else name + out.append({"label": label, **ids}) + return out + + def reconciled_view(run: Run) -> dict[str, Any]: + """GET 账本 reconciled 里的一项:哪一次对账运行、状态、对的哪条查询和哪份口径、参数从哪来;card 和 groups 是对账卡和 + 每一组对照的四个指标(界面按 /evidence/metrics/{card}/{指标} 取值、点开出处,不按命名规则自己拼)。""" + from app.ledger.derive import RECONCILE_CARD + origin = run.origin if isinstance(run.origin, dict) else {} return {"run_id": run.id, "status": run.status, "query": origin.get("query"), "caliber": origin.get("caliber"), "workflow_id": origin.get("workflow_id"), "version": origin.get("version"), "inputs_from": origin.get("inputs_from"), "rows": origin.get("rows"), + "card": RECONCILE_CARD, "groups": reconcile_groups(run.graph), "created_at": run.created_at.isoformat() if run.created_at else None} @@ -294,11 +337,16 @@ def plan_pairs(*, ours_columns: list[str], ours_rows: list[Any], hidden: set[str by_id = {str(m.get("id")): (i, m) for i, m in enumerate(metrics)} multi = len(ours_rows) > 1 + # 要人选对照时给界面的选项:这次结果里是数、没遮罩的列,口径卡上的指标(id、名字、单位) + numeric = [c for i, c in enumerate(ours_columns) if c.lower() not in hidden and _numeric(ours_rows, i)] + options = {"options": {"columns": numeric, + "metrics": [{"id": str(m.get("id")), "name": str(m.get("name") or m.get("id")), + "unit": str(m.get("unit") or "")} for m in metrics if m.get("id")]}} if multi: return _plan_rows(ours_columns, ours_rows, hidden, caliber_columns, referenced, check_column) if chosen is not None: if not isinstance(chosen, list) or not chosen or not all(isinstance(p, dict) for p in chosen): - raise ReconcileRefused(422, PAIRS_SHAPE, NEEDS_PAIRS) + raise ReconcileRefused(422, PAIRS_SHAPE, NEEDS_PAIRS, extra=options) pairs = [] for item in chosen: ours, metric = str(item.get("ours") or ""), str(item.get("metric") or "") @@ -310,7 +358,7 @@ def plan_pairs(*, ours_columns: list[str], ours_rows: list[Any], hidden: set[str unit=str(m.get("unit") or ""), decimals=m.get("decimals"))) return Plan(pairs=pairs) if fallback: - raise ReconcileRefused(409, PAIRS_FALLBACK, NEEDS_PAIRS) + raise ReconcileRefused(409, PAIRS_FALLBACK, NEEDS_PAIRS, extra=options) pairs = [] if caliber_columns is not None and len(caliber_columns) == len(ours_columns): for index, m in enumerate(metrics): @@ -323,7 +371,7 @@ def plan_pairs(*, ours_columns: list[str], ours_rows: list[Any], hidden: set[str pairs.append(Pair(ours=ours, metric=str(m.get("id")), index=index, name=str(m.get("name") or m.get("id")), unit=str(m.get("unit") or ""), decimals=m.get("decimals"))) if not pairs: - raise ReconcileRefused(409, PAIRS_NONE, NEEDS_PAIRS) + raise ReconcileRefused(409, PAIRS_NONE, NEEDS_PAIRS, extra=options) return Plan(pairs=pairs) @@ -521,4 +569,4 @@ def build(pinned: Any, *, sql: str, tool: str, plan: Plan, inputs: dict[str, Any __all__ = ["CHECK_INPUTS", "MAX_COLUMNS", "MAX_ROWS", "NEEDS_PAIRS", "ORIGIN", "REFUSED", "Pair", "Plan", "ReconcileRefused", "Request", "actions_of", "align_sql", "build", "plan_pairs", "reconcile", - "reconciled_runs", "reconciled_view", "tail_nodes"] + "reconcile_groups", "reconciled_runs", "reconciled_view", "tail_nodes"] diff --git a/backend/app/ledger/view.py b/backend/app/ledger/view.py index d1c8f356..81492c2b 100644 --- a/backend/app/ledger/view.py +++ b/backend/app/ledger/view.py @@ -116,6 +116,11 @@ async def run_view(run_id: str) -> dict[str, Any]: recorded = await store.latest(run_id) if recorded is None: why = ledger_match.ineligible(run) + if why == ledger_match.NOT_SEALED and run.status == "succeeded" \ + and ledger_match.wanted(run.run_class, run.origin_kind): + # runner 先发 run.finished、落库,再封存、再排上比对(engine/runner._finalize):页面收到 run.finished 立刻来取, + # 这一下还没封存。这不是「不比对」,是封存完就比——照实答 pending,页面按退避接着取;这里不另排按需比对 + return {**base, "state": "pending"} sealed = await _sealed(run_id) if why is None else None if sealed is not None and not sealed.queries: why = ledger_match.NO_QUERIES diff --git a/backend/tests/test_ledger_api.py b/backend/tests/test_ledger_api.py index 24cc969a..e70a6561 100644 --- a/backend/tests/test_ledger_api.py +++ b/backend/tests/test_ledger_api.py @@ -93,6 +93,30 @@ async def test_an_unmatched_run_is_matched_on_demand_and_says_it_looks_back(clie assert body["retro_note"] == "按现在的口径回看" +async def test_a_run_that_just_finished_and_is_about_to_be_sealed_is_pending(client, monkeypatch): + """runner 先发 run.finished、落库,再封存、再排上比对:页面收到 run.finished 立刻来取账本,这一下运行已经成功、还没封存。 + 这不是「不比对」,是「封存完就比」——照实答 pending(不在这里另排一次按需比对:runner 封存之后自己会排),页面按退避 + 接着取;真不比的(正式运行、失败的)照旧 ineligible。""" + await S.publish() + row = await S.explore(monkeypatch, S.EQUIVALENT, text="本周销售额 [[v:Q1.r0.销售额]]。") + await ledger_match.drain() + from app.db.models import Run + + async with SessionLocal() as session: + fresh = Run(workflow_name="刚跑完", status="succeeded", run_class="exploratory", origin_kind="chat", graph={}, + input={}, output={}) + failed = Run(workflow_name="失败了", status="failed", run_class="exploratory", origin_kind="chat", graph={}, + input={}, output={}) + session.add_all([fresh, failed]) + await session.commit() + fresh_id, failed_id = fresh.id, failed.id + scheduled: list[str] = [] + monkeypatch.setattr(ledger_match, "schedule", lambda run_id, **kw: scheduled.append(run_id) or True) + body = await ledger_of(client, fresh_id) + assert body["state"] == "pending" and scheduled == [], body + assert (await ledger_of(client, failed_id))["state"] == "ineligible" + + async def test_runs_that_are_not_compared_say_why(client, monkeypatch): row = await S.explore(monkeypatch, S.EQUIVALENT, origin="api", text="本周销售额 [[v:Q1.r0.销售额]]。") body = await ledger_of(client, row.id) diff --git a/backend/tests/test_ledger_reconcile.py b/backend/tests/test_ledger_reconcile.py index a14b5175..68beded9 100644 --- a/backend/tests/test_ledger_reconcile.py +++ b/backend/tests/test_ledger_reconcile.py @@ -248,3 +248,35 @@ async def test_users_read_their_reconcile_runs_only_through_the_evidence(client, assert (await carol.get(f"/api/runs/{done.id}/evidence")).status_code == 200 finally: await auth_env.reset() + + +async def test_the_reconcile_view_gives_the_panel_what_it_draws(client, monkeypatch): + """界面层不放逻辑(W4-c 账本前端):「看差多少」那一项带上口径的入口字段(核对参数的表单照它画:哪几项、必填、有没有 + 缺省值);认不出列怎么配时 409 另带可选的列和口径卡上的指标(选对照的那一步照它画);对过的账列出对账卡和每一组的 + 这次 / 口径 / 差值 / 相对差是哪几个指标(三个数各自点得开,界面不按命名规则去拼指标 id)。""" + wf = await S.publish(graph=S.caliber_graph(expression="cell(nodes.fetch, 0, 'gmv') * 1")) + row = await S.explore(monkeypatch, S.WITH_REFUNDS) + [action] = [a for a in (await ledger_of(client, row.id))["actions"] if a["kind"] == "reconcile"] + assert action["fields"] == [{"name": "start", "required": True, "has_default": False}, + {"name": "end", "required": True, "has_default": False}, + {"name": "store", "required": False, "has_default": True}] + body = {"query": action["query"], "workflow_id": wf, "version": 1, "inputs": CHECKED, "confirm": True} + res = await client.post(f"/api/ledger/answers/{row.id}/reconcile", json=body) + assert res.status_code == 409 and res.json()["code"] == ledger_reconcile.NEEDS_PAIRS + assert res.json()["options"] == {"columns": ["gmv"], "metrics": [{"id": "gmv", "name": "销售额", "unit": "元"}]} + done = await reconcile(client, row.id, {**body, "pairs": [{"ours": "gmv", "metric": "gmv"}]}) + [listed] = (await ledger_of(client, row.id))["reconciled"] + assert listed["run_id"] == done.id and listed["card"] == "reconcile" + assert listed["groups"] == [{"label": "销售额", "ours": "ours_0", "caliber": "cal_0", "diff": "diff_0", "rel": "rel_0"}] + + +async def test_multi_row_reconcile_groups_carry_the_row_labels(client, monkeypatch): + wf = await S.publish(graph=S.caliber_graph(BY_REGION)) + row = await S.explore(monkeypatch, BY_REGION_ALL, text="东区 [[v:Q1.r0.gmv]],西区 [[v:Q1.r1.gmv]]。") + [action] = [a for a in (await ledger_of(client, row.id))["actions"] if a["kind"] == "reconcile"] + await reconcile(client, row.id, {"query": action["query"], "workflow_id": wf, "version": 1, "inputs": CHECKED, + "confirm": True}) + [listed] = (await ledger_of(client, row.id))["reconciled"] + assert [g["label"] for g in listed["groups"]] == ["区域=east · gmv", "区域=west · gmv"] + assert listed["groups"][1] == {"label": "区域=west · gmv", "ours": "ours_1_0", "caliber": "cal_1_0", "diff": "diff_1_0", + "rel": "rel_1_0"} From b24aabefcf42d691eefbfaa44c181660d0af4da8 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 20:02:08 +0800 Subject: [PATCH 4/8] =?UTF-8?q?=E8=B4=A6=E6=9C=AC=E5=89=8D=E7=AB=AF?= =?UTF-8?q?=EF=BC=9A=E8=AF=81=E6=8D=AE=E3=80=8C=E5=8F=A3=E5=BE=84=E3=80=8D?= =?UTF-8?q?=E4=B8=80=E6=AD=A5=E3=80=81=E6=95=B0=E5=AD=97=E4=B8=8A=E7=9A=84?= =?UTF-8?q?=E5=B0=8F=E6=A0=87=E8=AE=B0=E3=80=81=E9=97=AE=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E8=BD=AE=E6=AC=A1=E6=91=98=E8=A6=81=E4=B8=8E=E5=87=BA=E5=85=B7?= =?UTF-8?q?=20/=20=E5=AF=B9=E8=B4=A6=E3=80=81=E5=8F=AF=E6=B2=89=E6=B7=80?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=E3=80=81=E8=AE=BE=E7=BD=AE=E9=87=8C?= =?UTF-8?q?=E7=9A=84=E5=8F=A3=E5=BE=84=E8=B4=A6=E6=9C=AC=E4=B8=80=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第 2、3 波只有接口,这一波接上界面(docs/design/next-round/02-口径账本.md 做法 3–6、8 的界面、做法 11;总方案 X3、X10)。 界面层不放逻辑:标签、整题判断、能不能出具、能不能自动、不能的原因、要不要先核对参数都照 GET /api/runs/{id}/ledger 给的画。 - 比对结果不靠实时流(第 2 波遗留):ledger.matched 在封存之后追加、事件总线已经关了,打开着的页面收不到。store/ledger 按退避轮询(1、2、3、5、8、13 秒,之后每 15 秒),服务端答 pending 时写「正在比对口径」,等满 2 分钟还没结论照实说、 给「再取一次」;要自动出具的再等出具的那一次出现,出具、对账的运行没结束的等它们结束。只在有组件看着时轮询,同一次 运行的正文、面板、轮次摘要共用一份 - 证据正文(EvidenceDoc):来自口径的数字后面挂一个小标记,写明受管 / 已发布,悬停写是哪一份口径、怎么认的;相关口径的 数不加标记 - 证据面板出处链最上面加「口径」一步(run/LedgerStep):来自口径——「X」v3(受管)· 参数 · 等价已证明 / 助手选用 · 按口径正式出具;相关口径——差在哪 + 看差多少;这次的推理——没有相关的已发布口径;没比对的写原因;脚注写「封存后比对, 不在封存范围内」,事后补比的写按哪种口径回看 - 口径对账(run/LedgerReconcile):核对参数(照动作里的入口字段画,推断的参数要先核对,遮罩值不回填)→ 发起(认不出列 怎么配时照 409 带回的选项选对照的指标)→ 结果卡片:每组按你的问法、按口径、差值(附相对差)各自点得开出处链 (apps/EvidenceDrawer,同应用页点数) - 问数据轮次底部(run/LedgerTurn):一行摘要(几个数来自口径「X」vN、几个是这次的推理、几个没有比对)、整题等价时按口径 正式出具(能自动的写正在自动出具;不能的照写原因,使用者没有应用授权写「请搭建者出具」)、有相关口径时对账;出具过的 正式运行挂在下面,档位写完整出具 / 降档出具 / 不予出具,搭建者点开去运行;回收站里的对话只看不发起 - 可沉淀的问题(pages/ledger/CertifyQueue):工作流列表弹窗里的抽屉,确定性重复、问题聚类、被反复用的答案分开写; 「固化成口径草稿」走 /copilot/from-run 的 freeze 并打开画布,聚类没有共同的 SQL、按人挑的那一轮固化;「不是口径」 要写理由 - 设置(pages/settings/LedgerSettings,照 VerifySettings):自动按口径正式出具、每日上限、比对时限、升版后每次最多重算几组, 和其余偏好共用保存条、整组写 ledger - 类型 typesLedger.ts、接口 api/caliberLedger.ts(挂 api.caliberLedger)、文案 lib/termsLedger.ts;types.ts 的证据片段 答复加 ledger、rendered 两个键 --- frontend/src/api/caliberLedger.ts | 37 ++ frontend/src/api/client.ts | 4 + frontend/src/canvas/WorkflowPicker.tsx | 22 +- frontend/src/lib/termsLedger.ts | 207 +++++++++++ frontend/src/pages/ChatPage.tsx | 18 +- frontend/src/pages/SettingsPage.tsx | 36 +- frontend/src/pages/ledger/CertifyQueue.tsx | 208 +++++++++++ .../src/pages/settings/LedgerSettings.tsx | 114 ++++++ frontend/src/run/EvidenceDoc.tsx | 61 +++- frontend/src/run/EvidencePanel.tsx | 12 + frontend/src/run/LedgerReconcile.tsx | 283 +++++++++++++++ frontend/src/run/LedgerStep.tsx | 325 ++++++++++++++++++ frontend/src/run/LedgerTurn.tsx | 104 ++++++ frontend/src/store/ledger.ts | 180 ++++++++++ frontend/src/types.ts | 7 + frontend/src/typesLedger.ts | 321 +++++++++++++++++ 16 files changed, 1917 insertions(+), 22 deletions(-) create mode 100644 frontend/src/api/caliberLedger.ts create mode 100644 frontend/src/lib/termsLedger.ts create mode 100644 frontend/src/pages/ledger/CertifyQueue.tsx create mode 100644 frontend/src/pages/settings/LedgerSettings.tsx create mode 100644 frontend/src/run/LedgerReconcile.tsx create mode 100644 frontend/src/run/LedgerStep.tsx create mode 100644 frontend/src/run/LedgerTurn.tsx create mode 100644 frontend/src/store/ledger.ts create mode 100644 frontend/src/typesLedger.ts diff --git a/frontend/src/api/caliberLedger.ts b/frontend/src/api/caliberLedger.ts new file mode 100644 index 00000000..5e9b8cf6 --- /dev/null +++ b/frontend/src/api/caliberLedger.ts @@ -0,0 +1,37 @@ +/** + * 口径账本的接口(docs/design/next-round/02-口径账本.md),挂在 api.caliberLedger 上。形状见 typesLedger.ts。 + * + * - run:GET /api/runs/{id}/ledger,一次运行里每个数的口径标签、整题判断、能做的动作、出具过的正式运行、对过的账; + * - issue:按口径正式出具(参数只由服务端从比对工件里取,这里只能选「按哪份口径」); + * - reconcile:口径对账(点开才跑一次确定性派生的只读图); + * - certifyQueue / dismiss:可沉淀的问题、「不是口径」(搭建者及以上); + * - freeze:固化成口径草稿(/copilot/from-run 的 freeze 选项,报告引用的查询变成固定 SQL 的取数节点)。 + * + * 应用平台的「账本」(版本被哪些应用固定、生效记录)在 api.ledger(api/apps.ts),和这里不是一回事。 + * 请求函数从 ./http 导入,不从 ./client 导入(client.ts 要导入这个文件,反过来就成了循环)。 + */ +import type { + CertifyQueue, FreezeOut, LedgerIssueOut, LedgerReconcileIn, LedgerReconcileOut, RunLedger, +} from '../typesLedger' +import { get, post, type RequestOptions } from './http' + +const at = (runId: string) => `/ledger/answers/${encodeURIComponent(runId)}` + +export const caliberLedger = { + run: (runId: string, opts?: RequestOptions) => get(`/runs/${encodeURIComponent(runId)}/ledger`, opts), + issue: (runId: string, body: { workflow_id: string; version: number }) => post(`${at(runId)}/issue`, body), + reconcile: (runId: string, body: LedgerReconcileIn) => post(`${at(runId)}/reconcile`, body), + certifyQueue: (opts?: RequestOptions) => get('/ledger/certify-queue', opts), + dismiss: (body: { item_id: string; kind?: string; note: string }) => + post<{ ok: boolean; item_id: string }>('/ledger/certify-queue/dismiss', body), + /** + * 固化成口径草稿:代表运行里报告引用了的查询变成固定 SQL 的取数节点,peers(同一个 SQL 形状的别的运行)用来认哪些字面量 + * 跨轮变了。落成新的草稿工作流,人在画布上审改、按受管级别发布 + */ + freeze: (runId: string, opts: { peers?: string[]; conversation_id?: string | null; turn_id?: string | null } = {}) => + post('/copilot/from-run', { + run_id: runId, freeze: true, peers: opts.peers ?? [], + ...(opts.conversation_id ? { conversation_id: opts.conversation_id } : {}), + ...(opts.turn_id ? { turn_id: opts.turn_id } : {}), + }), +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index d37f2e4b..f81cda84 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -30,6 +30,8 @@ import { apps, ledger } from './apps' import { actions, tasks } from './tasks' import { auth, identity } from './auth' import { accessKeys } from './accessKeys' +// 口径账本(下一轮第 4 波 W4-c):问数据答案的口径标签、按口径出具、对账、可沉淀的问题 +import { caliberLedger } from './caliberLedger' import { capabilities, endpoints, notify } from './capabilities' // 普通用户建应用(typesBlueprint.ts 是接口约定) import { blueprints, files, personal, templates } from './blueprints' @@ -963,6 +965,8 @@ export const api = { identity, // 访问密钥与服务账号(下一轮第 2 波) accessKeys, + // 口径账本:答案里每个数的口径标签、按口径正式出具、口径对账、可沉淀的问题(typesLedger.ts 是接口约定) + caliberLedger, capabilities, endpoints, notify, diff --git a/frontend/src/canvas/WorkflowPicker.tsx b/frontend/src/canvas/WorkflowPicker.tsx index 17bc205f..1d60e568 100644 --- a/frontend/src/canvas/WorkflowPicker.tsx +++ b/frontend/src/canvas/WorkflowPicker.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' -import { Check, Copy, LayoutTemplate, Plus, Search, Trash2, Workflow as WorkflowIcon } from 'lucide-react' +import { Check, Copy, Layers, LayoutTemplate, Plus, Search, Trash2, Workflow as WorkflowIcon } from 'lucide-react' import clsx from 'clsx' import { api } from '../api/client' import { useCatalog } from '../store/catalog' @@ -11,6 +11,9 @@ import { formatShortcut } from '../lib/keys' import { leavePass, registerLeaveGuard } from '../lib/leave' import { WORKFLOW_STATUS_LABEL, publishedLevelOf } from '../lib/terms' import type { GraphSpec, Workflow } from '../types' +import { useAtLeast } from '../store/auth' +import { LEDGER_UI } from '../lib/termsLedger' +import { CertifyQueue } from '../pages/ledger/CertifyQueue' /** 标签的中文。后端写的是机器标记,和中文界面混排很突兀 */ const TAG_LABEL: Record = { extracted: '从运行提取', template: '模板' } @@ -192,8 +195,11 @@ export function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () = const [filter, setFilter] = useState('all') const [cursor, setCursor] = useState(0) const listRef = useRef(null) + // 「可沉淀的问题」抽屉(口径账本的认证队列,搭建者及以上):盖在列表上,返回回到列表 + const [queue, setQueue] = useState(false) + const builder = useAtLeast('builder') - useEffect(() => { if (open) { setQuery(''); setCursor(0) } }, [open]) + useEffect(() => { if (open) { setQuery(''); setCursor(0); setQueue(false) } }, [open]) const shown = useMemo(() => { const q = query.trim().toLowerCase() @@ -267,13 +273,14 @@ export function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () = } return ( - + ↑↓ 选择 · {formatShortcut('Enter')} 打开 · Esc 关闭 }> + {queue ? setQueue(false)} onClose={onClose} beforeLeave={confirmDiscard} /> : <>
@@ -302,6 +309,12 @@ export function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () = ))}
+ {builder && ( + + )}
{!shown.length ? ( @@ -369,6 +382,7 @@ export function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () = })} )} + }
) } diff --git a/frontend/src/lib/termsLedger.ts b/frontend/src/lib/termsLedger.ts new file mode 100644 index 00000000..20543f3d --- /dev/null +++ b/frontend/src/lib/termsLedger.ts @@ -0,0 +1,207 @@ +/** + * 口径账本的界面文案(docs/design/next-round/02-口径账本.md 做法 3–6、8 的界面部分;总方案 X10):证据正文里数字上的 + * 小标记、证据面板的「口径」一步、问数据轮次底部的摘要和动作、口径对账、可沉淀的问题、设置里的口径账本一组。 + * + * 叫法:来自口径(受管 / 已发布)· 等价已证明 / 助手选用、相关口径、这次的推理、口径对账、可沉淀的问题;出具档位沿用 + * 「完整出具 / 降档出具 / 不予出具」(服务端给 tier_text);版本写「固定版本」。标签四种、认法两种、级别两种的叫法在 + * terms.ts 的 LEDGER_TEXT(时间线那一行同一套),这里不重写。规矩同 terms.ts 开头的术语表。 + */ +import { formatNumber } from './format' + +/** 口径的写法:「周销售」v3(受管) */ +export const caliberName = (name: string | null | undefined, version: number | null | undefined, level?: string) => + `「${name || '未命名'}」${version != null ? `v${version}` : ''}${level ? `(${level})` : ''}` + +export const LEDGER_UI = { + // ---- 证据正文:来自口径的数字上的小标记 ---- + mark: { + /** 标记上的字就是级别(受管 / 已发布);相关口径的数不加标记,只在面板里说 */ + title: (caliber: string, how: string) => `来自口径${caliber} · ${how}`, + aria: (caliber: string, how: string) => `,来自口径${caliber},${how}`, + }, + + // ---- 证据面板最上面的「口径」一步 ---- + step: { + title: '口径', + pending: '正在比对口径…', + pendingSub: '运行封存后在后台和已发布口径比对,比完这里会自动更新', + timeout: '比对口径还没有结果:可能在排队,或比对超过了时限', + retry: '再取一次', + failed: '无法读取口径比对', + unreadable: (reason: string) => `口径比对记录无法读取${reason ? `:${reason}` : ''}`, + params: '参数', + noParams: '没有参数', + masked: '已遮罩', + column: (c: string) => `对应口径里的列「${c}」`, + how: { + independent: '这次 Agent 独立写的 SQL 被证明和这份口径的取数等价', + composed: '助手按问法选用了这份口径,取数照那一版生成;这份口径答的是不是这个问题,要由人确认', + }, + relatedSub: '这个数是这次的推理,下面这份已发布口径和它相关', + where: '差在哪', + noDiff: '没有归纳出具体差异', + fallback: '两条 SQL 的结构对不上,未能归纳成具体差异,请对照原文', + notComparable: '这份口径不能对账', + reasoningSub: '没有相关的已发布口径', + unknownSub: '没有和已发布口径比对', + }, + + // ---- 按口径正式出具(整题等价时) ---- + issue: { + button: '按口径正式出具', + busy: '正在发起…', + /** 服务端判了能自动出具:比对完就自动发起,这里不另给按钮 */ + auto: '整题等价于这份口径,已在按口径自动正式出具', + autoWaiting: '正在按口径自动出具…', + autoTimeout: '自动出具的正式运行还没有出现,可以手动发起', + launched: (caliber: string) => `已按口径${caliber}发起正式运行`, + again: (caliber: string) => `已经按口径${caliber}出具过同样参数的这一次`, + issuedRun: '已出具', + readOnly: '对话在回收站中,恢复后才能出具', + }, + /** 出具过的正式运行,挂在轮次下面 */ + issued: { + title: (auto: boolean) => (auto ? '按口径自动出具' : '按口径正式出具'), + running: '正式运行进行中', + rejected: '被驳回', + failed: '正式运行没有完成', + cancelled: '已取消', + open: '打开运行', + /** 使用者读不了正式运行的原始记录(记录页只给搭建者) */ + userNote: '正式运行的记录由搭建者在记录页查看', + }, + + // ---- 口径对账 ---- + reconcile: { + button: '看差多少', + turnButton: (caliber: string) => `对账:${caliber}`, + title: (caliber: string) => `口径对账:${caliber}`, + intro: '按你的问法和按口径,在同一份数据上各算一次,差值在对账卡里算。只读,不写任何数据', + where: '差在哪', + params: '核对参数', + paramsHint: '参数按这次的 SQL 推断,请核对', + paramsFixed: '参数取自比对时绑定出来的值', + editParams: '修改参数', + required: '必填', + defaulted: '留空用口径的缺省值', + maskedPlaceholder: '已遮罩,请重新填写', + pairs: '选择要对照的指标', + pairsHint: '认不出这次的哪一列对应口径的哪个指标,请为要对照的列选一个口径卡上的指标', + pairNone: '不对照', + pairEmpty: '至少选一组对照', + launch: '发起对账', + busy: '正在发起…', + cancel: '取消', + launched: '已发起对账,结果在下面', + readOnly: '对话在回收站中,恢复后才能对账', + }, + /** 对账的结果卡片 */ + result: { + title: (caliber: string) => `口径对账 · ${caliber}`, + running: '对账进行中…', + failed: '对账没有完成', + cancelled: '对账已取消', + inputs: { binding: '按比对时推断的参数', checked: '按核对过的参数' } as Record, + ours: '按你的问法', + caliber: '按口径', + diff: '差值', + rel: '相对差', + loading: '正在取值…', + noValue: '取值失败', + open: (what: string, label: string) => `${label} · ${what}:点开看出处`, + more: (n: number) => `展开其余 ${formatNumber(n)} 组`, + less: '收起', + original: (text: string) => `原答案里写的是 ${text};对账时按同样的 SQL 重新取数,数据有变化时两者可能不同`, + openRun: '打开对账运行', + }, + + // ---- 问数据:轮次底部的摘要 ---- + turn: { + pending: '正在比对口径…', + timeout: '比对口径还没有结果', + /** 一行摘要:几个数来自哪份口径、几个是这次的推理、几个没有比对 */ + summary: (parts: { caliber: number; calibers: string[]; reasoning: number; related: number; unknown: number }) => { + const out: string[] = [] + if (parts.caliber) { + out.push(parts.calibers.length === 1 ? `${formatNumber(parts.caliber)} 个数来自口径${parts.calibers[0]}` + : `${formatNumber(parts.caliber)} 个数来自 ${formatNumber(parts.calibers.length)} 份口径`) + } + const reasoning = parts.reasoning + parts.related + if (reasoning) { + out.push(`${formatNumber(reasoning)} 个数是这次的推理${parts.related ? `(其中 ${formatNumber(parts.related)} 个有相关口径)` : ''}`) + } + if (parts.unknown) out.push(`${formatNumber(parts.unknown)} 个数没有比对`) + return out.join(',') + }, + whole: (caliber: string, how: string) => `整题等价于口径${caliber} · ${how}`, + label: '口径', + }, + + // ---- 工作流列表页:可沉淀的问题 ---- + certify: { + open: '可沉淀的问题', + openHint: '被反复问到、反复写出同样查询的问题:固化成口径草稿,人审后发布,以后再问就认得出等价', + back: '返回工作流列表', + title: '可沉淀的问题', + intro: '三类来源分开列出。固化成口径草稿会新建一张草稿工作流(报告引用的查询变成固定 SQL 的取数节点),在画布上审改、按受管级别发布后才生效', + kinds: { + shape: '确定性重复:同样形状的 SQL', + cluster: '问题聚类:问法相近的问题', + reused: '被反复用的答案', + } as Record, + kindHint: { + shape: '问数据里执行过、被报告引用、又没有对上任何口径的查询,按数据源和规范化后的 SQL 分组:出现在多次运行、多段对话里', + cluster: '只按问题原文聚类(不含对话历史),问法相近不等于口径相同,固化前请确认是同一个问题', + reused: '导出过多次、做成过应用、在画布里打开或提取过的答案', + } as Record, + empty: '暂时没有可沉淀的问题', + emptyBody: (runs: number) => `看了最近 ${formatNumber(runs)} 次问数据的运行,没有达到门槛的重复`, + threshold: (runs: number, conversations: number) => `门槛:同一形状出现在 ${formatNumber(runs)} 次以上运行、来自 ${formatNumber(conversations)} 段以上对话`, + shapeStats: (runs: number, conversations: number) => `${formatNumber(runs)} 次运行 · ${formatNumber(conversations)} 段对话`, + params: (p: number, c: number) => `${formatNumber(p)} 个参数候选 · ${formatNumber(c)} 个口径常量`, + clusterStats: (n: number) => `${formatNumber(n)} 个相近的问题`, + uses: (u: { exports: number; app: boolean; extracted: boolean; canvas: boolean }) => [ + u.exports ? `导出 ${formatNumber(u.exports)} 次` : '', u.app ? '做成过应用' : '', u.extracted ? '提取过模板' : '', + u.canvas ? '在画布里打开过' : '', + ].filter(Boolean).join(' · '), + source: (s: string) => `数据源 ${s}`, + shape: 'SQL 形状(取值已换成「?」)', + related: '已有相关口径', + frozen: '已固化成', + turns: '来自这些轮次', + openTurn: '打开对话', + openRun: '打开运行', + freeze: '固化成口径草稿', + freezeTurn: '按这一轮固化', + freezeBusy: '正在固化…', + frozenOk: (name: string) => `已固化成草稿「${name}」,在画布里审改后发布`, + dismiss: '不是口径', + dismissTitle: '这不是口径', + dismissLabel: '理由', + dismissPlaceholder: '例如:每次问的是不同门店的临时核对,不需要固定下来', + dismissNeed: '请写明理由', + dismissConfirm: '确认不是口径', + dismissed: '已记下,这一项不再出现', + noRun: '这一项没有可固化的运行', + loadFailed: '无法读取可沉淀的问题', + }, + + // ---- 设置:口径账本一组 ---- + settings: { + title: '口径账本', + hint: '问数据的答案封存后在后台和已发布口径比对:按口径正式出具、口径对账、升版后的召回都按这里的设置', + autoIssue: '自动按口径正式出具', + autoIssueHint: '问数据的答案整题等价于受管口径(Agent 独立写的 SQL 被证明等价、图里没有人工节点和写入)时自动发起一次正式运行;不满足的只给一键出具', + dailyLimit: '按口径正式出具每日上限', + dailyLimitHint: '自动的、一键的合计;0 表示不再按口径出具。正式运行含报告撰写的模型费用', + timeout: '口径比对时限(秒)', + timeoutHint: '一次运行的口径比对最多算这么久,超时的照实记没比完', + recallLimit: '口径升版后每次最多重算几组', + recallLimitHint: '发布新版本后自动重算受影响的答案,按参数去重成组;超出的写明另有几组未重算;0 表示不自动重算', + invalid: { + limit: (max: number) => `请填写 0 到 ${formatNumber(max)} 之间的整数`, + timeout: (lo: number, hi: number) => `请填写 ${lo} 到 ${hi} 之间的秒数`, + }, + saveInvalid: '口径账本的设置中有无效值,请修正后再保存', + }, +} diff --git a/frontend/src/pages/ChatPage.tsx b/frontend/src/pages/ChatPage.tsx index 5ea4aed0..d3790806 100644 --- a/frontend/src/pages/ChatPage.tsx +++ b/frontend/src/pages/ChatPage.tsx @@ -11,6 +11,7 @@ import { AssistantStream, type StreamTurn, type TurnFailure } from '../run/Assis import { PromptBox } from '../run/Composer' import { decodeCopilot, decodeRun, exitLabels } from '../run/decode' import { catalogPatchesOf } from '../run/catalogPatch' +import { LedgerTurn } from '../run/LedgerTurn' import { sourceHandles } from '../canvas/nodeDefs' import { isComposing, PageHeader, Skeleton, Spinner, StatusBadge, TechDetails, toast } from '../components/ui' import { humanizeError } from '../lib/errors' @@ -294,10 +295,19 @@ export function ChatPage() { approvalsFor={(t) => } renderTurnActions={(t) => { const turn = turns?.find((x) => x.id === t.id) - return currentId && turn && hasRemedies(turn) - ? - : null + if (!currentId || !turn) return null + // 轮次底部:口径账本的摘要和动作(交付了的轮次才有:封存后在后台比对,见 run/LedgerTurn),再是补救动作 + const ledger = turn.phase === 'done' && !!turn.run?.id && !turn.asked + if (!ledger && !hasRemedies(turn)) return null + return ( + <> + {ledger && } + {hasRemedies(turn) && ( + + )} + + ) }} onFollowUp={(text) => { // 追问是从表格里派生的一句话,点了就问;这会儿发不出去就先放进输入框 diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx index a058f038..31ff84e5 100644 --- a/frontend/src/pages/SettingsPage.tsx +++ b/frontend/src/pages/SettingsPage.tsx @@ -38,6 +38,10 @@ import { IdentityTab } from './settings/IdentityTab' import { NotifyTab } from './settings/NotifyTab' import { AuditTab } from './settings/AuditTab' import { AccessKeysTab } from './settings/AccessKeysTab' +import { + LedgerSection, ledgerChanged, ledgerDraftOf, ledgerErrors, ledgerLabels, ledgerPayload, type LedgerDraft, +} from './settings/LedgerSettings' +import { LEDGER_UI } from '../lib/termsLedger' import { ACCESS_KEY_TEXT } from '../lib/termsApp' // 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上。 @@ -689,6 +693,8 @@ function PrefsTab() { // 核查一组(双盲复算、反方审稿、审批质询)的草稿另放一份,和上面的共用保存条;verifySaves 是存过几次,今日核查花费跟着再取 const [verifyDraft, setVerifyDraft] = useState(null) const [verifySaves, setVerifySaves] = useState(0) + // 口径账本一组(自动按口径出具、每日上限、比对时限、升版后重算几组,pages/settings/LedgerSettings):草稿另放一份,共用保存条 + const [ledgerDraft, setLedgerDraft] = useState(null) const [saving, setSaving] = useState(false) const [savedFlash, setSavedFlash] = useState(0) const [saveError, setSaveError] = useState(null) @@ -778,9 +784,14 @@ function PrefsTab() { const verifyKeys = verifyChanged(verifyCur, verifySaved) const verifyErrs = verifyErrors(verifyCur, verifySaved) const verifyInvalid = Object.values(verifyErrs).some(Boolean) - const invalid = guardInvalid || judgeInvalid || verifyInvalid || !!appsError + const ledgerSaved = ledgerDraftOf(values?.ledger) + const ledgerCur = ledgerDraft ?? ledgerSaved + const ledgerKeys = values?.ledger ? ledgerChanged(ledgerCur, ledgerSaved) : [] + const ledgerErrs = ledgerErrors(ledgerCur, ledgerSaved) + const ledgerInvalid = Object.values(ledgerErrs).some(Boolean) + const invalid = guardInvalid || judgeInvalid || verifyInvalid || ledgerInvalid || !!appsError const changed = (Object.keys(saved) as (keyof typeof saved)[]).filter((k) => cur[k] !== saved[k]) - const dirty = values ? changed.length + verifyKeys.length : 0 + const dirty = values ? changed.length + verifyKeys.length + ledgerKeys.length : 0 // 外壳唯一的 blocker 在地址(pathname)变化时问:切标签、导航、⌘K、⌥ 数字、后退都算 useLeaveGuard(dirty > 0, () => confirmLeave(dirty)) @@ -800,6 +811,11 @@ function PrefsTab() { setFieldError(null) setVerifyDraft({ ...verifyCur, ...patch }) } + const editLedger = (patch: Partial) => { + setSaveError(null) + setFieldError(null) + setLedgerDraft({ ...ledgerCur, ...patch }) + } /** * 署名只在这台浏览器里,先落本机:它不该跟着后端一起「没存上」。运行默认值 @@ -833,6 +849,8 @@ function PrefsTab() { } : null // 核查一组同样整组写(VerifySettings 的 verifyPayload) const verify = verifyKeys.length ? verifyPayload(verifyCur) : null + // 口径账本一组同样整组写(LedgerSettings 的 ledgerPayload) + const ledger = ledgerKeys.length ? ledgerPayload(ledgerCur) : null // 起草模型一组:两项一起写,空着的存 null(跟随助手的模型) const catalogDraft = draftChanged ? { provider: cur.draftProvider || null, model: cur.draftModel.trim() || null } : null // 应用一组同样整组写:别的键(以后加的)照原样带回去 @@ -840,7 +858,7 @@ function PrefsTab() { ? { ...(values.apps ?? {}), on_demand_daily_limit: Number(cur.appsDaily.trim()), user_personal_apps: cur.appsPersonal, share_links: cur.appsShare } : null - if (runChanged || judge || verify || catalogDraft || apps) { + if (runChanged || judge || verify || ledger || catalogDraft || apps) { const run = { ...(values.run ?? {}), default_memory_scope: cur.scope, @@ -854,6 +872,7 @@ function PrefsTab() { } const out = await api.settings.put({ ...(runChanged ? { run } : {}), ...(judge ? { judge } : {}), ...(verify ? { verify } : {}), + ...(ledger ? { ledger } : {}), ...(catalogDraft ? { catalog_draft: catalogDraft } : {}), ...(apps ? { apps } : {}), }) setValues((v) => ({ @@ -861,6 +880,7 @@ function PrefsTab() { ...(runChanged ? { run: out?.run ?? run } : {}), ...(judge ? { judge: out?.judge ?? judge } : {}), ...(verify ? { verify: out?.verify ?? verify } : {}), + ...(ledger ? { ledger: out?.ledger ?? ledger } : {}), ...(catalogDraft ? { catalog_draft: out?.catalog_draft ?? catalogDraft } : {}), ...(apps ? { apps: out?.apps ?? apps } : {}), })) @@ -870,6 +890,7 @@ function PrefsTab() { } setDraft(null) setVerifyDraft(null) + setLedgerDraft(null) setSavedFlash(Date.now()) } catch (e) { // 署名已经存上了:留在草稿里的只剩运行默认值,条上的计数跟着变少 @@ -1180,6 +1201,8 @@ function PrefsTab() { {values.verify && } + {values.ledger && } + {values.catalog_draft && ( @@ -1244,7 +1267,7 @@ function PrefsTab() { draftProvider: DRAFT_MODEL_SETTING_TEXT.provider, draftModel: DRAFT_MODEL_SETTING_TEXT.model, appsDaily: APP_SETTING_TEXT.onDemandLimit, appsPersonal: APP_SETTING_TEXT.personalApps, appsShare: APP_SETTING_TEXT.shareLinks, - })[k]).concat(verifyLabels(verifyKeys)).join('、')} + })[k]).concat(verifyLabels(verifyKeys), ledgerLabels(ledgerKeys)).join('、')} {saveError != null && ( @@ -1255,12 +1278,13 @@ function PrefsTab() { )} + onClick={() => { setDraft(null); setVerifyDraft(null); setLedgerDraft(null); setSaveError(null); setFieldError(null) }}>放弃 diff --git a/frontend/src/pages/ledger/CertifyQueue.tsx b/frontend/src/pages/ledger/CertifyQueue.tsx new file mode 100644 index 00000000..be549d25 --- /dev/null +++ b/frontend/src/pages/ledger/CertifyQueue.tsx @@ -0,0 +1,208 @@ +import { useEffect, useState } from 'react' +import { Link, useNavigate } from 'react-router-dom' +import { ChevronLeft, Layers, Sparkles, X } from 'lucide-react' +import { api } from '../../api/client' +import { EmptyState, ErrorState, Skeleton, Spinner, promptDialog, toast } from '../../components/ui' +import { leavePass } from '../../lib/leave' +import { LEDGER_UI, caliberName } from '../../lib/termsLedger' +import { LEDGER_TEXT } from '../../lib/terms' +import { useCatalog } from '../../store/catalog' +import type { CertifyItem, CertifyQueue as Queue, CertifyTurn } from '../../typesLedger' + +/** + * 可沉淀的问题(认证队列,docs/design/next-round/02-口径账本.md 做法 8;服务端 app/ledger/certify.py):工作流列表页 + * (编排页的「工作流」弹窗)里的一个抽屉。 + * + * 同一类问题被反复问、Agent 反复写出同一个形状的 SQL,就该沉淀成一份口径:以后再问,比对器认得出「等价已证明」,还能按 + * 口径正式出具。三类来源照实分开写——确定性重复(同样形状的 SQL)、问题聚类(只按问题原文,问法相近不等于口径相同)、 + * 被反复用的答案——门槛、计数都是服务端给的。 + * + * - 固化成口径草稿:走 /copilot/from-run 的 freeze(报告引用的查询变成固定 SQL 的取数节点,跨轮变化的字面量成为参数), + * 落成新的草稿工作流,打开画布让人审改、按受管级别发布——提取器是作者,不是发布者。确定性重复的带上同组的别的运行 + * (认哪些字面量变了);问题聚类没有共同的 SQL,按人挑的那一轮固化。 + * - 不是口径:要写理由(记一条审计 ledger.certify.dismiss),之后这一项不再进队。 + */ + +const ORDER: CertifyItem['kind'][] = ['shape', 'cluster', 'reused'] + +/** 一轮在哪看:有对话的打开对话,没有的打开运行 */ +const turnHref = (t: CertifyTurn) => (t.conversation_id ? `/chat/${t.conversation_id}` : t.run_id ? `/runs/${t.run_id}` : null) + +export function CertifyQueue({ onBack, onClose, beforeLeave }: { + onBack: () => void + /** 打开了固化出的草稿:关掉外面的弹窗 */ + onClose: () => void + /** 去画布之前问一句(画布上有没保存的改动时);返回 false 就不去 */ + beforeLeave: () => Promise +}) { + const navigate = useNavigate() + const refreshCatalog = useCatalog((s) => s.refresh) + const workflows = useCatalog((s) => s.workflows) + const [queue, setQueue] = useState(null) + const [error, setError] = useState(null) + const [busy, setBusy] = useState(null) + + const load = () => { + setError(null) + setQueue(null) + api.caliberLedger.certifyQueue().then(setQueue, setError) + } + useEffect(load, []) + + const nameOf = (r: NonNullable[number]) => { + const level = r.level ? (LEDGER_TEXT.level as Record)[r.level] ?? '' : '' + return caliberName(workflows.find((w) => w.id === r.workflow_id)?.name ?? r.workflow_id, r.version, level) + } + + const freeze = async (item: CertifyItem, turn?: CertifyTurn) => { + const runId = turn?.run_id ?? item.representative?.run_id + if (!runId) { toast.warn(LEDGER_UI.certify.noRun); return } + if (!(await beforeLeave())) return + const first = turn ?? item.turns.find((t) => t.run_id === runId) ?? item.turns[0] + setBusy(`${item.id}:${runId}`) + try { + const out = await api.caliberLedger.freeze(runId, { + peers: !turn && item.kind === 'shape' ? item.peers ?? [] : [], + conversation_id: first?.conversation_id, turn_id: first?.turn_id, + }) + toast.ok(LEDGER_UI.certify.frozenOk(out.name)) + void refreshCatalog() + onClose() + navigate(`/studio/${out.workflow_id}`, leavePass({ state: { discard: true } })) + } catch (e) { + toast.error(e) + } finally { + setBusy(null) + } + } + + const dismiss = async (item: CertifyItem) => { + const note = await promptDialog({ + title: LEDGER_UI.certify.dismissTitle, label: LEDGER_UI.certify.dismissLabel, + placeholder: LEDGER_UI.certify.dismissPlaceholder, confirmLabel: LEDGER_UI.certify.dismissConfirm, + validate: (v) => (v.trim() ? null : LEDGER_UI.certify.dismissNeed), + }) + if (note == null || !note.trim()) return + setBusy(`${item.id}:dismiss`) + try { + await api.caliberLedger.dismiss({ item_id: item.id, kind: item.kind, note: note.trim() }) + setQueue((q) => (q ? { ...q, items: q.items.filter((i) => i.id !== item.id) } : q)) + toast.ok(LEDGER_UI.certify.dismissed) + } catch (e) { + toast.error(e) + } finally { + setBusy(null) + } + } + + const C = LEDGER_UI.certify + const groups = ORDER.map((kind) => ({ kind, items: (queue?.items ?? []).filter((i) => i.kind === kind) })) + .filter((g) => g.items.length) + + return ( +
+
+ +
+

{C.intro}

+ {error ? + : !queue ? + : !groups.length ? ( + } title={C.empty} + body={<>{C.emptyBody(queue.considered.runs)}
{C.threshold(queue.threshold.runs, queue.threshold.conversations)}} /> + ) : ( +
+ {groups.map((g) => ( +
+

{C.kinds[g.kind]} {g.items.length}

+

{C.kindHint[g.kind]}

+
    + {g.items.map((item) => ( +
  • +
    +
    +
    {item.question || '—'}
    +
    + {item.kind === 'shape' && [ + C.shapeStats(item.runs ?? 0, item.conversations ?? 0), + C.params(item.params?.length ?? 0, item.constants ?? 0), + item.source ? C.source(item.source) : '', + ].filter(Boolean).join(' · ')} + {item.kind === 'cluster' && C.clusterStats(item.count ?? item.turns.length)} + {item.kind === 'reused' && item.uses && C.uses(item.uses)} +
    +
    +
    + {item.kind !== 'cluster' && ( + + )} + +
    +
    + {item.kind === 'shape' && item.shape && ( +
    + {C.shape} +
    {item.shape}
    +
    + )} + {!!item.related?.length && ( +

    + {C.related}:{item.related.map(nameOf).join('、')} +

    + )} + {!!item.frozen_into?.length && ( +

    + {C.frozen} + {item.frozen_into.map((w) => ( + 「{w.name}」 + ))} +

    + )} + {!!item.turns.length && ( +
    + {C.turns}({item.turns.length}) +
      + {item.turns.map((t, i) => { + const href = turnHref(t) + return ( +
    • + {t.question || '—'} + {href && ( + + {t.conversation_id ? C.openTurn : C.openRun} + + )} + {item.kind === 'cluster' && t.run_id && ( + + )} +
    • + ) + })} +
    +
    + )} +
  • + ))} +
+
+ ))} +
+ )} +
+ ) +} diff --git a/frontend/src/pages/settings/LedgerSettings.tsx b/frontend/src/pages/settings/LedgerSettings.tsx new file mode 100644 index 00000000..476caa28 --- /dev/null +++ b/frontend/src/pages/settings/LedgerSettings.tsx @@ -0,0 +1,114 @@ +import { Field, SectionBar } from '../../components/ui' +import { LEDGER_UI } from '../../lib/termsLedger' + +/* + * 设置页「偏好设置」里「口径账本」一节(服务端 api/settings.py 的 ledger 一组,docs/design/next-round/02-口径账本.md + * 做法 5、7):自动按口径正式出具的开关、每日上限、比对时限、口径升版后每次最多重算几组。 + * + * 照 VerifySettings.tsx 的写法:草稿由 PrefsTab 持有、和其余设置共用一条保存条(这一节只画、只报改动),存的时候整组写 + * ledger——服务端对没给的项回落到默认值,只发改过的那一项会把别的项冲回默认。字段名就是服务端 LEDGER_SETTING_LABEL 的 + * 叫法,422 的报错写的也是它。范围同服务端(ledger_problem):每日上限 0 到 100,000、重算组数 0 到 1,000、时限 1 到 60 秒。 + */ + +const S = LEDGER_UI.settings + +/** 范围:同服务端 settings.APPS_DAILY_LIMIT_MAX、LEDGER_RECALL_MAX、LEDGER_TIMEOUT_RANGE */ +const DAILY_MAX = 100_000 +const RECALL_MAX = 1000 +const TIMEOUT_RANGE = [1, 60] as const + +export interface LedgerDraft { + auto_issue: boolean + issue_daily_limit: string + match_timeout_s: string + recall_limit: string +} +export type LedgerKey = keyof LedgerDraft + +const LABEL: Record = { + auto_issue: S.autoIssue, issue_daily_limit: S.dailyLimit, match_timeout_s: S.timeout, recall_limit: S.recallLimit, +} + +const isRecord = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) +const text = (v: unknown, fallback: string) => (typeof v === 'number' && Number.isFinite(v) ? String(v) : fallback) + +/** GET /settings 的 ledger 一组(服务端给的是生效的样子,没存过的补了默认)→ 草稿 */ +export function ledgerDraftOf(group: unknown): LedgerDraft { + const g = isRecord(group) ? group : {} + return { + auto_issue: g.auto_issue !== false, + issue_daily_limit: text(g.issue_daily_limit, ''), + match_timeout_s: text(g.match_timeout_s, ''), + recall_limit: text(g.recall_limit, ''), + } +} + +export function ledgerChanged(cur: LedgerDraft, saved: LedgerDraft): LedgerKey[] { + return (Object.keys(saved) as LedgerKey[]).filter((k) => cur[k] !== saved[k]) +} + +/** 保存条上这几项的叫法:和字段名、服务端报错同一套 */ +export const ledgerLabels = (keys: LedgerKey[]): string[] => keys.map((k) => LABEL[k]) + +const intIn = (v: string, lo: number, hi: number) => /^\d+$/.test(v.trim()) && Number(v) >= lo && Number(v) <= hi + +/** 各项的问题。只校验改过的(存着的值不合规不该挡住别的设置保存) */ +export function ledgerErrors(cur: LedgerDraft, saved: LedgerDraft): Partial> { + const out: Partial> = {} + for (const k of ledgerChanged(cur, saved)) { + if (k === 'issue_daily_limit' && !intIn(cur[k], 0, DAILY_MAX)) out[k] = S.invalid.limit(DAILY_MAX) + if (k === 'recall_limit' && !intIn(cur[k], 0, RECALL_MAX)) out[k] = S.invalid.limit(RECALL_MAX) + if (k === 'match_timeout_s') { + const n = Number(cur[k].trim()) + if (!(cur[k].trim() !== '' && Number.isFinite(n) && n >= TIMEOUT_RANGE[0] && n <= TIMEOUT_RANGE[1])) { + out[k] = S.invalid.timeout(TIMEOUT_RANGE[0], TIMEOUT_RANGE[1]) + } + } + } + return out +} + +/** 草稿 → 存进去的整组 ledger */ +export function ledgerPayload(cur: LedgerDraft): Record { + return { + auto_issue: cur.auto_issue, + issue_daily_limit: Number(cur.issue_daily_limit.trim()), + match_timeout_s: Number(cur.match_timeout_s.trim()), + recall_limit: Number(cur.recall_limit.trim()), + } +} + +const id = (k: LedgerKey) => `pref-ledger-${k.replace(/_/g, '-')}` + +export function LedgerSection({ cur, errors, onEdit }: { + cur: LedgerDraft + errors: Partial> + onEdit: (patch: Partial) => void +}) { + const num = (k: Exclude, hint: string, mode: 'numeric' | 'decimal' = 'numeric') => ( + + {(p) => ( + onEdit({ [k]: e.target.value } as Partial)} /> + )} + + ) + return ( +
+ + +
+ {num('issue_daily_limit', S.dailyLimitHint)} + {num('match_timeout_s', S.timeoutHint, 'decimal')} + {num('recall_limit', S.recallLimitHint)} +
+
+ ) +} diff --git a/frontend/src/run/EvidenceDoc.tsx b/frontend/src/run/EvidenceDoc.tsx index 454e2e35..32493827 100644 --- a/frontend/src/run/EvidenceDoc.tsx +++ b/frontend/src/run/EvidenceDoc.tsx @@ -16,7 +16,7 @@ import { } from '../lib/evidence' import { formatNumber } from '../lib/format' import { - CHALLENGE_TEXT, EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, INQUIRY_TEXT, JUDGE_TEXT, claimTally, evidenceTally, + CHALLENGE_TEXT, EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, INQUIRY_TEXT, JUDGE_TEXT, LEDGER_TEXT, claimTally, evidenceTally, type ClaimTallyCounts, } from '../lib/terms' import { useEvidence, useVerdicts, type Slot } from '../store/evidence' @@ -26,6 +26,10 @@ import type { } from '../types' import { EvidencePanel, type PanelMode, type PanelView } from './EvidencePanel' import { askAbout, type InquiryAccess } from './Inquiry' +import { caliberOf, ledgerEnabled } from './LedgerStep' +import { LEDGER_UI } from '../lib/termsLedger' +import { useRunLedger } from '../store/ledger' +import type { LedgerLabel } from '../typesLedger' import { BlockView, Markdown, StyledSlice, inlineStyles, numericColumns, type InlineStyles } from './Markdown' /** @@ -47,6 +51,10 @@ import { BlockView, Markdown, StyledSlice, inlineStyles, numericColumns, type In * 上一处有问题的地方(无证据、可疑名称、证据相矛盾、部分有依据;证据不足的排在这些之后),回车打开证据面板, * Esc 关掉并留在原片段;面板开着时方向键走到哪、面板跟到哪,Tab 进面板。 * + * 口径账本(next-round 02 做法 3):来自口径的数字后面挂一个小标记,写明受管还是已发布(悬停写是哪一份口径、怎么认的); + * 相关口径的数不加标记,只在证据面板的「口径」一步里说。标签按运行另取(GET /runs/{id}/ledger,store/ledger 按退避 + * 等比对出结果),正式运行、没有运行的文档不取。 + * * 长报告:事件都挂在容器上(片段只带 data-seg),块用 memo,外加 * content-visibility: auto;超过 TEXT_CAP 的部分先折叠,跳转到折叠里的片段时自动展开。 */ @@ -370,6 +378,10 @@ export const EvidenceDoc = forwardRef challengeMarks(graph, report, artifact), [graph, report, artifact]) const model = useMemo(() => buildModel(blocks, overlay, ask, marks), [blocks, overlay, ask, marks]) + // 来自口径的数字上的小标记:按运行取的口径账本里这份报告的标签(只画 caliber 一种) + const ledger = useRunLedger(runId, ledgerEnabled(runId, runClass)) + const labels = report ? ledger?.data?.reports?.[report]?.labels : undefined + const caliberMarks = useMemo(() => caliberMarksOf(labels), [labels]) const counts = useMemo(() => docTally(doc), [doc]) const claims = useMemo(() => claimCounts(doc, overlay), [doc, overlay]) const rootRef = useRef(null) @@ -664,7 +676,7 @@ export const EvidenceDoc = forwardRef + panelId={panelId} model={model} ask={ask} calibers={caliberMarks} /> {mode === 'inline' && b === activeBlock && panelNode} ))} @@ -741,7 +753,7 @@ function useSelectionPick(root: RefObject, anchor: RefObject const start = at(range.startContainer) if (!inside(start) || !inside(at(range.endContainer))) { setPick(null); return } const frag = range.cloneContents() - frag.querySelectorAll('[data-inquiry-ask], .ev-tag, .ev-badge, .sr-only').forEach((n) => n.remove()) + frag.querySelectorAll('[data-inquiry-ask], .ev-tag, .ev-badge, .ev-caliber, .sr-only').forEach((n) => n.remove()) const quote = (frag.textContent ?? '').replace(/\s+/g, ' ').trim() if ([...quote].length < 2) { setPick(null); return } const rects = range.getClientRects() @@ -878,8 +890,10 @@ export function ClaimTally({ claims, lead }: { claims: ClaimTallyCounts; lead: b /** 列表项的开头:结构片段里带着行首的 - / 1. 。列表项被分成几句时,后面几句接在同一项里 */ const ITEM_START = /(^|\n)[ \t]*([-*+]|\d+[.)])[ \t]+$/ -const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, active, panelId, model, ask }: { +const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, active, panelId, model, ask, calibers }: { block: EvidenceBlock + /** 来自口径的数字:片段 id → 小标记(口径账本) */ + calibers?: CaliberMarks dense: boolean doc: EvidenceDocData /** 句末徽标从这里取:这一句眼下的判定(封存后追加的盖过文档里的) */ @@ -904,7 +918,7 @@ const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, ac } const unit = (u: EvidenceUnit, opts?: { code?: boolean; tag?: boolean }) => ( ) @@ -970,6 +984,23 @@ const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, ac } }) +/** 来自口径的数字上的小标记:片段 id → 标记上的字(级别)、悬停、读屏 */ +type CaliberMarks = Map + +function caliberMarksOf(labels: Record | undefined): CaliberMarks | undefined { + if (!labels) return undefined + const out: CaliberMarks = new Map() + for (const [id, label] of Object.entries(labels)) { + if (label.kind !== 'caliber') continue + const how = LEDGER_TEXT.how[label.how === 'composed' ? 'composed' : 'independent'] + const caliber = caliberOf(label) + const level = label.level_text || (label.level ? (LEDGER_TEXT.level as Record)[label.level] ?? '' : '') + out.set(id, { text: level || LEDGER_TEXT.kind.caliber, level: label.level ?? '', title: LEDGER_UI.mark.title(caliber, how), + aria: LEDGER_UI.mark.aria(caliber, how) }) + } + return out.size ? out : undefined +} + /** 反方审稿的判断在句末徽标里的样子。soft 是悬停、展开时铺的浅底,醒目的那两种不铺(见 LOUD_RING) */ interface MarkLook { icon: LucideIcon; color: string; soft: string; loud: boolean } @@ -1016,9 +1047,10 @@ function ChallengeMark({ verdict, look, after }: { verdict: string; look: MarkLo * 一枚徽标(也是按钮),证据相矛盾(和旧的证据不支持)的整句铺浅底——字本身不画线。被反方审过的 * 句子同样挂徽标(和判定并在一起),点开都是整句面板 */ -function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask }: { +function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask, calibers }: { unit: EvidenceUnit; doc: EvidenceDocData; current: string | null; active: string | null; panelId: string code?: boolean; tag: boolean; badge?: Badge + calibers?: CaliberMarks /** * 审批质询的「质询」:roving 是这一句一个可点的都没有,「质询」本身进键盘顺序;follow 跟在这一句后面,焦点在这一句上时 * 按 Tab 到达 @@ -1041,7 +1073,8 @@ function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask } const meta = EVIDENCE_STATE[state] if (meta.alert && TAG_TEXT[state]) alerts.add(state) const open = active === s.id - return ( + const mark = calibers?.get(s.id) + const button = ( ) + if (!mark) return button + // 来自口径的数:后面挂一个小标记(受管 / 已发布),悬停写是哪一份口径、怎么认的。不进键盘顺序(读屏念在片段上) + return ( + + {button} + + + ) }) const key = badge ? badgeKey(unit.id) : '' const meta = badge?.state ? EVIDENCE_STATE[badge.state] : null diff --git a/frontend/src/run/EvidencePanel.tsx b/frontend/src/run/EvidencePanel.tsx index c8fe069d..87df5131 100644 --- a/frontend/src/run/EvidencePanel.tsx +++ b/frontend/src/run/EvidencePanel.tsx @@ -34,6 +34,7 @@ import { ArtifactViewer, ResultTable } from './AssistantStream' import { ChallengeSummary, ClaimVerdictPending, type ClaimWait } from './ChallengeSummary' import { useEvidenceHost } from './evidenceHost' import { EvidenceProvenance } from './EvidenceProvenance' +import { LedgerPart } from './LedgerStep' import { CopyChip } from './Markdown' import { SqlCheckList } from './SqlChecks' import { @@ -86,6 +87,10 @@ import { * 输入来源里只说核对结果、不写值;遮没遮核对不了的(快照读不出来)同样不显示值,写明原因。类型都在 types.ts * (EvidenceDualCheck、EvidenceUnitChallenge、EvidenceInput 的 masked / mask_unverified)。 * + * 口径账本(next-round 02 做法 3、6):数字、取值片段的出处链最上面多「口径」一步(run/LedgerStep 的 LedgerPart)—— + * 来自口径「X」v3(受管)· 参数 · 等价已证明 / 助手选用 · 按口径正式出具;相关口径的差在哪和看差多少(口径对账);这次的 + * 推理。比对在封存之后做,不在封存范围内,脚注写明;比对还没出结果时写「正在比对口径」并按退避再取。 + * * 四种摆法:side 从右侧弹出(宽屏),drawer 从底部抽出(窄屏),inline 在 360px 的 * 画布右栏里直接栏内展开,dock 放进页面给的一块常驻位置(记录页的「证据」页签)。 * 都不是模态的:开着面板照样能在正文里走。 @@ -424,6 +429,13 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block + {state === 'deterministic' && (isMetric || isCell) && !docIssue && ( + // 口径账本:出处链最上面的「口径」一步(来自口径 / 相关口径 / 这次的推理)。比对在封存之后做,这一步按运行另取 + // (GET /runs/{id}/ledger,还在比对时按退避再取);片段接口的 ledger 键先顶上 + + )} + {bad && ( diff --git a/frontend/src/run/LedgerReconcile.tsx b/frontend/src/run/LedgerReconcile.tsx new file mode 100644 index 00000000..a07905e6 --- /dev/null +++ b/frontend/src/run/LedgerReconcile.tsx @@ -0,0 +1,283 @@ +import { useEffect, useMemo, useState } from 'react' +import { Link } from 'react-router-dom' +import { Scale } from 'lucide-react' +import { ApiError, api } from '../api/client' +import { EvidenceDrawer, type EvidenceTarget } from '../apps/EvidenceDrawer' +import { Field, Modal, Spinner, StatusBadge, toast } from '../components/ui' +import { errorMessage } from '../lib/errors' +import { LEDGER_UI } from '../lib/termsLedger' +import { useAtLeast } from '../store/auth' +import { useLedger } from '../store/ledger' +import type { + LedgerField, LedgerPairOptions, LedgerReconcileAction, LedgerReconcileIn, LedgerReconciled, LedgerReconcileGroup, + LedgerRelated, RunLedger, +} from '../typesLedger' +import { BindingList, DiffList, caliberOf } from './LedgerStep' + +/** + * 口径对账(docs/design/next-round/02-口径账本.md 做法 6 的界面):「差在哪」比对时就有,「差多少」点开才跑一次确定性 + * 派生的只读图(来源 reconcile,服务端专用),差值在对账卡里算(叙述层无算术,界面也不算)。 + * + * 流程:核对参数 → 发起 → 三个数各自点得开。 + * - 核对参数:服务端在动作里写了 needs_check(参数是推断的、不全的、带遮罩值的)就先让人核对,表单照动作里的入口字段画 + * (必填、有没有缺省值),遮罩值不回填、要人重新填写;不用核对的照样能「修改参数」,改了就按核对过的参数发起。 + * - 发起:服务端认不出这次的哪一列对口径的哪个指标时回 409(ledger_reconcile_needs_pairs)、带上可选的列和指标,这里照它 + * 画「选择要对照的指标」,人选好再发起;参数不对的回 422 / 409,把服务端的话写在表单下面。 + * - 结果(ReconcileResults):每一组对照写按你的问法、按口径、差值(另附相对差),每个数按 + * /runs/{对账运行}/evidence/metrics/{对账卡}/{指标} 取值,点一下打开它的出处链(apps/EvidenceDrawer,和应用页点数同一套)。 + * 哪几个指标是一组由服务端给(reconciled.groups),这里不按命名规则拼。 + */ + +const NEEDS_PAIRS = 'ledger_reconcile_needs_pairs' +const CHECK_INPUTS = 'ledger_reconcile_check_inputs' + +/** 核对参数的表单:动作里的入口字段(老答复没有时按绑定的字段),值先填绑定出来的,遮罩值空着 */ +function fieldsOf(action: LedgerReconcileAction): LedgerField[] { + if (action.fields?.length) return action.fields + return action.binding.map((b) => ({ name: b.field, required: false, has_default: false })) +} + +function draftOf(action: LedgerReconcileAction): Record { + const out: Record = {} + for (const f of fieldsOf(action)) { + const b = action.binding.find((x) => x.field === f.name) + out[f.name] = b && !b.masked && b.value != null ? String(b.value) : '' + } + return out +} + +export function ReconcileDialog({ runId, action, related, onClose }: { + runId: string; action: LedgerReconcileAction; related?: LedgerRelated; onClose: () => void +}) { + const refresh = useLedger((s) => s.refresh) + const fields = fieldsOf(action) + const [values, setValues] = useState>(() => draftOf(action)) + const [editing, setEditing] = useState(action.needs_check) + const [options, setOptions] = useState(null) + const [pairs, setPairs] = useState>({}) + const [busy, setBusy] = useState(false) + const [problem, setProblem] = useState('') + const caliber = caliberOf(action) + const masked = new Set(action.binding.filter((b) => b.masked).map((b) => b.field)) + const chosen = Object.entries(pairs).filter(([, m]) => !!m).map(([ours, metric]) => ({ ours, metric })) + const dirty = editing && JSON.stringify(values) !== JSON.stringify(draftOf(action)) + + const launch = async () => { + if (options && !chosen.length) { setProblem(LEDGER_UI.reconcile.pairEmpty); return } + setBusy(true) + setProblem('') + const body: LedgerReconcileIn = { query: action.query, workflow_id: action.workflow_id, version: action.version } + if (editing) { + // 空着的不送:留空的项按口径的缺省值(服务端按入口字段校验,缺必填的照实拒收) + body.inputs = Object.fromEntries(Object.entries(values).filter(([, v]) => v.trim() !== '').map(([k, v]) => [k, v.trim()])) + body.confirm = true + } + if (options) body.pairs = chosen + try { + await api.caliberLedger.reconcile(runId, body) + toast.ok(LEDGER_UI.reconcile.launched) + refresh(runId) + onClose() + } catch (e) { + if (e instanceof ApiError && e.code === NEEDS_PAIRS) { + const raw = (e.body as { options?: LedgerPairOptions } | undefined)?.options + if (raw && Array.isArray(raw.columns) && Array.isArray(raw.metrics)) setOptions(raw) + setProblem(e.message) + } else if (e instanceof ApiError && e.code === CHECK_INPUTS) { + setEditing(true) + setProblem(e.message) + } else { + setProblem(errorMessage(e)) + } + } finally { + setBusy(false) + } + } + + return ( + + + + }> +
+

{LEDGER_UI.reconcile.intro}

+ {related && ( +
+
{LEDGER_UI.reconcile.where}
+ +
+ )} +
+
+ {LEDGER_UI.reconcile.params} + {!editing && fields.length > 0 && ( + + )} +
+ {editing ? ( + <> +

+ {action.check_reason || LEDGER_UI.reconcile.paramsHint} +

+
+ {fields.map((f) => ( + + {(p) => ( + setValues((v) => ({ ...v, [f.name]: e.target.value }))} /> + )} + + ))} +
+ + ) : ( +
+

{LEDGER_UI.reconcile.paramsFixed}

+ +
+ )} +
+ {options && ( +
+
{LEDGER_UI.reconcile.pairs}
+

{LEDGER_UI.reconcile.pairsHint}

+
+ {options.columns.map((col) => ( + + ))} +
+
+ )} + {problem &&

{problem}

} +
+
+ ) +} + +/** 正在取的指标值,按(运行、卡、指标)记一份:同一组数在面板、轮次两处挂着时只取一次 */ +const values = new Map>() +function valueOf(runId: string, card: string, metric: string): Promise { + const key = `${runId}\u0000${card}\u0000${metric}` + let p = values.get(key) + if (!p) { + p = api.apps.metricEvidence(runId, card, metric).then((d) => String(d?.rendered ?? '')) + values.set(key, p) + p.catch(() => values.delete(key)) + } + return p +} + +/** 对账卡上的一个数:取值,点一下打开它的出处链 */ +function MetricValue({ runId, card, metric, what, label, onOpen }: { + runId: string; card: string; metric: string; what: string; label: string; onOpen: (t: EvidenceTarget) => void +}) { + const [text, setText] = useState(null) + const [failed, setFailed] = useState(false) + useEffect(() => { + let alive = true + setText(null) + setFailed(false) + valueOf(runId, card, metric).then((v) => { if (alive) setText(v) }, () => { if (alive) setFailed(true) }) + return () => { alive = false } + }, [runId, card, metric]) + return ( + + {what} + + + ) +} + +const SHOWN = 3 + +function GroupRow({ runId, card, group, onOpen }: { + runId: string; card: string; group: LedgerReconcileGroup; onOpen: (t: EvidenceTarget) => void +}) { + const R = LEDGER_UI.result + return ( +
  • + {group.label} + + + + +
  • + ) +} + +function ReconcileCard({ item, data, original }: { item: LedgerReconciled; data?: RunLedger; original?: string }) { + const builder = useAtLeast('builder') + const [all, setAll] = useState(false) + const [target, setTarget] = useState(null) + const c = (data?.calibers ?? []).find((x) => x.caliber === item.caliber) + const caliber = c ? caliberOf(c) : caliberOf({ version: item.version }) + const groups = item.groups ?? [] + const shown = all ? groups : groups.slice(0, SHOWN) + const R = LEDGER_UI.result + const state = item.status === 'succeeded' ? 'succeeded' : item.status === 'failed' ? 'failed' + : item.status === 'cancelled' ? 'cancelled' : 'running' + return ( +
    +
    + + {R.title(caliber)} + {item.inputs_from && R.inputs[item.inputs_from] && {R.inputs[item.inputs_from]}} + {builder && {R.openRun}} +
    + {state === 'running' &&

    {R.running}

    } + {state === 'failed' &&

    {R.failed}

    } + {state === 'cancelled' &&

    {R.cancelled}

    } + {state === 'succeeded' && item.card && groups.length > 0 && ( + <> +
      + {shown.map((g) => )} +
    + {groups.length > SHOWN && ( + + )} + {original &&

    {R.original(original)}

    } + + )} + setTarget(null)} /> +
    + ) +} + +/** 对过的账(新的在前)。original:从证据面板打开时,正文里这个数写的是什么 */ +export function ReconcileResults({ items, data, original }: { + runId: string; items: LedgerReconciled[]; data?: RunLedger; original?: string +}) { + const sorted = useMemo(() => items, [items]) + if (!sorted.length) return null + return ( +
    + {sorted.map((item) => )} +
    + ) +} diff --git a/frontend/src/run/LedgerStep.tsx b/frontend/src/run/LedgerStep.tsx new file mode 100644 index 00000000..ce95db74 --- /dev/null +++ b/frontend/src/run/LedgerStep.tsx @@ -0,0 +1,325 @@ +import { useState, type ReactNode } from 'react' +import { Link } from 'react-router-dom' +import { BookMarked, RotateCw, Scale } from 'lucide-react' +import { ApiError, api } from '../api/client' +import { Spinner, StatusBadge, toast } from '../components/ui' +import { errorMessage } from '../lib/errors' +import { LEDGER_TEXT } from '../lib/terms' +import { LEDGER_UI, caliberName } from '../lib/termsLedger' +import { useAtLeast } from '../store/auth' +import { useLedger, useRunLedger, type LedgerSlot } from '../store/ledger' +import type { + LedgerBinding, LedgerIssueAction, LedgerIssued, LedgerLabel, LedgerReconcileAction, LedgerRelated, RunLedger, SegmentLedger, +} from '../typesLedger' +import { ReconcileDialog, ReconcileResults } from './LedgerReconcile' + +/** + * 口径账本在证据里的那一部分(docs/design/next-round/02-口径账本.md 做法 3、5、6 的界面): + * - 证据面板出处链最上面的「口径」一步(LedgerPart):来自口径——「X」v3(受管)· 参数 · 怎么认的(等价已证明 / 助手选用) + * · 按口径正式出具;相关口径——差在哪 + 看差多少(口径对账:核对参数 → 发起 → 三个数各自点得开);这次的推理—— + * 写「没有相关的已发布口径」;没比对的写原因。比对还没出结果时写「正在比对口径」,store/ledger 按退避轮询, + * 等满了还没结论照实说、给「再取一次」; + * - 按口径正式出具那一项(IssueControl)和出具过的正式运行(IssuedList):问数据的轮次摘要用同一份。 + * + * 界面层不放逻辑:标签、能不能出具、能不能自动、不能的原因、要不要先核对参数都是服务端给的(GET /runs/{id}/ledger), + * 这里只照着画。比对在封存之后做,脚注写明「封存后比对,不在封存范围内」,事后补比的另写按哪种口径回看。 + */ + +/** 级别的叫法:服务端给 level_text,老答复没有时按 LEDGER_TEXT 的说法 */ +export const levelOf = (x: { level?: string | null; level_text?: string }) => + x.level_text || (x.level ? (LEDGER_TEXT.level as Record)[x.level] ?? '' : '') + +export const caliberOf = (x: { workflow_name?: string | null; version?: number | null; level?: string | null; level_text?: string }) => + caliberName(x.workflow_name, x.version, levelOf(x)) + +/** 一次运行的口径账本里,某份报告的某个片段的标签:先看按运行取的那一份,没有时退回片段接口的 ledger 键 */ +export function labelOf(data: RunLedger | undefined, report: string | undefined, segId: string, + fallback?: SegmentLedger | null): LedgerLabel | undefined { + const fromRun = report ? data?.reports?.[report]?.labels?.[segId] : undefined + return fromRun ?? fallback?.label ?? undefined +} + +/** 能不能取账本:正式运行本身就是某一版口径的出具,不比对;没有运行(预览、导出的文档)也没有 */ +export const ledgerEnabled = (runId: string | undefined, runClass: string | undefined) => !!runId && runClass !== 'formal' + +/** + * 取账本出了错要不要说:服务端说这次运行不存在(404)时不说——证据链那边已经照实说了运行取不到,这里再挂一句「口径比对 + * 读不出」是同一件事说两遍;别的错(服务端出错、连不上)照实说、给「再取一次」 + */ +export const ledgerErrorShown = (slot: LedgerSlot | undefined) => + slot?.status === 'error' && !(slot.error instanceof ApiError && slot.error.status === 404) + +/** 绑定的参数:字段 = 值,遮罩值只写「已遮罩」 */ +export function BindingList({ binding }: { binding?: LedgerBinding[] }) { + if (!binding?.length) return {LEDGER_UI.step.noParams} + return ( + + {binding.map((b) => ( + + {b.field} = {b.masked ? LEDGER_UI.step.masked : String(b.value ?? '')} + + ))} + + ) +} + +/** 比对还没出结论 / 等满了 / 读不出:三种都说清,后两种给「再取一次」 */ +export function LedgerWaiting({ slot, runId, compact = false }: { slot: LedgerSlot; runId: string; compact?: boolean }) { + const refresh = useLedger((s) => s.refresh) + const retry = ( + + ) + if (slot.status === 'error') { + return ( +
    + {LEDGER_UI.step.failed}:{errorMessage(slot.error)}{retry} +
    + ) + } + if (slot.timedOut) { + return ( +
    + {compact ? LEDGER_UI.turn.timeout : LEDGER_UI.step.timeout}{retry} +
    + ) + } + return ( +
    + {LEDGER_UI.step.pending} + {!compact && {LEDGER_UI.step.pendingSub}} +
    + ) +} + +/** 比对的来历:封存后比对,不在封存范围内;事后补比的写按哪种口径回看 */ +export function LedgerFootnote({ data }: { data: RunLedger }) { + return ( +

    + {[data.note || LEDGER_TEXT.sub, data.retro ? data.retro_note || LEDGER_TEXT.retro : ''].filter(Boolean).join(' · ')} +

    + ) +} + +/** + * 按口径正式出具(整题等价时)。服务端给了能不能、能不能自动、不能的原因:能自动的写「已在自动出具」、等出具的那一次出现 + * (等满了还没有,给按钮);只给一键的给按钮,按钮下写为什么不自动;不能出具的照写原因(使用者没有应用授权时是「请搭建者 + * 出具」)。同一运行、同一口径、同一组参数只发起一次:再点交回那一次 + */ +export function IssueControl({ runId, action, slot, readOnly = false }: { + runId: string; action: LedgerIssueAction; slot?: LedgerSlot; readOnly?: boolean +}) { + const refresh = useLedger((s) => s.refresh) + const [busy, setBusy] = useState(false) + const caliber = caliberOf(action) + const issued = action.issued_run || (slot?.data?.issued ?? []).some((i) => i.workflow_id === action.workflow_id + && i.version === action.version) + if (issued) return null + if (!action.available) { + return

    {action.reason}

    + } + if (action.auto && !slot?.timedOut) { + return ( +

    + {LEDGER_UI.issue.auto} +

    + ) + } + const issue = async () => { + setBusy(true) + try { + const out = await api.caliberLedger.issue(runId, { workflow_id: action.workflow_id, version: action.version }) + toast.ok(out.created ? LEDGER_UI.issue.launched(caliber) : LEDGER_UI.issue.again(caliber)) + refresh(runId) + } catch (e) { + toast.error(e) + } finally { + setBusy(false) + } + } + return ( +
    + + {action.auto && slot?.timedOut &&

    {LEDGER_UI.issue.autoTimeout}

    } + {!action.auto && action.auto_reason && ( +

    {action.auto_reason}

    + )} +
    + ) +} + +/** 出具过的一次正式运行的状态:结束了写档位(完整出具 / 降档出具 / 不予出具),没结束写进行中 */ +function issuedState(i: LedgerIssued): { code: string; text: string } { + if (i.status === 'succeeded') return { code: 'succeeded', text: i.tier_text || LEDGER_TEXT.kind.caliber } + if (i.status === 'cancelled' && i.end_reason === 'rejected') return { code: 'rejected', text: LEDGER_UI.issued.rejected } + if (i.status === 'cancelled') return { code: 'cancelled', text: LEDGER_UI.issued.cancelled } + if (i.status === 'failed') return { code: 'failed', text: LEDGER_UI.issued.failed } + return { code: 'running', text: LEDGER_UI.issued.running } +} + +/** 出具过的正式运行,挂在轮次下面、面板里:点开去运行(使用者读不了正式运行的原始记录,写明由搭建者查看) */ +export function IssuedList({ data }: { data: RunLedger }) { + const builder = useAtLeast('builder') + const issued = data.issued ?? [] + if (!issued.length) return null + const nameOf = (i: LedgerIssued) => { + const c = (data.calibers ?? []).find((x) => x.workflow_id === i.workflow_id && x.version === i.version) + const a = (data.actions ?? []).find((x): x is LedgerIssueAction => x.kind === 'issue' && x.workflow_id === i.workflow_id + && x.version === i.version) + return caliberOf(c ?? a ?? { version: i.version }) + } + return ( +
      + {issued.map((i) => { + const st = issuedState(i) + return ( +
    • + + {LEDGER_UI.issued.title(i.auto)} + {nameOf(i)} + {st.text} + {builder + ? {LEDGER_UI.issued.open} + : {LEDGER_UI.issued.userNote}} +
    • + ) + })} +
    + ) +} + +/** 一份相关口径对应的那一项「看差多少」:同一条查询(指标的几条查询之一)、同一份口径 */ +export function reconcileActionFor(data: RunLedger | undefined, queries: string[], caliber: string | undefined) { + return (data?.actions ?? []).find((a): a is LedgerReconcileAction => a.kind === 'reconcile' && a.caliber === caliber + && queries.includes(a.query)) +} + +/** 差在哪:explain_sql_diff 的条目(SQL 片段服务端已按遮罩换过);兜底说明另写一句 */ +export function DiffList({ related }: { related?: LedgerRelated }) { + const items = (related?.diff?.items ?? []).filter((i) => i.text) + if (!items.length && !related?.diff?.fallback) { + return

    {related?.reason || LEDGER_UI.step.noDiff}

    + } + return ( +
      + {items.map((i, n) =>
    • {i.text}
    • )} + {related?.diff?.fallback && !items.length &&
    • {LEDGER_UI.step.fallback}
    • } +
    + ) +} + +/** 面板里的一小节:同 EvidencePanel 的 Part */ +function Section({ title, children, ...rest }: { title: string; children: ReactNode } & Record<`data-${string}`, string>) { + return ( +
    +
    {title}
    + {children} +
    + ) +} + +/** + * 证据面板出处链最上面的「口径」一步。只给数字、取值片段(单元格、指标):别的片段服务端本来就不标。正式运行、没有运行、 + * 不比对的运行不画这一步 + */ +export function LedgerPart({ runId, runClass, report, segId, segText, segLedger, readOnly = false }: { + runId?: string; runClass?: string; report?: string; segId: string + /** 正文里这个数写的是什么:对账结果里对照着说原答案当时的值 */ + segText?: string + /** 片段接口的 ledger 键(按运行取的那一份还没回来时先用它) */ + segLedger?: SegmentLedger | null + readOnly?: boolean +}) { + const on = ledgerEnabled(runId, runClass) + const slot = useRunLedger(runId, on) + const [dialog, setDialog] = useState<{ action: LedgerReconcileAction; related?: LedgerRelated } | null>(null) + if (!on || !runId) return null + const data = slot?.data + const label = labelOf(data, report, segId, segLedger) + if (!label) { + // 还在比对、等满了、读不出:照实说;比对过了这个片段没有标签(不是数)、不比对的、第一次还没取回来的:这一步不画 + if (!slot || (slot.status === 'loading' && !data)) return null + if (ledgerErrorShown(slot) || (slot.status !== 'error' && data?.state === 'pending')) { + return
    + } + if (data?.state === 'unreadable') { + return ( +
    +

    {LEDGER_UI.step.unreadable(data.reason ?? '')}

    +
    + ) + } + return null + } + const queries = label.queries ?? (label.query ? [label.query] : []) + const issue = label.kind === 'caliber' && data?.whole?.equivalent + ? (data.actions ?? []).find((a): a is LedgerIssueAction => a.kind === 'issue' && a.workflow_id === label.workflow_id + && a.version === label.version) + : undefined + const how = label.how === 'composed' ? 'composed' : 'independent' + return ( +
    + {label.kind === 'caliber' && ( +
    +

    + {LEDGER_TEXT.kind.caliber}{caliberOf(label)} + {LEDGER_TEXT.how[how]} +

    +

    {LEDGER_UI.step.how[how]}

    +
    + {LEDGER_UI.step.params} + +
    + {label.column &&

    {LEDGER_UI.step.column(label.column)}

    } + {issue && } + {data && issue && + i.workflow_id === issue.workflow_id && i.version === issue.version) }} />} +
    + )} + {label.kind === 'related' && ( +
    +

    {LEDGER_UI.step.relatedSub}{label.reason ? `:${label.reason}` : ''}

    + {(label.related ?? []).map((r, i) => { + const action = reconcileActionFor(data, queries, r.caliber) + // 指标的相关口径只写是哪一版,差在哪在它的各条查询上 + const where = r.diff ? r : (data?.queries ?? []).filter((q) => queries.includes(q.artifact)) + .flatMap((q) => q.candidates).find((c) => c.caliber === r.caliber && c.status === 'related') + const done = (data?.reconciled ?? []).filter((x) => x.caliber === r.caliber && !!x.query && queries.includes(x.query)) + return ( +
    +

    {LEDGER_TEXT.kind.related}{caliberOf(r)}

    +
    +
    {LEDGER_UI.step.where}
    + +
    + {action ? ( + + ) : r.comparable === false ?

    {r.reason || LEDGER_UI.step.notComparable}

    : null} + {!!done.length && } +
    + ) + })} +
    + )} + {label.kind === 'reasoning' && ( +

    {LEDGER_TEXT.kind.reasoning} · {LEDGER_UI.step.reasoningSub}

    + )} + {label.kind === 'unknown' && ( +

    {LEDGER_TEXT.kind.unknown}{label.reason ? `:${label.reason}` : ''}

    + )} + {data && } + {dialog && data && ( + setDialog(null)} /> + )} +
    + ) +} diff --git a/frontend/src/run/LedgerTurn.tsx b/frontend/src/run/LedgerTurn.tsx new file mode 100644 index 00000000..ab5e1e12 --- /dev/null +++ b/frontend/src/run/LedgerTurn.tsx @@ -0,0 +1,104 @@ +import { useMemo, useState } from 'react' +import { BookMarked, Scale } from 'lucide-react' +import { LEDGER_TEXT } from '../lib/terms' +import { LEDGER_UI } from '../lib/termsLedger' +import { useRunLedger } from '../store/ledger' +import type { LedgerIssueAction, LedgerReconcileAction, LedgerRelated, RunLedger } from '../typesLedger' +import { IssueControl, IssuedList, LedgerFootnote, LedgerWaiting, caliberOf, ledgerEnabled, ledgerErrorShown } from './LedgerStep' +import { ReconcileDialog, ReconcileResults } from './LedgerReconcile' + +/** + * 问数据轮次底部的口径账本(docs/design/next-round/02-口径账本.md 做法 11):一行摘要(「3 个数来自口径「周销售」v3, + * 1 个数是这次的推理」)和对应的动作——整题等价时按口径正式出具(能自动的写正在自动出具),有相关口径时对账; + * 正式出具的结果(自动的、一键的)挂在轮次下面、点开去运行;对过的账一张结果卡片,三个数各自点得开。 + * + * 比对在封存之后做:轮次刚交付时写「正在比对口径」,store/ledger 按退避再取,等满了还没结论照实说、给「再取一次」。 + * 不靠实时流(ledger.matched 追加时这次运行的事件总线已经关了)。界面层不放逻辑:每个数的标签、整题判断、能不能出具、 + * 能不能自动、不能的原因都是服务端给的;摘要只是把主报告里服务端标好的数按标签数一数、写出是哪份口径。 + */ + +/** 摘要的几个数:主报告里服务端标好的标签按种类数,来自口径的写出是哪几份口径(按出现的先后) */ +function summaryOf(data: RunLedger) { + const labels = Object.values((data.primary ? data.reports?.[data.primary]?.labels : undefined) ?? {}) + const counts = { caliber: 0, related: 0, reasoning: 0, unknown: 0 } + const calibers: string[] = [] + for (const l of labels) { + counts[l.kind] += 1 + if (l.kind === 'caliber') { + const name = caliberOf(l) + if (!calibers.includes(name)) calibers.push(name) + } + } + return { ...counts, calibers, total: labels.length } +} + +/** 对账的入口:每条查询、每份相关口径一项;差在哪取那条查询上的比对 */ +function reconcileEntries(data: RunLedger): { action: LedgerReconcileAction; related?: LedgerRelated }[] { + return (data.actions ?? []).filter((a): a is LedgerReconcileAction => a.kind === 'reconcile').map((action) => ({ + action, + related: (data.queries ?? []).find((q) => q.artifact === action.query)?.candidates + .find((c) => c.caliber === action.caliber && c.status === 'related'), + })) +} + +export function LedgerTurn({ runId, runClass, done, readOnly = false }: { + runId: string | undefined + runClass?: string + /** 这一轮交付了(运行成功结束):之前不取,运行没封存、没比对 */ + done: boolean + /** 对话在回收站里:只看,不出具、不对账 */ + readOnly?: boolean +}) { + const on = done && ledgerEnabled(runId, runClass) + const slot = useRunLedger(runId, on) + const [dialog, setDialog] = useState<{ action: LedgerReconcileAction; related?: LedgerRelated } | null>(null) + const data = slot?.data + const summary = useMemo(() => (data?.state === 'matched' ? summaryOf(data) : null), [data]) + if (!on || !runId || !slot) return null + if (ledgerErrorShown(slot) || (slot.status !== 'error' && data?.state === 'pending')) { + return ( +
    + +
    + ) + } + if (!data || data.state !== 'matched' || !summary) return null + const issue = (data.actions ?? []).find((a): a is LedgerIssueAction => a.kind === 'issue') + const reconciles = reconcileEntries(data) + const issued = data.issued ?? [] + const reconciled = data.reconciled ?? [] + if (!summary.total && !issued.length && !reconciled.length) return null + const whole = data.whole + return ( +
    + {summary.total > 0 && ( +

    + + {LEDGER_UI.turn.label} + {LEDGER_UI.turn.summary(summary)} +

    + )} + {whole?.equivalent && ( +

    + {LEDGER_UI.turn.whole(caliberOf(whole), LEDGER_TEXT.how[whole.how === 'composed' ? 'composed' : 'independent'])} +

    + )} + {(issue || reconciles.length > 0) && ( +
    + {issue && } + {reconciles.map(({ action, related }) => ( + + ))} +
    + )} + + {reconciled.length > 0 && } + + {dialog && setDialog(null)} />} +
    + ) +} diff --git a/frontend/src/store/ledger.ts b/frontend/src/store/ledger.ts new file mode 100644 index 00000000..951700ca --- /dev/null +++ b/frontend/src/store/ledger.ts @@ -0,0 +1,180 @@ +import { useEffect } from 'react' +import { create } from 'zustand' +import { api } from '../api/client' +import type { LedgerIssueAction, RunLedger } from '../typesLedger' + +/** + * 一次运行的口径账本(GET /api/runs/{id}/ledger):证据正文里数字上的小标记、证据面板的「口径」一步、问数据轮次底部的 + * 摘要和动作都读这一份,同一次运行只取一份。 + * + * **比对结果不靠实时流。** 比对在封存之后放到后台做,结果是一条封存后追加的 ledger.matched——那时这次运行的事件总线已经 + * 关了,打开着的页面收不到(第 2 波遗留)。所以这里按退避轮询:服务端答 pending(正在比对,或者刚跑完、封存完就比)时 + * 隔 1、2、3、5、8、13 秒、之后每 15 秒再取一次,等满 MATCH_WAIT_MS 还没结论就停下、照实说(timedOut),给「再取一次」。 + * 比对完、要自动按口径出具的(动作写着 auto、还没有发起的那一次)再等一会儿,等到出具的正式运行出现;出具、对账的运行 + * 还没结束的,隔一阵再取,等它们结束(档位、三个数要等运行结束才有)。 + * + * 只在有人看着(有组件挂着 useRunLedger)时轮询;不比对的(ineligible)答复只当 INELIGIBLE_TTL_MS 内的结论:运行状态会变 + * (还在跑的运行、审批停着的运行之后才成功结束)。界面层不放逻辑:要不要接着等只看服务端给的 state、actions、运行状态。 + */ + +export interface LedgerSlot { + status: 'loading' | 'ok' | 'error' + data?: RunLedger + error?: unknown + /** 等满了还没有比对结论(或者自动出具一直没出现):停下来照实说 */ + timedOut?: boolean + /** 这一轮等待从什么时候开始(毫秒) */ + since?: number + fetchedAt?: number +} + +/** 等比对出结论最多多久 */ +export const MATCH_WAIT_MS = 120_000 +/** 比对完、动作写着要自动出具的:再等这么久,等出具的那一次运行出现 */ +export const AUTO_WAIT_MS = 60_000 +/** 出具、对账的运行还没结束:最多再等这么久 */ +export const RUN_WAIT_MS = 15 * 60_000 +const INELIGIBLE_TTL_MS = 20_000 +const BACKOFF = [1000, 2000, 3000, 5000, 8000, 13000] +const SLOW = 15_000 +/** 出具、对账运行还在跑时隔多久取一次 */ +const RUN_POLL = 5000 + +/** 运行还没结束的几种状态(interrupted 是停在审批或挂起,照样算没结束) */ +const LIVE = new Set(['queued', 'running', 'interrupted']) + +/** 动作写着要自动按口径出具、还没有发起的那一次(服务端判的能不能自动,这里只看它给的字段) */ +export function autoIssuePending(data: RunLedger | undefined): LedgerIssueAction | undefined { + if (!data || data.state !== 'matched') return undefined + const action = (data.actions ?? []).find((a): a is LedgerIssueAction => a.kind === 'issue' && a.auto && !a.issued_run) + return action && !(data.issued ?? []).some((i) => i.workflow_id === action.workflow_id && i.version === action.version) + ? action : undefined +} + +/** 出具、对账的运行里还有没结束的 */ +export const runsLive = (data: RunLedger | undefined): boolean => + !!data && [...(data.issued ?? []), ...(data.reconciled ?? [])].some((r) => LIVE.has(r.status)) + +interface LedgerState { + slots: Record + /** 有人看着这次运行:没取过、取失败了、不比对的结论过期了就取,按需接着轮询 */ + acquire: (runId: string) => void + release: (runId: string) => void + /** 刚发起了出具、对账,或者用户点了「再取一次」:马上取,重新开始等 */ + refresh: (runId: string) => void +} + +const watchers = new Map() +const timers = new Map>() +const attempts = new Map() +const inflight = new Map>() + +const clear = (runId: string) => { + const t = timers.get(runId) + if (t) clearTimeout(t) + timers.delete(runId) +} + +export const useLedger = create((set, get) => { + const patch = (runId: string, next: Partial) => + set((s) => ({ slots: { ...s.slots, [runId]: { ...(s.slots[runId] ?? { status: 'loading' }), ...next } } })) + + /** 下一次什么时候取(毫秒);不用再取了为 null。到点了还没结论的,顺手记 timedOut */ + const nextDelay = (runId: string): number | null => { + const slot = get().slots[runId] + const data = slot?.data + const since = slot?.since ?? Date.now() + const waited = Date.now() - since + const n = attempts.get(runId) ?? 0 + const backoff = BACKOFF[n] ?? SLOW + if (slot?.status === 'error') return null + if (data?.state === 'pending') { + if (waited >= MATCH_WAIT_MS) { patch(runId, { timedOut: true }); return null } + return backoff + } + if (autoIssuePending(data)) { + if (waited >= AUTO_WAIT_MS) { patch(runId, { timedOut: true }); return null } + return backoff + } + if (runsLive(data)) return waited >= RUN_WAIT_MS ? null : Math.max(RUN_POLL, Math.min(backoff, SLOW)) + return null + } + + const schedule = (runId: string) => { + clear(runId) + if (!watchers.get(runId)) return + const delay = nextDelay(runId) + if (delay == null) return + attempts.set(runId, (attempts.get(runId) ?? 0) + 1) + timers.set(runId, setTimeout(() => { timers.delete(runId); void load(runId) }, delay)) + } + + const load = (runId: string): Promise => { + const going = inflight.get(runId) + if (going) return going + const before = get().slots[runId] + if (!before?.data) patch(runId, { status: 'loading' }) + const p = api.caliberLedger.run(runId).then( + (data) => { + const prev = get().slots[runId]?.data + // 等的东西变了(比对出了结论、自动出具出现了):等待从这一刻重新算 + const moved = !!prev && (prev.state !== data.state + || (prev.issued?.length ?? 0) !== (data.issued?.length ?? 0)) + if (moved) attempts.set(runId, 0) + patch(runId, { status: 'ok', data, error: undefined, fetchedAt: Date.now(), timedOut: false, + ...(moved ? { since: Date.now() } : {}) }) + }, + (error) => { patch(runId, { status: 'error', error, fetchedAt: Date.now() }) }, + ).finally(() => { + inflight.delete(runId) + schedule(runId) + }) + inflight.set(runId, p) + return p + } + + return { + slots: {}, + acquire: (runId) => { + watchers.set(runId, (watchers.get(runId) ?? 0) + 1) + const slot = get().slots[runId] + const stale = !slot || slot.status === 'error' + || (slot.data?.state === 'ineligible' && Date.now() - (slot.fetchedAt ?? 0) > INELIGIBLE_TTL_MS) + if (stale) { + attempts.set(runId, 0) + patch(runId, { since: Date.now(), timedOut: false }) + void load(runId) + } else if (!timers.has(runId) && !inflight.has(runId) && !slot.timedOut) { + schedule(runId) + } + }, + release: (runId) => { + const n = (watchers.get(runId) ?? 1) - 1 + if (n > 0) { watchers.set(runId, n); return } + watchers.delete(runId) + clear(runId) + }, + refresh: (runId) => { + clear(runId) + attempts.set(runId, 0) + patch(runId, { since: Date.now(), timedOut: false }) + void load(runId) + }, + } +}) + +/** + * 这次运行的口径账本。enabled 为假(运行还没结束、正式运行、没有运行)时不取:正式运行本身就是某一版口径的出具,不比对。 + * 同一次运行挂几处(正文、面板、轮次摘要)只取一份、只轮询一份 + */ +export function useRunLedger(runId: string | null | undefined, enabled = true): LedgerSlot | undefined { + const acquire = useLedger((s) => s.acquire) + const release = useLedger((s) => s.release) + const on = !!runId && enabled + useEffect(() => { + if (!on || !runId) return + acquire(runId) + return () => release(runId) + }, [on, runId, acquire, release]) + return useLedger((s) => (on && runId ? s.slots[runId] : undefined)) +} diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 742ac45a..d5aa82e0 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -2527,6 +2527,13 @@ export interface EvidenceSegmentDetail { redacted?: { columns?: string[] } /** 可疑实体:最接近的已知名字(最多 3 个),给「是不是想写…」 */ closest?: (string | { alias?: string; name?: string; table?: string; kind?: string })[] + /** + * 口径账本(next-round 02 做法 3):这个数的口径标签和比对的来历。封存后比对,没比对过的运行、不是数的片段没有这个键 + * (老运行的返回一字不差)。形状见 typesLedger.ts + */ + ledger?: import('./typesLedger').SegmentLedger + /** 指标接口(/evidence/metrics/{node}/{metric})给的展示值:遮罩的写「已遮罩」 */ + rendered?: string } // ------------------------------------------------------------------------- diff --git a/frontend/src/typesLedger.ts b/frontend/src/typesLedger.ts new file mode 100644 index 00000000..982c2dfd --- /dev/null +++ b/frontend/src/typesLedger.ts @@ -0,0 +1,321 @@ +/** + * 口径账本的接口约定(docs/design/next-round/02-口径账本.md;服务端 app/ledger/view.py、issue.py、reconcile.py、certify.py)。 + * + * 界面层不放逻辑:每个数的标签、整题判断、能做的动作(能不能出具、能不能自动、不能的原因、要不要先核对参数)都由服务端 + * 给,界面照着画。比对在封存之后做(不在封存范围内),GET /api/runs/{id}/ledger 在比对还没出结果时答 state=pending, + * 页面按退避再取(store/ledger.ts),不靠实时流:ledger.matched 在事件总线关闭之后才追加,打开着的页面收不到。 + */ + +/** 绑定的一个参数:值是这次运行查到过的遮罩值时不给值(masked),也不能拿它代填出具 */ +export interface LedgerBinding { + field: string + value?: unknown + masked?: boolean +} + +/** 差在哪的一条(explain_sql_diff 的条目,SQL 片段已按遮罩换过)。text 是一句中文说明 */ +export interface LedgerDiffItem { + aspect?: string + a?: unknown + b?: unknown + text?: string +} + +export interface LedgerDiff { + items: LedgerDiffItem[] + /** 兜底说明:两条 SQL 对不上结构,没能归纳成具体差异 */ + fallback: boolean + text_diff: string[] +} + +/** 一份相关口径(同一个数据源、查了同样的表,但不等价) */ +export interface LedgerRelated { + caliber?: string + workflow_id?: string + version?: number + level?: string + level_text?: string + workflow_name?: string | null + node_id?: string + comparable?: boolean + reason?: string + via?: string + binding?: LedgerBinding[] + diff?: LedgerDiff | null +} + +/** + * 一个数的标签(四种): + * - caliber:来自口径「X」vN(how:independent 等价已证明 / composed 助手选用) + * - related:相关口径(附差在哪),数本身是这次的推理 + * - reasoning:这次的推理,没有相关的已发布口径 + * - unknown:没比对(reason 写为什么) + */ +export interface LedgerLabel { + kind: 'caliber' | 'related' | 'reasoning' | 'unknown' + how?: 'independent' | 'composed' + caliber?: string + workflow_id?: string + version?: number + level?: string + level_text?: string + workflow_name?: string | null + binding?: LedgerBinding[] + related?: LedgerRelated[] + reason?: string + /** 出自哪条查询(查询快照工件);指标是 queries */ + query?: string + queries?: string[] + node_id?: string + column?: string | null + card?: string + metric?: string +} + +/** 一条查询的比对:proven / composed / related / none / skipped */ +export interface LedgerQuery { + artifact: string + node_id?: string + source?: string + tables?: string[] + status: 'proven' | 'composed' | 'related' | 'none' | 'skipped' | string + reason?: string + note?: string + candidates: (LedgerRelated & { status?: string; how?: string })[] +} + +/** 整题判断(主报告):所有带标签的数都来自同一口径的同一版、参数一致时 equivalent */ +export interface LedgerWhole { + equivalent: boolean + reason?: string + counts?: Partial> + caliber?: string + workflow_id?: string + version?: number + level?: string + level_text?: string + workflow_name?: string | null + how?: 'independent' | 'composed' + binding?: LedgerBinding[] + missing?: string[] + missing_required?: string[] +} + +/** 按口径正式出具这一项:能不能(available / reason)、能不能自动(auto / auto_reason)、已经发起过的那一次(issued_run) */ +export interface LedgerIssueAction { + kind: 'issue' + workflow_id: string + version: number + caliber: string + workflow_name: string + how?: 'independent' | 'composed' | null + level?: string | null + level_text: string + available: boolean + auto: boolean + reason?: string + auto_reason?: string + issued_run?: string +} + +/** 入口字段(比对工件里记的那一份):核对参数的表单照它画 */ +export interface LedgerField { + name: string + required: boolean + has_default: boolean +} + +/** 看差多少(口径对账)这一项 */ +export interface LedgerReconcileAction { + kind: 'reconcile' + query: string + caliber: string + workflow_id: string + version: number + node_id?: string + workflow_name?: string | null + level_text: string + /** 参数是推断的、不全的、带遮罩值的:要人先核对(check_reason 是原因) */ + needs_check: boolean + check_reason?: string + binding: LedgerBinding[] + /** 两条 SQL 对不上结构:多半要人选对照的指标 */ + fallback: boolean + fields?: LedgerField[] +} + +export type LedgerAction = LedgerIssueAction | LedgerReconcileAction + +/** 按口径出具过的一次正式运行。tier_text 是「完整出具 / 降档出具 / 不予出具」,运行没结束时为空 */ +export interface LedgerIssued { + run_id: string + status: string + end_reason?: string | null + workflow_id: string + version: number + tier?: string | null + tier_text?: string | null + auto: boolean + created_at?: string | null +} + +/** 对账卡上的一组对照:这次 / 口径 / 差值 / 相对差各是哪个指标 */ +export interface LedgerReconcileGroup { + label: string + ours: string + caliber: string + diff: string + rel: string +} + +/** 对过的一次账 */ +export interface LedgerReconciled { + run_id: string + status: string + query?: string + caliber?: string + workflow_id?: string + version?: number + /** binding:按比对时的参数;checked:人核对过的参数 */ + inputs_from?: 'binding' | 'checked' | string + rows?: number[] | null + card?: string + groups?: LedgerReconcileGroup[] + created_at?: string | null +} + +export interface LedgerCaliber { + caliber: string + workflow_id: string + version: number + level?: string + graph_hash?: string | null + workflow_name?: string | null + level_text: string +} + +/** + * GET /api/runs/{id}/ledger。state:matched 比对过;pending 正在比对(或刚跑完、封存完就比);ineligible 这次运行不比对 + * (reason 写为什么);unreadable 比对记录读不出 + */ +export interface RunLedger { + run_id: string + state: 'matched' | 'pending' | 'ineligible' | 'unreadable' + reason?: string + /** 「封存后比对,不在封存范围内」 */ + note?: string + artifact?: string + algo?: string + trigger?: string + retro?: boolean + matched_at?: string | null + post_seal?: boolean + /** 事后补比的:按现在的口径回看 / 按之后发布的口径回看 */ + retro_note?: string + calibers?: LedgerCaliber[] + queries?: LedgerQuery[] + reports?: Record }> + primary?: string | null + whole?: LedgerWhole + actions?: LedgerAction[] + issued?: LedgerIssued[] + reconciled?: LedgerReconciled[] +} + +/** 证据片段接口(GET /runs/{id}/evidence/segments/{seg})的 ledger 键:这个片段的标签和比对的来历 */ +export interface SegmentLedger { + label: LedgerLabel + artifact?: string + algo?: string + trigger?: string + retro?: boolean + matched_at?: string | null + post_seal?: boolean + note?: string + retro_note?: string +} + +/** POST /api/ledger/answers/{run}/issue 的答复:created 为假是同一次已经发起过、交回那一次 */ +export interface LedgerIssueOut { + run_id: string + created: boolean + issued: LedgerIssued +} + +/** POST /api/ledger/answers/{run}/reconcile 的请求体 */ +export interface LedgerReconcileIn { + query: string + workflow_id: string + version: number + inputs?: Record + confirm?: boolean + pairs?: { ours: string; metric: string }[] +} + +export interface LedgerReconcileOut { + run_id: string + reconciled: LedgerReconciled +} + +/** 认不出列怎么配时 409(ledger_reconcile_needs_pairs)另带的选项 */ +export interface LedgerPairOptions { + columns: string[] + metrics: { id: string; name: string; unit?: string }[] +} + +// ---------------------------------------------------------------- 认证队列(可沉淀的问题) + +export interface CertifyTurn { + run_id: string | null + conversation_id?: string | null + turn_id?: string | null + question: string +} + +export interface CertifyFrozen { + workflow_id: string + name: string + status?: string + published_version?: number | null +} + +/** 三种来源:确定性重复(SQL 形状相同)、问题聚类、被反复用的答案 */ +export interface CertifyItem { + id: string + kind: 'shape' | 'cluster' | 'reused' + question: string + turns: CertifyTurn[] + frozen_into?: CertifyFrozen[] + // shape + source?: string + shape?: string + runs?: number + conversations?: number + params?: { index: number; distinct: number }[] + constants?: number + related?: { caliber?: string; workflow_id?: string; version?: number; level?: string }[] + representative?: { run_id: string; query?: string } + peers?: string[] + // cluster + count?: number + // reused + uses?: { exports: number; app: boolean; extracted: boolean; canvas: boolean } +} + +export interface CertifyQueue { + items: CertifyItem[] + considered: { runs: number; matched: number; questions: number } + threshold: { runs: number; conversations: number; exports: number } + embedder?: unknown +} + +/** 固化成口径草稿(POST /copilot/from-run,freeze: true)的答复 */ +export interface FreezeOut { + workflow_id: string + name: string + nodes: number + edges: number + params: string[] + metrics: string[] + sources: CertifyTurn[] +} From 9ad6c035d01599cf5a2adb3a8ad83e4412bdfde2 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 20:34:21 +0800 Subject: [PATCH 5/8] =?UTF-8?q?=E5=8F=A3=E5=BE=84=E8=B4=A6=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E7=95=8C=E9=9D=A2=E6=A3=80=E6=9F=A5=EF=BC=9Acheck-led?= =?UTF-8?q?ger=20=E6=8D=A2=E6=88=90=E7=9C=9F=E6=A3=80=E6=9F=A5=EF=BC=8Cche?= =?UTF-8?q?ck-evidence=E3=80=81check-chat=20=E5=90=84=E5=8A=A0=E4=B8=80?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 都用 page.route 假接口加夹具(scripts/ledger-fixtures.mjs:GET /api/runs/{id}/ledger 的形状照服务端 run_view,挂在可点击 证据的夹具 evidence-doc.json 上,只用通用名),写请求在浏览器层拦下、核对请求体,认不出的写请求一律记账、结束时必须为空。 - check-ledger(骨架里的占位换掉): · 比对还没出结果:「口径」一步写「正在比对口径」、按退避再取(间隔越来越长),等满了照实说、给「再取一次」、不再取, 点了重新取、比对过了就画出来,之后不再取(store/ledger 在开发构建里挂 window.__ledger,把等待起点挪到两分钟前); · 三种情况:来自口径(口径、级别、怎么认的、参数、事后补比的说明)、相关口径(差在哪 + 看差多少)、这次的推理; · 对账:参数要核对时表单直接打开、照入口字段画 → 发起带核对过的参数(空着的不送)→ 409 带回的选项画「选择要对照的 指标」、一组没选不发起 → 选好再发起带上对照 → 结果卡片先写进行中、再取一次后画出按你的问法 / 按口径 / 差值 / 相对差, 点差值打开出处链; · 可沉淀的问题:工作流列表弹窗里的抽屉,三类来源分开写、各写怎么认出来的;聚类只按那一轮固化;「不是口径」不写理由 不能确认、写了才记下并拿掉这一项;固化走 from-run 的 freeze(带同组的别的运行和来源轮次)、打开画布里的草稿; · 使用者:不能出具的照服务端的原因写「请搭建者出具」、不摆按钮,对账照样能用,出具过的正式运行不给链接、写由搭建者查看; · 设置里口径账本一组:显示生效的值,不合规的值写范围、不让存,保存条写改了哪几项,整组写 ledger。 - check-evidence「口径账本」一节:来自口径的数字挂「受管 / 已发布」小标记(紧跟数字、悬停写口径和认法、读屏念在数字上), 相关口径、这次的推理、没比对的不挂;面板「口径」一步在出处链最上面,四种标签各写各的,不是数的片段不画;同一次运行只取 一次账本。别的节的夹具一律答不比对,不落到真服务端。 - check-chat「口径账本」一节:交付了的轮次底部先写「正在比对口径」,按退避再取到比对出结果后写摘要、比完不再取;按口径正式 出具、对账按钮照服务端的动作摆,出具的请求只说按哪份口径,出具过的正式运行挂在轮次下面(档位、打开运行);对账请求带 哪条查询、哪份口径、核对过的参数。 --- frontend/src/store/ledger.ts | 3 + scripts/check-chat.mjs | 112 +++++++++- scripts/check-evidence.mjs | 77 +++++++ scripts/check-ledger.mjs | 404 ++++++++++++++++++++++++++++++++++- scripts/ledger-fixtures.mjs | 114 ++++++++++ 5 files changed, 704 insertions(+), 6 deletions(-) create mode 100644 scripts/ledger-fixtures.mjs diff --git a/frontend/src/store/ledger.ts b/frontend/src/store/ledger.ts index 951700ca..30c3adb3 100644 --- a/frontend/src/store/ledger.ts +++ b/frontend/src/store/ledger.ts @@ -178,3 +178,6 @@ export function useRunLedger(runId: string | null | undefined, enabled = true): }, [on, runId, acquire, release]) return useLedger((s) => (on && runId ? s.slots[runId] : undefined)) } + +// 检查脚本(scripts/check-ledger.mjs)读写它:把一轮等待的起点挪到很早以前,不用真等两分钟就能看到「还没有结果」 +if (import.meta.env.DEV) (window as any).__ledger = useLedger diff --git a/scripts/check-chat.mjs b/scripts/check-chat.mjs index e6b073cf..28a140d1 100644 --- a/scripts/check-chat.mjs +++ b/scripts/check-chat.mjs @@ -30,12 +30,16 @@ // 「正在理解需求」;输入框提示回答助手的问题;刷新后照样标「助手反问」,不当成没查库的回答; // 15. 回答上的「做成应用」带着这次运行进蓝图(建运行起点的蓝图),不再提取工作流、跳画布的发布弹窗; // 16. 服务端这一轮已经自查修正过(收到 check 的结论)还没过的:不再整轮重新生成一遍,直接说没过、给补救。 +// 17. 口径账本(next-round 02):交付了的轮次底部写「正在比对口径」,按退避再取到比对出结果、比完不再取;一行摘要 +// (几个数来自哪份口径)、按口径正式出具和对账按钮照服务端给的动作摆;出具、对账的写请求在浏览器层拦下并核对请求体, +// 出具过的正式运行挂在轮次下面(档位、打开运行)。 // // 所有写请求都被拦在浏览器里,不碰任何库。 // 跑之前前端得起着(./scripts/dev.sh),默认连 5273。对别的实例(比如一份沙箱拷贝)跑时 // 带上地址:AGENTLAB_WEB=http://localhost:<前端端口> node scripts/check-chat.mjs import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' import { mkdirSync, readFileSync } from 'node:fs' +import { ISSUE, RECONCILE, WHOLE, WHOLE_LABELS, ledgerOf } from './ledger-fixtures.mjs' const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' const CHROME = process.env.CHROME_PATH @@ -211,12 +215,20 @@ const REJECT_CONVS = { const ASKBACK_CONVS = { askBack: conv('c0askbk', '助手反问过的会话', 1, 60 * 24 * 34), } +/** 只在「口径账本」那段出现:库里存着一轮带证据的答案(evidence-doc 的周报),交付了,等着比对口径 */ +const LEDGER_CONVS = { + led: conv('c0ledgr', '问数据:上周的周报', 1, 60 * 24 * 32), +} /** 只在「问数据的证据」那段出现:库里存着一轮带证据的答案,刷新后回运行取 _evidence */ const ASK_CONVS = { askZ: conv('c0askz', '问数据:各区域销售额和最大的一单', 1, 60 * 24 * 33), } const DETAIL = { c0askbk: [turn('tab1', '上周销售额是多少', { answer: '销售额按下单日还是支付日算?', meta: { v: 1, asked: true } })], + c0ledgr: [turn('tl1', '上周的周报', { + answer: '(周报原文)', graph: GRAPH, run_id: 'run-led', + meta: { v: 1, runId: 'run-led', runClass: 'exploratory', runStatus: 'succeeded', evidence: true }, + })], c0askz: [turn('tz9', '上周各区域的销售额,最大的一单是多少', { answer: EVQ.output.answer, graph: GRAPH, run_id: 'run-evq', meta: { v: 1, runId: 'run-evq', runClass: 'exploratory', runStatus: 'succeeded', evidence: true }, @@ -361,6 +373,7 @@ const EVIDENCE = JSON.parse(readFileSync(new URL('../frontend/src/run/__tests__/ const RUNS = { 'run-evid': { status: 'succeeded', output: EVIDENCE.output, error: null }, 'run-evq': { status: 'succeeded', output: EVQ.output, error: null }, + 'run-led': { status: 'succeeded', output: EVIDENCE.output, error: null }, 'run-cancelled': { status: 'cancelled', output: {}, error: null }, 'run-failed': { status: 'failed', output: {}, error: '查询超时' }, 'run-rejected': { status: 'failed', output: {}, error: '人工驳回:数字对不上' }, @@ -419,6 +432,8 @@ const ctl = { extraSource: false, /** 列表里多摆「被驳回」那段的两个会话(REJECT_CONVS) */ rejectConvs: false, + /** 列表里多摆「口径账本」那段的会话(LEDGER_CONVS) */ + ledgerConvs: false, } /** 会话的归档 / 删除状态。各段各自 resetDb,免得上一段删掉的会话影响下一段 */ const db = { archived: new Set(), purged: new Set() } @@ -430,7 +445,8 @@ resetDb() const allConvs = () => [...Object.values(CONVS), ...Object.values(TRASHED), ...(ctl.trashMore ? Object.values(TRASH_MORE) : []), ...(ctl.guardConvs ? Object.values(GUARD_CONVS) : []), ...(ctl.askConvs ? Object.values(ASK_CONVS) : []), ...(ctl.askBack ? Object.values(ASKBACK_CONVS) : []), - ...(ctl.fixConvs ? Object.values(FIX_CONVS) : []), ...(ctl.rejectConvs ? Object.values(REJECT_CONVS) : [])] + ...(ctl.fixConvs ? Object.values(FIX_CONVS) : []), ...(ctl.rejectConvs ? Object.values(REJECT_CONVS) : []), + ...(ctl.ledgerConvs ? Object.values(LEDGER_CONVS) : [])] .filter((c) => !db.purged.has(c.id)) .map((c) => ({ ...c, archived: db.archived.has(c.id) })) let runSeq = 0 @@ -1507,6 +1523,100 @@ for (const theme of THEMES) { } }) + await section('ledger', '口径账本:轮次底部「正在比对口径」→ 摘要、按口径正式出具、对账(写请求在浏览器层拦下)', async () => { + ctl.ledgerConvs = true + try { + const { page, ctx, errors } = await open(theme) + // 文档记着的运行要和成果的运行对得上(run-led),片段、证据图按这次运行答 + await page.route(/\/api\/artifacts\//, (route) => route.fulfill({ json: { id: EVIDENCE.doc_artifact, + content: { ...EVIDENCE.doc, run_id: 'run-led' } } })) + await page.route(/\/api\/runs\/run-led\/evidence(\/.*)?(\?.*)?$/, (route) => { + const m = new URL(route.request().url()).pathname.match(/\/segments\/([^/]+)$/) + return m ? route.fulfill({ json: EVIDENCE.segments[decodeURIComponent(m[1])] ?? {} }) : route.fulfill({ json: EVIDENCE.graph }) + }) + // 账本:头两次答 pending(正在比对),之后比对过了:整题等价于受管口径「周报口径」v2,另有一条查询可以对账 + const led = { gets: [], writes: [], issued: [] } + await page.route(/\/api\/runs\/run-led\/ledger$/, (route) => { + led.gets.push(Date.now()) + if (led.gets.length <= 2) return route.fulfill({ json: { run_id: 'run-led', state: 'pending', note: '封存后比对,不在封存范围内' } }) + return route.fulfill({ json: ledgerOf('run-led', { labels: WHOLE_LABELS, whole: WHOLE, actions: [ISSUE, RECONCILE], + issued: led.issued }) }) + }) + await page.route(/\/api\/ledger\//, (route) => { + const req = route.request() + const path = new URL(req.url()).pathname + let body = null + try { body = req.postDataJSON() } catch { body = null } + led.writes.push({ key: `${req.method()} ${path}`, body }) + if (req.method() === 'POST' && path === '/api/ledger/answers/run-led/issue') { + led.issued = [{ run_id: 'run-iss-1', status: 'succeeded', end_reason: null, workflow_id: 'wf-weekly', version: 2, + tier: 'formal', tier_text: '完整出具', auto: false, created_at: iso(0) }] + return route.fulfill({ json: { run_id: 'run-iss-1', created: true, issued: led.issued[0] } }) + } + // 对账:这一段只核对按钮发出的请求体,结果卡片在 check-ledger 里看 + if (req.method() === 'POST' && path === '/api/ledger/answers/run-led/reconcile') { + return route.fulfill({ status: 409, json: { detail: '检查脚本:不真的发起对账', code: 'ledger_reconcile_refused' } }) + } + return route.fulfill({ status: 409, json: { detail: '检查脚本不写库' } }) + }) + await goto(page, 'c0ledgr') + const turnBox = page.locator('[data-turn]').first() + const waiting = await page.locator('[data-ledger-turn="waiting"]').first().waitFor({ timeout: 8000 }).then(() => true, () => false) + check('交付了的轮次:比对还没出结果时写「正在比对口径」', waiting + && (await page.locator('[data-ledger-turn="waiting"]').first().innerText()).includes('正在比对口径')) + const summary = page.locator('[data-ledger-summary]').first() + const shown = await summary.waitFor({ timeout: 10000 }).then(() => true, () => false) + check('按退避再取,比对出结果后写摘要(不靠实时流)', shown && led.gets.length === 3, `${led.gets.length} 次`) + const gaps = led.gets.slice(1).map((t, i) => t - led.gets[i]) + check('……隔得越来越久(退避),不是每一拍都取', gaps.length === 2 && gaps[0] >= 700 && gaps[1] >= gaps[0] - 100, + gaps.join('ms, ') + 'ms') + const text = (await summary.innerText()).replace(/\s+/g, ' ') + check('摘要:几个数来自哪份口径', text.includes('3 个数来自口径「周报口径」v2(受管)'), text) + check('整题等价:写等价于哪份口径、怎么认的', (await page.locator('[data-ledger-whole]').first().innerText()) + .includes('整题等价于口径「周报口径」v2(受管) · 等价已证明')) + await page.waitForTimeout(3500) + check('比对过了、没有要等的:不再取', led.gets.length === 3, `${led.gets.length} 次`) + const issueBtn = page.locator('[data-ledger-issue-button]').first() + check('按服务端的动作摆「按口径正式出具」,下面写为什么不自动', await issueBtn.count() === 1 + && (await page.locator('[data-ledger-auto-reason]').first().innerText()).includes('设置里关了自动按口径出具')) + check('有相关口径:摆「对账」按钮', (await page.locator('[data-ledger-turn-reconcile]').first().innerText()).includes('对账:「订单口径」v1(已发布)')) + check('数字上挂着来自口径的小标记', await turnBox.locator('[data-ev-caliber-of="s6"]').count() === 1) + + await issueBtn.click() + const posted = await until(() => led.writes.some((w) => w.key === 'POST /api/ledger/answers/run-led/issue'), 5000) + const issueBody = led.writes.find((w) => w.key === 'POST /api/ledger/answers/run-led/issue')?.body + check('出具的请求只说按哪份口径(参数由服务端从比对里取)', posted + && JSON.stringify(issueBody) === JSON.stringify({ workflow_id: 'wf-weekly', version: 2 }), JSON.stringify(issueBody)) + const issued = page.locator('[data-ledger-issued="run-iss-1"]').first() + const issuedShown = await issued.waitFor({ timeout: 6000 }).then(() => true, () => false) + const issuedText = issuedShown ? (await issued.innerText()).replace(/\s+/g, ' ') : '' + check('出具的正式运行挂在轮次下面:写档位', issuedText.includes('按口径正式出具') && issuedText.includes('「周报口径」v2(受管)') + && issuedText.includes('完整出具'), issuedText) + check('……点开去运行', await issued.locator('a[href="/runs/run-iss-1"]').count() === 1) + check('出具过了:不再摆出具按钮', await page.locator('[data-ledger-issue-button]').count() === 0) + + await page.locator('[data-ledger-turn-reconcile]').first().click() + const dialog = page.locator('[data-ledger-reconcile-dialog]') + check('点「对账」打开对账:差在哪、核对参数', await dialog.waitFor({ timeout: 4000 }).then(() => true, () => false) + && (await dialog.innerText()).includes('口径只保留状态为已支付的行') && (await dialog.innerText()).includes('参数按这次的 SQL 推断,请核对')) + await page.locator('[data-ledger-param-input="start"]').fill('2026-09-02') + await page.locator('[data-ledger-reconcile-launch]').click() + await until(() => led.writes.some((w) => w.key === 'POST /api/ledger/answers/run-led/reconcile'), 5000) + const recBody = led.writes.find((w) => w.key === 'POST /api/ledger/answers/run-led/reconcile')?.body + check('对账的请求:哪条查询、哪份口径、核对过的参数(confirm)', recBody?.query === 'q-orders' && recBody?.workflow_id === 'wf-orders' + && recBody?.version === 1 && recBody?.confirm === true && recBody?.inputs?.start === '2026-09-02' && !('store' in (recBody?.inputs ?? {})), + JSON.stringify(recBody)) + check('服务端拒了:照它的话写在对账框里', (await page.locator('[data-ledger-reconcile-problem]').innerText().catch(() => '')) + .includes('检查脚本:不真的发起对账')) + check('写请求只有出具、对账这两次(都在浏览器层拦下)', led.writes.length === 2, led.writes.map((w) => w.key).join(' | ')) + await page.screenshot({ path: `${SHOTS}/ledger-${theme}.png` }) + check('没有运行时报错', errors.length === 0, errors[0] ?? '') + await ctx.close() + } finally { + ctl.ledgerConvs = false + } + }) + await section('fixfirst', '要改的东西在工具库里:先去改参数定义,「接着跑」退成次要', async () => { ctl.fixConvs = true try { diff --git a/scripts/check-evidence.mjs b/scripts/check-evidence.mjs index bef463b4..84d326b8 100644 --- a/scripts/check-evidence.mjs +++ b/scripts/check-evidence.mjs @@ -17,6 +17,7 @@ // EVIDENCE_SHOTS=<目录> 时亮暗两套各截几张,供人眼复核。 import { readFileSync } from 'node:fs' import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' +import { ledgerOf } from './ledger-fixtures.mjs' const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' const CHROME = process.env.CHROME_PATH @@ -106,6 +107,13 @@ async function routed(page, { judge = null, segPatch = null, prov = null, graph return r.fulfill({ status: reply.status ?? 200, json: reply.json }) } if (req.method() !== 'GET') return r.abort() + // 口径账本(next-round 02):证据正文、面板会按运行取一次。各节的夹具都不比对(只有「口径账本」那一节另给答复), + // 免得落到真服务端、按夹具的假运行答 404 + const lm = url.pathname.match(/^\/api\/runs\/([^/]+)\/ledger$/) + if (lm) { + hits.push(`ledger:${decodeURIComponent(lm[1])}`) + return r.fulfill({ json: { run_id: decodeURIComponent(lm[1]), state: 'ineligible', reason: '检查脚本的夹具不比对口径' } }) + } const pm = url.pathname.match(/\/api\/runs\/([^/]+)\/evidence\/segments\/([^/]+)\/provenance$/) if (pm) { const [run, sid] = [decodeURIComponent(pm[1]), decodeURIComponent(pm[2])] @@ -4130,6 +4138,75 @@ await section('ask', '期 4:句末「质询」图标平时的对比度—— await r.ctx.close() }) +await section('ledger', '口径账本:来自口径的数字挂小标记(受管 / 已发布),面板出处链最上面「口径」一步分三种情况', async () => { + // 来自口径的数加一个小标记、写明受管还是已发布;相关口径的数不加标记,只在面板里说。面板「口径」一步:来自口径——「X」v3 + //(受管)· 参数 · 怎么认的;相关口径——差在哪 + 看差多少;这次的推理——没有相关的已发布口径(02 做法 3、11) + const LED = ledgerOf(fx.run_id) + let asked = 0 + const r = await open('/ui-harness.html?evidence=1', { before: (page) => page.route( + (u) => new URL(u).pathname === `/api/runs/${fx.run_id}/ledger`, (route) => { asked += 1; return route.fulfill({ json: LED }) }) }) + const p = r.page + await p.waitForSelector('#evidence-wide [data-ev-caliber-of="s6"]', { timeout: 6000 }).catch(() => {}) + const mark = (id) => p.evaluate((sid) => { + const el = document.querySelector(`#evidence-wide [data-ev-caliber-of="${sid}"]`) + const seg = document.querySelector(`#evidence-wide [data-seg="${sid}"]`) + return el ? { text: el.textContent, title: el.getAttribute('title'), level: el.getAttribute('data-ev-caliber'), + hidden: el.getAttribute('aria-hidden'), aria: seg?.getAttribute('aria-label') ?? '', + after: seg?.nextElementSibling === el } : null + }, id) + const s6 = await mark('s6') + check('受管口径的数挂「受管」小标记,紧跟在数字后面', s6?.text === '受管' && s6.level === 'governed' && s6.after, JSON.stringify(s6)) + check('……悬停写是哪一份口径、怎么认的', s6?.title === '来自口径「周报口径」v2(受管) · 等价已证明', s6?.title) + check('……标记不进读屏(读屏念在数字上)', s6?.hidden === 'true' && s6.aria.includes('来自口径「周报口径」v2(受管),等价已证明'), s6?.aria) + const s10 = await mark('s10') + check('已发布口径、助手选用的数挂「已发布」', s10?.text === '已发布' && s10.title.includes('助手选用'), JSON.stringify(s10)) + check('相关口径、这次的推理、没比对的数都不挂标记', !(await mark('s8')) && !(await mark('s12')) && !(await mark('s23'))) + check('标记只挂在面向读者的正文上:窄栏那份同样挂', await p.locator('#evidence-narrow [data-ev-caliber-of="s6"]').count() === 1) + + const part = () => p.locator('[data-evidence-panel] [data-ev-ledger]') + await openSeg(p, 's6', '[data-ev-ledger]') + const caliber = await part().innerText().catch(() => '') + check('来自口径:「口径」一步写口径、级别、怎么认的', await part().getAttribute('data-ev-ledger').catch(() => null) === 'caliber' + && caliber.includes('来自口径「周报口径」v2(受管)') && caliber.includes('等价已证明'), caliber.replace(/\s+/g, ' ')) + check('……写参数', caliber.includes('week = 2026-W37'), caliber.replace(/\s+/g, ' ')) + check('……脚注写明封存后比对、不在封存范围内', caliber.includes('封存后比对,不在封存范围内')) + const order = await p.evaluate(() => { + const body = document.querySelector('[data-evidence-panel] [data-ev-body]') + const kids = [...(body?.children ?? [])] + const at = (sel) => kids.findIndex((k) => k.matches(sel) || !!k.querySelector(sel)) + return { sentence: at('[data-ev-sentence]'), ledger: at('[data-ev-ledger]'), metric: at('[data-ev-metric], [data-ev-metric-step]'), + seal: at('[data-ev-seal]') } + }) + check('「口径」一步在出处链最上面:紧跟句子,在指标步骤、封存之前', order.ledger === order.sentence + 1 + && (order.metric < 0 || order.ledger < order.metric) && order.ledger < order.seal, JSON.stringify(order)) + check('整题不等价:这个数上没有「按口径正式出具」', await p.locator('[data-evidence-panel] [data-ledger-issue-button]').count() === 0) + + await openSeg(p, 's10', '[data-ev-ledger="caliber"]') + const composed = await part().innerText().catch(() => '') + check('助手选用:写「助手选用」和由人确认的说明', composed.includes('助手选用') && composed.includes('要由人确认'), composed.replace(/\s+/g, ' ')) + check('……绑定的遮罩值只写「已遮罩」', composed.includes('store = 已遮罩'), composed.replace(/\s+/g, ' ')) + + await openSeg(p, 's8', '[data-ev-ledger="related"]') + const related = await part().innerText().catch(() => '') + check('相关口径:写哪一份、差在哪', related.includes('相关口径「订单口径」v1(已发布)') && related.includes('差在哪') + && related.includes('口径只保留状态为已支付的行,这次没有这个条件'), related.replace(/\s+/g, ' ')) + check('……给「看差多少」(服务端给了对账这一项)', await p.locator('[data-evidence-panel] [data-ledger-reconcile-open]').count() === 1) + + await openSeg(p, 's12', '[data-ev-ledger="reasoning"]') + const reasoning = await part().innerText().catch(() => '') + check('这次的推理:写「没有相关的已发布口径」', reasoning.includes('这次的推理') && reasoning.includes('没有相关的已发布口径'), reasoning) + + await openSeg(p, 's23', '[data-ev-ledger="unknown"]') + const unknown = await part().innerText().catch(() => '') + check('没有比对:写原因', unknown.includes('没有比对') && unknown.includes('比对超过时限,没有做完'), unknown) + + await openSeg(p, 's4', '[data-ev-seal-state]') + check('不是数的片段(运行输入)不画「口径」一步', await part().count() === 0) + check('同一次运行只取一次账本(正文两份、面板开了几次都共用一份,比对过了不再轮询)', asked === 1, `${asked} 次`) + check('没有运行时报错', r.errors.length === 0, r.errors.join(' | ')) + await r.ctx.close() +}) + check('没有运行时报错(组件预览)', harness.errors.length === 0, harness.errors.join(' | ')) await harness.ctx.close() await browser.close() diff --git a/scripts/check-ledger.mjs b/scripts/check-ledger.mjs index eac430e3..62000b94 100644 --- a/scripts/check-ledger.mjs +++ b/scripts/check-ledger.mjs @@ -1,7 +1,401 @@ #!/usr/bin/env node -// 口径账本的界面检查(docs/design/next-round 02 做法 8)。 +// 口径账本的界面检查(docs/design/next-round/02-口径账本.md 做法 3–6、8 的界面,第 4 波 W4-c)。 // -// 第 4 波骨架里的占位:check-all 先登记好名字,W4-c 换成真检查(假接口加夹具,照 check-share 的写法)。 -console.log('=== 占位 ===') -console.log(' ✓ 占位:W4-c 换成真检查') -console.log('\n✓ 占位通过') +// 守的是: +// - 证据面板「口径」一步:比对还没出结果时写「正在比对口径」,按退避再取(不靠实时流:ledger.matched 在事件总线关闭 +// 之后才追加);等满了还没有结论照实说、给「再取一次」,点了重新取、取到就画;三种情况(来自口径 / 相关口径 / 这次的 +// 推理)各写各的; +// - 口径对账:核对参数(推断的参数要先核对)→ 发起(认不出列怎么配时照 409 带回的选项选对照的指标,再发起)→ 结果卡片: +// 这次 / 口径 / 差值 / 相对差四个数各自取值、点开是出处链;请求体逐项核对; +// - 可沉淀的问题:工作流列表弹窗里的抽屉,三类来源分开写;「固化成口径草稿」走 from-run 的 freeze(带同组的别的运行)、 +// 打开画布;聚类按人挑的那一轮固化;「不是口径」要写理由; +// - 使用者看到的入口照服务端的动作:不能出具的写原因(请搭建者出具)、不摆出具按钮,能对账的照样对账;出具过的正式运行 +// 不给打开运行的链接(使用者读不了它的原始记录),写由搭建者查看; +// - 设置里口径账本一组:和其余偏好共用保存条,整组写 ledger,值不合规不让存。 +// +// 不写库:所有写请求都在浏览器层拦下(伪造的答复),核对请求体;认不出的写请求一律 409 并记账,检查结束时必须是空的。 +// 夹具见 scripts/ledger-fixtures.mjs(挂在可点击证据的夹具 evidence-doc.json 上,只用通用名)。 +// +// 跑之前前端得起着(./scripts/dev.sh),默认连 5273: +// AGENTLAB_WEB=http://localhost:<前端端口> node scripts/check-ledger.mjs +import { readFileSync } from 'node:fs' +import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' +import { + ISSUE, QUEUE, RECONCILE, RECONCILE_VALUES, WHOLE, WHOLE_LABELS, ledgerOf, metricDetail, reconciledOf, +} from './ledger-fixtures.mjs' + +const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' +const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' +const ONLY = (process.env.CHECK_ONLY ?? '').split(',').map((s) => s.trim()).filter(Boolean) +const fx = JSON.parse(readFileSync(new URL('../frontend/src/run/__tests__/evidence-doc.json', import.meta.url), 'utf8')) +const RUN = fx.run_id + +let failed = 0 +const check = (name, cond, detail = '') => { + const d = String(detail ?? '').replace(/\s+/g, ' ').slice(0, 200) + console.log(` ${cond ? '✓' : '✗'} ${name}${d ? ` — ${d}` : ''}`) + if (!cond) failed++ +} +const opened = new Set() +async function section(name, fn) { + if (ONLY.length && !ONLY.some((k) => name.includes(k))) return + console.log(`\n=== ${name} ===`) + try { + await fn() + } catch (e) { + check(`${name} 中途出错`, false, String(e?.message ?? e).split('\n')[0]) + } finally { + for (const c of opened) await c.close().catch(() => {}) + opened.clear() + } +} +const until = async (fn, ms = 6000, step = 100) => { + const end = Date.now() + ms + let v = await fn() + while (!v && Date.now() < end) { + await new Promise((r) => setTimeout(r, step)) + v = await fn() + } + return v +} +const stray = [] +const ADMIN = { mode: 'off', username: null, display_name: null, role: 'admin', groups: [], verified: false } +const USER = { mode: 'local', username: 'carol', display_name: '使用者丙', role: 'user', groups: [], verified: true, user_can_chat: true } + +const browser = await chromium.launch({ executablePath: CHROME }) + +/** + * 开一页:/api/ 下的请求按 reply 答,记下每个请求(sent);reply 不认的 GET 交给真服务端,不认的写请求一律 409 并记进 + * stray(检查结束时必须是空的) + */ +async function open(path, { me = ADMIN, reply = () => null, w = 1280, h = 900 } = {}) { + const ctx = await browser.newContext({ viewport: { width: w, height: h } }) + opened.add(ctx) + ctx.setDefaultTimeout(8000) + const page = await ctx.newPage() + const errors = [] + const sent = [] + page.on('pageerror', (e) => errors.push(e.message)) + page.on('dialog', (d) => { errors.push(`原生对话框:${d.message()}`); void d.dismiss() }) + await page.route((u) => new URL(u).pathname.startsWith('/api/'), async (route) => { + const req = route.request() + const url = new URL(req.url()) + const p = decodeURIComponent(url.pathname.replace(/^\/api/, '')) + let body = null + try { body = req.postDataJSON() } catch { body = null } + sent.push({ key: `${req.method()} ${p}`, body, at: Date.now() }) + if (p === '/auth/me') return route.fulfill({ json: me }) + const out = await reply(req.method(), p, body, url) + if (out) return route.fulfill({ status: out.status ?? 200, json: out.json ?? {} }) + if (req.method() === 'GET') return route.continue() + stray.push(`${req.method()} ${p}`) + return route.fulfill({ status: 409, json: { detail: '检查脚本不写库' } }) + }) + await page.goto(`${WEB}${path}`, { waitUntil: 'domcontentloaded' }) + return { ctx, page, errors, sent } +} + +/** 可点击证据的组件预览页:片段接口、证据图按夹具答,账本按 ledger() 答 */ +function evidenceReply(ledger, extra = () => null) { + return async (method, p, body, url) => { + const more = await extra(method, p, body, url) + if (more) return more + if (method !== 'GET') return null + if (p === `/runs/${RUN}/ledger`) return { json: await ledger() } + const seg = p.match(new RegExp(`^/runs/${RUN}/evidence/segments/([^/]+)$`)) + if (seg) return fx.segments[seg[1]] ? { json: fx.segments[seg[1]] } : { status: 404, json: { detail: '报告中没有这个片段' } } + if (p === `/runs/${RUN}/evidence`) return { json: fx.graph } + // 组件预览页上别的几份夹具:不比对 + const other = p.match(/^\/runs\/([^/]+)\/ledger$/) + if (other) return { json: { run_id: other[1], state: 'ineligible', reason: '检查脚本的夹具不比对口径' } } + return null + } +} + +const panelPart = (page) => page.locator('[data-evidence-panel] [data-ev-ledger]') +async function openSeg(page, id) { + await page.locator(`#evidence-wide [data-seg="${id}"]`).click() + await page.waitForSelector('[data-evidence-panel]', { timeout: 4000 }).catch(() => {}) +} + +// ---------------------------------------------------------------- 正在比对、退避、等满了、再取一次 + +await section('比对还没出结果:正在比对口径、按退避再取、等满了照实说、再取一次', async () => { + const state = { matched: false, gets: [] } + const { page, errors } = await open('/ui-harness.html?evidence=1', { reply: evidenceReply(() => { + state.gets.push(Date.now()) + return state.matched ? ledgerOf(RUN) : { run_id: RUN, state: 'pending', note: '封存后比对,不在封存范围内' } + }) }) + await page.waitForSelector('[data-evidence-doc]', { timeout: 10000 }) + await openSeg(page, 's6') + const waiting = await page.locator('[data-evidence-panel] [data-ledger-state="pending"]').waitFor({ timeout: 5000 }).then(() => true, () => false) + check('「口径」一步写「正在比对口径」', waiting && (await panelPart(page).innerText()).includes('正在比对口径')) + check('……说明比完会自动更新', (await panelPart(page).innerText()).includes('比完这里会自动更新')) + check('还没比完时正文上不挂小标记', await page.locator('[data-ev-caliber-of]').count() === 0) + await until(() => state.gets.length >= 4, 9000) + const gaps = state.gets.slice(1).map((t, i) => t - state.gets[i]) + check('按退避再取:间隔越来越长(1、2、3 秒……)', state.gets.length >= 4 && gaps[0] >= 700 && gaps[1] >= gaps[0] - 150 + && gaps[2] >= gaps[1] - 150, gaps.map((g) => `${g}ms`).join(', ')) + // 把这一轮等待的起点挪到两分钟以前:下一次取回来还是 pending,就该照实说等满了,不再取 + await page.evaluate((run) => window.__ledger.setState((s) => ({ slots: { ...s.slots, [run]: { ...s.slots[run], since: Date.now() - 200_000 } } })), RUN) + const timedOut = await page.locator('[data-evidence-panel] [data-ledger-state="timeout"]').waitFor({ timeout: 15000 }).then(() => true, () => false) + check('等满了还没有结论:照实说,给「再取一次」', timedOut + && (await panelPart(page).innerText()).includes('比对口径还没有结果') && await page.locator('[data-ledger-retry]').count() >= 1) + const after = state.gets.length + await page.waitForTimeout(3500) + check('……等满了就不再取', state.gets.length === after, `${state.gets.length - after} 次`) + state.matched = true + await page.locator('[data-evidence-panel] [data-ledger-retry]').click() + const drawn = await page.locator('[data-evidence-panel] [data-ev-ledger="caliber"]').waitFor({ timeout: 5000 }).then(() => true, () => false) + check('点「再取一次」:重新取,比对过了就画出来', drawn && state.gets.length === after + 1, `${state.gets.length - after} 次`) + check('正文上的小标记跟着出来', await page.locator('#evidence-wide [data-ev-caliber-of="s6"]').count() === 1) + await page.waitForTimeout(2500) + check('比对过了、没有要等的:不再取', state.gets.length === after + 1, `${state.gets.length - after} 次`) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +// ---------------------------------------------------------------- 三种情况 + +await section('「口径」一步的三种情况:来自口径、相关口径、这次的推理', async () => { + const { page, errors } = await open('/ui-harness.html?evidence=1', { reply: evidenceReply(() => ledgerOf(RUN, { retro: true })) }) + await page.waitForSelector('#evidence-wide [data-ev-caliber-of="s6"]', { timeout: 10000 }) + await openSeg(page, 's6') + await page.locator('[data-evidence-panel] [data-ev-ledger="caliber"]').waitFor({ timeout: 5000 }) + const caliber = await panelPart(page).innerText() + check('来自口径:口径、版本、级别、怎么认的、参数', caliber.includes('来自口径「周报口径」v2(受管)') && caliber.includes('等价已证明') + && caliber.includes('week = 2026-W37'), caliber) + check('……事后补比的写「按现在的口径回看」', caliber.includes('封存后比对,不在封存范围内 · 按现在的口径回看'), caliber) + await openSeg(page, 's8') + await page.locator('[data-evidence-panel] [data-ev-ledger="related"]').waitFor({ timeout: 5000 }) + const related = await panelPart(page).innerText() + check('相关口径:差在哪 + 看差多少', related.includes('相关口径「订单口径」v1(已发布)') && related.includes('口径只保留状态为已支付的行') + && await page.locator('[data-evidence-panel] [data-ledger-reconcile-open]').count() === 1, related) + check('……这个数本身是这次的推理(照实说)', related.includes('这个数是这次的推理'), related) + await openSeg(page, 's12') + await page.locator('[data-evidence-panel] [data-ev-ledger="reasoning"]').waitFor({ timeout: 5000 }) + check('这次的推理:没有相关的已发布口径', (await panelPart(page).innerText()).includes('没有相关的已发布口径')) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +// ---------------------------------------------------------------- 对账 + +await section('口径对账:核对参数 → 发起 → 选对照的指标 → 三个数各自点得开', async () => { + const state = { posts: [], reconciled: [], polls: 0 } + const extra = (method, p, body) => { + if (method === 'POST' && p === `/ledger/answers/${RUN}/reconcile`) { + state.posts.push(body) + if (!body?.pairs) { + return { status: 409, json: { detail: '认不出这次的哪一列对应口径的哪个指标,请选择要对照的指标', code: 'ledger_reconcile_needs_pairs', + options: { columns: ['orders', 'refunds'], metrics: [{ id: 'orders', name: '订单数', unit: '单' }] } } } + } + state.reconciled = [reconciledOf('running')] + return { status: 201, json: { run_id: 'run-rec-1', reconciled: state.reconciled[0] } } + } + const m = p.match(/^\/runs\/run-rec-1\/evidence\/metrics\/reconcile\/([^/]+)$/) + if (method === 'GET' && m) return { json: metricDetail('run-rec-1', m[1]) } + return null + } + const ledger = () => { + // 发起之后:第一次取回来对账还在进行中,再取一次就做完了 + if (state.reconciled[0]?.status === 'running') { + state.polls += 1 + if (state.polls > 1) state.reconciled = [reconciledOf('succeeded')] + } + return ledgerOf(RUN, { reconciled: state.reconciled }) + } + const { page, errors } = await open('/ui-harness.html?evidence=1', { reply: evidenceReply(ledger, extra) }) + await page.waitForSelector('#evidence-wide [data-seg="s8"]', { timeout: 10000 }) + await openSeg(page, 's8') + await page.locator('[data-evidence-panel] [data-ledger-reconcile-open]').click() + const dialog = page.locator('[data-ledger-reconcile-dialog]') + await dialog.waitFor({ timeout: 4000 }) + const text = await dialog.innerText() + check('对账框:差在哪、写明只读', text.includes('口径只保留状态为已支付的行') && text.includes('只读'), text) + check('参数是推断的:先核对(表单直接打开、写原因)', await page.locator('[data-ledger-params="edit"]').count() === 1 + && text.includes('参数按这次的 SQL 推断,请核对')) + check('表单照动作里的入口字段画:推断出的值填好,有缺省值的写明留空用缺省值', + await page.locator('[data-ledger-param-input="start"]').inputValue() === '2026-09-01' + && await page.locator('[data-ledger-param-input="store"]').inputValue() === '' && text.includes('留空用口径的缺省值')) + await page.locator('[data-ledger-param-input="start"]').fill('2026-09-03') + await page.locator('[data-ledger-reconcile-launch]').click() + await until(() => state.posts.length === 1) + check('第一次发起:带核对过的参数(confirm),空着的不送', JSON.stringify(state.posts[0]) === JSON.stringify({ + query: 'q-orders', workflow_id: 'wf-orders', version: 1, inputs: { start: '2026-09-03' }, confirm: true }), JSON.stringify(state.posts[0])) + const pairs = await page.locator('[data-ledger-pairs]').waitFor({ timeout: 4000 }).then(() => true, () => false) + check('认不出列怎么配:照服务端给的选项画「选择要对照的指标」', pairs && await page.locator('[data-ledger-pair]').count() === 2 + && (await page.locator('[data-ledger-reconcile-problem]').innerText()).includes('请选择要对照的指标')) + await page.locator('[data-ledger-reconcile-launch]').click() + check('一组都没选:不发起,说要至少选一组', state.posts.length === 1 + && (await page.locator('[data-ledger-reconcile-problem]').innerText()).includes('至少选一组对照')) + await page.locator('[data-ledger-pair="orders"]').selectOption('orders') + await page.locator('[data-ledger-reconcile-launch]').click() + await until(() => state.posts.length === 2) + check('选好再发起:带上对照(这次的列 → 口径卡上的指标)', JSON.stringify(state.posts[1]?.pairs) === JSON.stringify([{ ours: 'orders', metric: 'orders' }]) + && state.posts[1]?.confirm === true, JSON.stringify(state.posts[1])) + check('发起之后对账框收起', await until(async () => await dialog.count() === 0, 4000)) + const card = page.locator('[data-evidence-panel] [data-ledger-reconciled="run-rec-1"]') + const running = await card.waitFor({ timeout: 6000 }).then(() => true, () => false) + check('结果卡片:对账运行还在进行时写「对账进行中」', running && (await card.innerText()).includes('对账进行中')) + const done = await page.locator('[data-evidence-panel] [data-ledger-reconciled-state="succeeded"]').waitFor({ timeout: 12000 }).then(() => true, () => false) + check('……再取一次(运行还没结束时接着等),做完了画出每组对照', done) + await until(async () => (await card.innerText()).includes(RECONCILE_VALUES.diff_0), 5000) + const cardText = (await card.innerText()).replace(/\s+/g, ' ') + check('四个数:按你的问法、按口径、差值、相对差', cardText.includes(`按你的问法 ${RECONCILE_VALUES.ours_0}`) + && cardText.includes(`按口径 ${RECONCILE_VALUES.cal_0}`) && cardText.includes(`差值 ${RECONCILE_VALUES.diff_0}`) + && cardText.includes(`相对差 ${RECONCILE_VALUES.rel_0}`), cardText) + check('……写参数从哪来、原答案里写的是什么', cardText.includes('按核对过的参数') && cardText.includes('原答案里写的是 8.7%'), cardText) + await card.locator('[data-ledger-value="diff_0"]').click() + const drawer = page.locator('[data-evidence-panel="side"]').last() + const opened = await until(async () => (await drawer.innerText().catch(() => '')).includes('差值'), 5000) + check('点差值:打开它的出处链(同应用页点数)', opened, (await drawer.innerText().catch(() => '')).slice(0, 80)) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +// ---------------------------------------------------------------- 可沉淀的问题 + +const WF = { id: 'wf-led-check', name: '检查用工作流', description: '', version: 1, status: 'draft', tags: [], is_template: false, + graph: { nodes: [{ id: 'in', type: 'input', position: { x: 0, y: 0 }, data: { label: '入口', config: { fields: [] } } }], edges: [] } } +const FROZEN = { ...WF, id: 'wf-frozen', name: '上周销售额是多少(固化的口径草稿)', tags: ['certified'] } + +await section('可沉淀的问题:工作流列表的抽屉,三类来源分开写,固化成口径草稿、不是口径要写理由', async () => { + const state = { queue: structuredClone(QUEUE), freezes: [], dismisses: [] } + const reply = (method, p, body) => { + if (method === 'GET' && p === `/workflows/${WF.id}`) return { json: WF } + if (method === 'GET' && p === `/workflows/${FROZEN.id}`) return { json: FROZEN } + if (method === 'POST' && p === '/workflows/validate') return { json: { ok: true, issues: [] } } + if (method === 'POST' && p === '/workflows/variables') return { json: { variables: [], issues: [] } } + if (p.startsWith('/conversations')) return { json: method === 'GET' ? [] : { id: 'cv', kind: 'canvas', title: '', turns: [] } } + if (method === 'GET' && p === '/ledger/certify-queue') return { json: state.queue } + if (method === 'POST' && p === '/ledger/certify-queue/dismiss') { + state.dismisses.push(body) + return { json: { ok: true, item_id: body?.item_id } } + } + if (method === 'POST' && p === '/copilot/from-run') { + state.freezes.push(body) + return { json: { workflow_id: FROZEN.id, name: FROZEN.name, nodes: 5, edges: 4, params: ['p1'], metrics: ['m1'], sources: [] } } + } + return null + } + const { page, errors } = await open(`/studio/${WF.id}`, { reply }) + await page.locator('button[title="切换、新建、从模板新建工作流"]').click() + await page.locator('[data-certify-open]').click() + const drawer = page.locator('[data-certify-drawer]') + await drawer.waitFor({ timeout: 5000 }) + await page.locator('[data-certify-item]').first().waitFor({ timeout: 5000 }) + const kinds = await page.locator('[data-certify-kind]').evaluateAll((els) => els.map((e) => e.getAttribute('data-certify-kind'))) + check('三类来源分开列:确定性重复、问题聚类、被反复用的答案', JSON.stringify(kinds) === JSON.stringify(['shape', 'cluster', 'reused']), kinds.join(',')) + const text = (await drawer.innerText()).replace(/\s+/g, ' ') + check('各类写明是怎么认出来的(聚类不等于口径相同)', text.includes('确定性重复:同样形状的 SQL') && text.includes('问法相近不等于口径相同'), text.slice(0, 200)) + check('确定性重复:几次运行、几段对话、参数候选、已有相关口径', text.includes('4 次运行 · 3 段对话') && text.includes('1 个参数候选 · 1 个口径常量') + && text.includes('已有相关口径'), text.slice(0, 300)) + check('被反复用的答案:怎么被用的、已固化成哪张草稿', text.includes('导出 2 次 · 在画布里打开过') && text.includes('本月新客数(固化的口径草稿)')) + const cluster = page.locator('[data-certify-item="cluster:bb22"]') + check('问题聚类没有共同的 SQL:不给整项固化,按人挑的那一轮固化', await cluster.locator('[data-certify-freeze]').count() === 0 + && await cluster.locator('[data-certify-freeze-turn]').count() === 2) + + await cluster.locator('[data-certify-dismiss]').click() + const dialog = page.getByRole('dialog', { name: '这不是口径' }) + await dialog.waitFor({ timeout: 4000 }) + check('「不是口径」不写理由:确认键不能点', await dialog.getByRole('button', { name: '确认不是口径' }).isDisabled() + && state.dismisses.length === 0) + await dialog.getByRole('textbox').fill('问的是各门店的临时核对') + await dialog.getByRole('button', { name: '确认不是口径' }).click() + await until(() => state.dismisses.length === 1) + check('写了理由才记下:请求带这一项、种类和理由', JSON.stringify(state.dismisses[0]) === JSON.stringify({ + item_id: 'cluster:bb22', kind: 'cluster', note: '问的是各门店的临时核对' }), JSON.stringify(state.dismisses[0])) + check('……这一项从抽屉里拿掉', await until(async () => await page.locator('[data-certify-item="cluster:bb22"]').count() === 0, 3000)) + + await page.locator('[data-certify-item="shape:aa11"] [data-certify-freeze]').click() + await until(() => state.freezes.length === 1) + check('固化成口径草稿:走 from-run 的 freeze,带同组的别的运行和来源轮次', JSON.stringify(state.freezes[0]) === JSON.stringify({ + run_id: 'run-s1', freeze: true, peers: ['run-s2', 'run-s3'], conversation_id: 'c-1', turn_id: 't-1' }), JSON.stringify(state.freezes[0])) + check('……打开画布里的草稿', await until(() => new URL(page.url()).pathname === `/studio/${FROZEN.id}`, 5000), page.url()) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +// ---------------------------------------------------------------- 使用者 + +await section('使用者看到的入口照服务端的动作:不能出具的写原因,能对账的照样对账,出具的运行不给链接', async () => { + const EV = JSON.parse(readFileSync(new URL('../frontend/src/run/__tests__/evidence-doc.json', import.meta.url), 'utf8')) + const RUN_U = 'run-user-led' + const at = new Date(Date.now() - 86400e3).toISOString() + const conv = { id: 'c-user-led', title: '问数据:上周的周报', kind: 'chat', workflow_id: null, archived: false, created_at: at, + last_active_at: at, turn_count: 1, last_question: '上周的周报', last_status: 'done', last_run_id: RUN_U } + const turn = { id: 'tu1', seq: 0, question: '上周的周报', answer: '(周报原文)', explanation: '', graph: null, run_id: RUN_U, + status: 'done', error: '', review: null, created_at: at, + meta: { v: 1, runId: RUN_U, runClass: 'exploratory', runStatus: 'succeeded', evidence: true } } + const refused = { ...ISSUE, available: false, auto: false, reason: '这份口径没有被你能使用的应用固定,不能由你按口径出具,请搭建者出具' } + delete refused.auto_reason + const LED = ledgerOf(RUN_U, { labels: WHOLE_LABELS, whole: WHOLE, actions: [refused, RECONCILE], + // 出具过的是另一份口径(订单口径):周报口径这一项还没出具过,照服务端的原因写为什么不能出具 + issued: [{ run_id: 'run-iss-u', status: 'succeeded', workflow_id: 'wf-orders', version: 1, tier: 'degraded', tier_text: '降档出具', auto: true }] }) + const reply = (method, p) => { + if (method === 'GET' && p === '/conversations') return { json: [conv] } + if (method === 'GET' && p === `/conversations/${conv.id}`) return { json: { ...conv, turns: [turn] } } + if (p.startsWith('/conversations')) return { json: {} } + if (method === 'GET' && p === `/runs/${RUN_U}`) return { json: { id: RUN_U, status: 'succeeded', run_class: 'exploratory', output: EV.output, usage: {} } } + if (method === 'GET' && p === `/runs/${RUN_U}/events`) return { json: [] } + if (method === 'GET' && p === `/runs/${RUN_U}/ledger`) return { json: LED } + if (method === 'GET' && p === `/runs/${RUN_U}/evidence`) return { json: EV.graph } + if (method === 'GET' && p.startsWith('/artifacts/')) return { json: { id: EV.doc_artifact, content: { ...EV.doc, run_id: RUN_U } } } + if (method === 'GET' && p.startsWith('/approvals')) return { json: [] } + return null + } + const { page, errors } = await open(`/chat/${conv.id}`, { me: USER, reply }) + const box = page.locator('[data-ledger-turn="matched"]').first() + const shown = await box.waitFor({ timeout: 12000 }).then(() => true, () => false) + const text = shown ? (await box.innerText()).replace(/\s+/g, ' ') : '' + check('使用者也看到摘要', text.includes('3 个数来自口径「周报口径」v2(受管)'), text) + check('不能出具:照服务端的原因写「请搭建者出具」,不摆出具按钮', text.includes('请搭建者出具') + && await page.locator('[data-ledger-issue-button]').count() === 0, text) + check('能对账:照样摆对账按钮', await page.locator('[data-ledger-turn-reconcile]').count() === 1) + const issued = page.locator('[data-ledger-issued="run-iss-u"]') + const issuedText = (await issued.innerText().catch(() => '')).replace(/\s+/g, ' ') + check('自动出具过的正式运行:写「按口径自动出具」、哪份口径和档位', issuedText.includes('按口径自动出具') + && issuedText.includes('「订单口径」v1(已发布)') && issuedText.includes('降档出具'), issuedText) + check('……使用者不给打开运行的链接,写由搭建者查看', await issued.locator('a').count() === 0 && issuedText.includes('由搭建者在记录页查看'), issuedText) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +// ---------------------------------------------------------------- 设置 + +await section('设置里的口径账本一组:共用保存条,整组写 ledger,值不合规不让存', async () => { + const state = { puts: [], ledger: { auto_issue: true, issue_daily_limit: 20, match_timeout_s: 8, recall_limit: 50 } } + const reply = (method, p, body) => { + if (method === 'GET' && p === '/settings') return { json: { run: {}, limits: { max_agent_steps: 100 }, apps: {}, ledger: state.ledger } } + if (method === 'PUT' && p === '/settings') { + state.puts.push(body) + if (body?.values?.ledger) state.ledger = body.values.ledger + return { json: { ledger: state.ledger } } + } + return null + } + const { page, errors } = await open('/settings/prefs', { reply }) + const sec = page.locator('[data-ledger-settings]') + await sec.waitFor({ timeout: 8000 }) + const text = await sec.innerText() + check('四项都在:自动出具、每日上限、比对时限、升版后重算几组', ['自动按口径正式出具', '按口径正式出具每日上限', '口径比对时限(秒)', + '口径升版后每次最多重算几组'].every((t) => text.includes(t)), text) + check('显示的是服务端生效的值', await page.locator('[data-ledger-setting="issue_daily_limit"]').inputValue() === '20' + && await page.locator('[data-ledger-setting="recall_limit"]').inputValue() === '50' + && await page.locator('[data-ledger-setting="auto_issue"]').isChecked()) + await page.locator('[data-ledger-setting="recall_limit"]').fill('5000') + const bar = page.locator('[data-prefs-bar]') + check('不合规的值:写明范围,保存键不能点', (await sec.innerText()).includes('请填写 0 到 1,000 之间的整数') + && await bar.getByRole('button', { name: '保存设置' }).isDisabled()) + await page.locator('[data-ledger-setting="recall_limit"]').fill('30') + await page.locator('[data-ledger-setting="auto_issue"]').uncheck() + check('保存条写改了哪几项(服务端的叫法)', (await bar.innerText()).includes('有 2 项未保存') + && (await bar.innerText()).includes('自动按口径正式出具') && (await bar.innerText()).includes('口径升版后每次最多重算几组')) + await bar.getByRole('button', { name: '保存设置' }).click() + await until(() => state.puts.length === 1) + check('整组写 ledger(没改的项照原值带上,不会被冲回默认)', JSON.stringify(state.puts[0]?.values) === JSON.stringify({ + ledger: { auto_issue: false, issue_daily_limit: 20, match_timeout_s: 8, recall_limit: 30 } }), JSON.stringify(state.puts[0])) + check('存完:保存条写「已保存」', await until(async () => (await bar.innerText().catch(() => '')).includes('已保存'), 3000)) + check('没有运行时报错', errors.length === 0, errors.join(' | ')) +}) + +check('认不出的写请求一个都没有(都在浏览器层拦下)', stray.length === 0, stray.join(' | ')) +await browser.close() +console.log(failed ? `\n✗ ${failed} 项未通过` : '\n✓ 口径账本全部通过') +process.exit(failed ? 1 : 0) diff --git a/scripts/ledger-fixtures.mjs b/scripts/ledger-fixtures.mjs new file mode 100644 index 00000000..246efcaa --- /dev/null +++ b/scripts/ledger-fixtures.mjs @@ -0,0 +1,114 @@ +// 口径账本的检查夹具(check-ledger、check-evidence、check-chat 共用):GET /api/runs/{id}/ledger 的答复形状照服务端 +// app/ledger/view.py 的 run_view(labels.view_label、issue.Plan.action、reconcile.actions_of / reconciled_view), +// 挂在可点击证据的夹具(frontend/src/run/__tests__/evidence-doc.json,compose_doc 真跑出来的周报,只用通用名)上: +// s6「45,678.5元」来自受管口径「周报口径」v2,等价已证明;s10「1,234单」来自已发布口径「订单口径」v1,助手选用; +// s8「8.7%」相关口径「订单口径」v1(差在哪:少了一个筛选条件),可以对账;s12「37.0元」这次的推理; +// s23「2.35%」没有比对(比对超时)。 +// 口径名、表名、数都是虚构的通用名。 + +/** 口径的几份(calibers) */ +export const WEEKLY = { caliber: 'wf-weekly@2', workflow_id: 'wf-weekly', version: 2, level: 'governed', level_text: '受管', + workflow_name: '周报口径', graph_hash: 'aa11' } +export const ORDERS = { caliber: 'wf-orders@1', workflow_id: 'wf-orders', version: 1, level: 'published', level_text: '已发布', + workflow_name: '订单口径', graph_hash: 'bb22' } + +const caliberLabel = (c, how, extra = {}) => ({ + kind: 'caliber', how, caliber: c.caliber, workflow_id: c.workflow_id, version: c.version, level: c.level, + level_text: c.level_text, workflow_name: c.workflow_name, ...extra, +}) + +export const DIFF = { items: [{ aspect: 'filter', a: null, b: "status = '[已遮罩]'", text: '口径只保留状态为已支付的行,这次没有这个条件' }], + fallback: false, text_diff: [] } + +/** 一份比对过的账本。whole:整题判断(缺省不等价);actions、issued、reconciled 可以换 */ +export function ledgerOf(runId, { whole, actions, issued = [], reconciled = [], retro = false, labels } = {}) { + return { + run_id: runId, state: 'matched', note: '封存后比对,不在封存范围内', post_seal: true, artifact: 'cm-1', algo: 'v1', + trigger: retro ? 'on_demand' : 'sealed', retro, matched_at: '2026-10-15T01:00:00+00:00', + ...(retro ? { retro_note: '按现在的口径回看' } : {}), + calibers: [WEEKLY, ORDERS], + queries: [ + { artifact: 'q-gmv', node_id: 'ag', source: 'shop', tables: ['orders'], status: 'proven', + candidates: [{ ...WEEKLY, node_id: 'fetch', status: 'proven', how: 'independent' }] }, + { artifact: 'q-orders', node_id: 'ag', source: 'shop', tables: ['orders'], status: 'related', + candidates: [{ ...ORDERS, node_id: 'fetch', status: 'related', comparable: true, via: 'heuristic', diff: DIFF, + binding: [{ field: 'start', value: '2026-09-01' }] }] }, + ], + reports: { write: { labels: labels ?? { + s6: caliberLabel(WEEKLY, 'independent', { binding: [{ field: 'week', value: '2026-W37' }], card: 'caliber', metric: 'gmv', + queries: ['q-gmv'] }), + s10: caliberLabel(ORDERS, 'composed', { binding: [{ field: 'store', masked: true, value: '已遮罩' }], card: 'caliber', + metric: 'orders', queries: ['q-gmv'] }), + s8: { kind: 'related', related: [{ caliber: ORDERS.caliber, workflow_id: ORDERS.workflow_id, version: 1, level: 'published', + level_text: '已发布', workflow_name: '订单口径', node_id: 'fetch' }], queries: ['q-orders'] }, + s12: { kind: 'reasoning', query: 'q-gmv' }, + s23: { kind: 'unknown', reason: '比对超过时限,没有做完', query: 'q-gmv' }, + } } }, + primary: 'write', + whole: whole ?? { equivalent: false, reason: '有的数是这次的推理', counts: { caliber: 2, related: 1, reasoning: 1, unknown: 1 } }, + actions: actions ?? [RECONCILE], + issued, reconciled, + } +} + +/** 看差多少(s8 那条查询、订单口径):参数是推断的,要先核对 */ +export const RECONCILE = { + kind: 'reconcile', query: 'q-orders', caliber: ORDERS.caliber, workflow_id: ORDERS.workflow_id, version: 1, node_id: 'fetch', + workflow_name: '订单口径', level_text: '已发布', needs_check: true, check_reason: '参数按这次的 SQL 推断,请核对', + binding: [{ field: 'start', value: '2026-09-01' }], fallback: false, + fields: [{ name: 'start', required: true, has_default: false }, { name: 'store', required: false, has_default: true }], +} + +/** 按口径正式出具(整题等价于周报口径):搭建者能一键,不自动的原因写在 auto_reason */ +export const ISSUE = { + kind: 'issue', workflow_id: WEEKLY.workflow_id, version: 2, caliber: WEEKLY.caliber, workflow_name: '周报口径', how: 'independent', + level: 'governed', level_text: '受管', available: true, auto: false, auto_reason: '设置里关了自动按口径出具', +} + +/** 整题等价时的标签(三个数都来自周报口径) */ +export const WHOLE_LABELS = { + s6: caliberLabel(WEEKLY, 'independent', { binding: [{ field: 'week', value: '2026-W37' }], queries: ['q-gmv'] }), + s10: caliberLabel(WEEKLY, 'independent', { binding: [{ field: 'week', value: '2026-W37' }], queries: ['q-gmv'] }), + s12: caliberLabel(WEEKLY, 'independent', { binding: [{ field: 'week', value: '2026-W37' }], queries: ['q-gmv'] }), +} +export const WHOLE = { equivalent: true, caliber: WEEKLY.caliber, workflow_id: WEEKLY.workflow_id, version: 2, level: 'governed', + level_text: '受管', workflow_name: '周报口径', how: 'independent', binding: [{ field: 'week', value: '2026-W37' }], + missing: [], missing_required: [], counts: { caliber: 3, related: 0, reasoning: 0, unknown: 0 } } + +/** 对过的一次账(单行:一组对照)。status 可以换 */ +export const reconciledOf = (status = 'succeeded') => ({ + run_id: 'run-rec-1', status, query: 'q-orders', caliber: ORDERS.caliber, workflow_id: ORDERS.workflow_id, version: 1, + inputs_from: 'checked', rows: null, card: 'reconcile', + groups: [{ label: '订单数', ours: 'ours_0', caliber: 'cal_0', diff: 'diff_0', rel: 'rel_0' }], created_at: '2026-10-15T02:00:00Z', +}) + +/** 对账卡上四个指标的展示值(/evidence/metrics/reconcile/{id} 的 rendered) */ +export const RECONCILE_VALUES = { ours_0: '1,234单', cal_0: '1,180单', diff_0: '54单', rel_0: '4.58%' } + +/** 对账运行的指标出处(形状同片段接口:chain、seal),给 EvidenceDrawer 画 */ +export const metricDetail = (runId, metric) => ({ + run_id: runId, node: 'reconcile', metric, rendered: RECONCILE_VALUES[metric] ?? '—', eid: `ev:metric:${metric}`, + chain: [{ step: 'metric', alias: 'm', metric, name: metric, value: 1, rendered: RECONCILE_VALUES[metric], node_id: 'reconcile', + caliber: '口径对账', version: 'v1', expression: 'cell(nodes.ours_q1, 0, \'orders\')', sealed: true, inputs: [] }], + seal: { sealed: true, ok: true, covered: true }, redacted: { columns: [] }, +}) + +/** 认证队列:三类来源各一项 */ +export const QUEUE = { + items: [ + { id: 'shape:aa11', kind: 'shape', source: 'shop', shape: 'SELECT SUM(amount) FROM orders WHERE paid_at >= ? AND status = ?', + runs: 4, conversations: 3, question: '上周销售额是多少', + turns: [{ run_id: 'run-s1', conversation_id: 'c-1', turn_id: 't-1', question: '上周销售额是多少' }, + { run_id: 'run-s2', conversation_id: 'c-2', turn_id: 't-2', question: '这周销售额是多少' }], + params: [{ index: 0, distinct: 3 }], constants: 1, related: [{ caliber: ORDERS.caliber, workflow_id: ORDERS.workflow_id, version: 1, level: 'published' }], + representative: { run_id: 'run-s1', query: 'q-1' }, peers: ['run-s2', 'run-s3'], frozen_into: [] }, + { id: 'cluster:bb22', kind: 'cluster', question: '各门店的退款率', count: 3, + turns: [{ run_id: 'run-c1', turn_id: 't-c1', question: '各门店的退款率' }, { run_id: 'run-c2', turn_id: 't-c2', question: '门店退款率怎么样' }], + frozen_into: [] }, + { id: 'reused:cc33', kind: 'reused', question: '本月新客数', uses: { exports: 2, app: false, extracted: false, canvas: true }, + turns: [{ run_id: 'run-r1', conversation_id: 'c-3', turn_id: 't-r1', question: '本月新客数' }], + representative: { run_id: 'run-r1' }, frozen_into: [{ workflow_id: 'wf-new-old', name: '本月新客数(固化的口径草稿)', status: 'draft' }] }, + ], + considered: { runs: 120, matched: 100, questions: 90 }, + threshold: { runs: 3, conversations: 2, exports: 2 }, +} From 9886e10be2f05618a6b0ddca49ccd91b17bea36f Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 22:13:52 +0800 Subject: [PATCH 6/8] =?UTF-8?q?=E8=B4=A6=E6=9C=AC=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=EF=BC=9A=E5=88=9A=E8=B7=91=E5=AE=8C=E6=9C=AA=E5=B0=81=E5=AD=98?= =?UTF-8?q?=E7=AD=94=20pending=20=E5=8F=AA=E9=99=90=E7=BB=93=E6=9D=9F?= =?UTF-8?q?=E5=90=8E=E4=B8=A4=E5=88=86=E9=92=9F=E5=86=85=EF=BC=8C=E6=97=A9?= =?UTF-8?q?=E5=B0=B1=E7=BB=93=E6=9D=9F=E3=80=81=E4=B8=80=E7=9B=B4=E6=B2=A1?= =?UTF-8?q?=E5=B0=81=E5=AD=98=E7=9A=84=E7=85=A7=E5=AE=9E=E7=AD=94=E3=80=8C?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E8=BF=98=E6=B2=A1=E6=9C=89=E5=B0=81=E5=AD=98?= =?UTF-8?q?=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复核 W4R-08:上一次给 GET /api/runs/{id}/ledger 加的 pending 分支没有时间界限——成功结束、要比对、没封存的运行一律答 pending。它本来只为 runner 落库 run.finished 之后、封存之前的那一下(页面收到 run.finished 立刻来取)。封存出了错、或者是 封存这件事之前的老数据,会永远答 pending:每个轮次底部、证据面板都转两分钟「正在比对口径」,再取一次还是 pending;改之前 答的 ineligible「运行还没有封存,不比对」才是实情。 - ledger/view.py:新增 SEAL_GRACE_S = 120(和页面等比对结论的上限 store/ledger.ts 的两分钟同一个量级),_just_finished 看 finished_at 在不在这段时间里(没记结束时间的不算;库里读回 naive 的按 UTC 算,同 db/base.UTCDateTime)。只有刚结束的才答 pending,其余照旧走 ineligible(NOT_SEALED);_stamp 里的局部 datetime 导入挪到模块顶上 - 测试:刚跑完的那条补上 finished_at=现在;新增一条结束已久、一直没封存的和一条没记结束时间的,都答 ineligible、原因是 没封存、不排按需比对。去掉 _just_finished 回跑,新测试失败(答的是 pending) --- backend/app/ledger/view.py | 20 +++++++++++++++---- backend/tests/test_ledger_api.py | 33 ++++++++++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/backend/app/ledger/view.py b/backend/app/ledger/view.py index 81492c2b..5ce136a6 100644 --- a/backend/app/ledger/view.py +++ b/backend/app/ledger/view.py @@ -10,6 +10,7 @@ issued 是这次运行按口径出具过的正式运行,reconciled 是对过 """ from __future__ import annotations +from datetime import datetime, timezone from typing import Any from sqlalchemy import select @@ -23,6 +24,10 @@ from app.ledger import store #: state:matched 比对过;pending 已排队按需比对;ineligible 这次运行不比对(reason 写为什么);unreadable 比对记录读不出 STATES = ("matched", "pending", "ineligible", "unreadable") +#: 成功结束、还没封存的运行,结束后这么多秒内答 pending(runner 落库之后马上封存,正常是几秒)。过了还没封存的是封存出了错、 +#: 或者是封存之前的老数据:再答 pending,页面就一直转圈、等满两分钟(store/ledger.ts 的等待上限)再取还是 pending——照实说没封存 +SEAL_GRACE_S = 120 + class _Hide: """按这次运行查到过的遮罩值遮:hide(值) 这个值给不给,shown(文字) 文字里的遮罩值换成「已遮罩」。""" @@ -92,8 +97,6 @@ def _labels_view(content: dict[str, Any], hider: _Hide, names: dict[str, str]) - def _stamp(recorded: store.Recorded) -> dict[str, Any]: """比对的来历:哪份工件、哪一版算法、谁触发的、什么时候追加的;事后补比的写明按现在的口径回看。""" - from datetime import datetime, timezone - at = datetime.fromtimestamp(recorded.ts, timezone.utc).isoformat(timespec="seconds") \ if isinstance(recorded.ts, (int, float)) else None return {"artifact": recorded.artifact, "algo": recorded.algo, "trigger": recorded.trigger, "retro": recorded.retro, @@ -102,6 +105,14 @@ def _stamp(recorded: store.Recorded) -> dict[str, Any]: else ledger_labels.RETRO_NOTE} if recorded.retro else {})} +def _just_finished(finished_at: datetime | None) -> bool: + """运行是不是刚结束(SEAL_GRACE_S 以内)。没记结束时间的不算;库里读回 naive 的按 UTC 算(同 db/base.UTCDateTime)。""" + if finished_at is None: + return False + at = finished_at if finished_at.tzinfo is not None else finished_at.replace(tzinfo=timezone.utc) + return (datetime.now(timezone.utc) - at).total_seconds() <= SEAL_GRACE_S + + async def run_view(run_id: str) -> dict[str, Any]: """GET /api/runs/{run_id}/ledger 的答复:标签、整题判断、每条查询的比对、能做的动作。没比对过、能比的运行这时排上按需比对 (trigger=on_demand),答复 state=pending;不比的照实说为什么。""" @@ -117,9 +128,10 @@ async def run_view(run_id: str) -> dict[str, Any]: if recorded is None: why = ledger_match.ineligible(run) if why == ledger_match.NOT_SEALED and run.status == "succeeded" \ - and ledger_match.wanted(run.run_class, run.origin_kind): + and ledger_match.wanted(run.run_class, run.origin_kind) and _just_finished(run.finished_at): # runner 先发 run.finished、落库,再封存、再排上比对(engine/runner._finalize):页面收到 run.finished 立刻来取, - # 这一下还没封存。这不是「不比对」,是封存完就比——照实答 pending,页面按退避接着取;这里不另排按需比对 + # 这一下还没封存。这不是「不比对」,是封存完就比——照实答 pending,页面按退避接着取;这里不另排按需比对。 + # 只限刚结束的那一会儿(SEAL_GRACE_S),早就结束、一直没封存的照实答 ineligible return {**base, "state": "pending"} sealed = await _sealed(run_id) if why is None else None if sealed is not None and not sealed.queries: diff --git a/backend/tests/test_ledger_api.py b/backend/tests/test_ledger_api.py index e70a6561..fceeb799 100644 --- a/backend/tests/test_ledger_api.py +++ b/backend/tests/test_ledger_api.py @@ -102,11 +102,14 @@ async def test_a_run_that_just_finished_and_is_about_to_be_sealed_is_pending(cli await ledger_match.drain() from app.db.models import Run + from datetime import datetime, timedelta, timezone + + now = datetime.now(timezone.utc) async with SessionLocal() as session: fresh = Run(workflow_name="刚跑完", status="succeeded", run_class="exploratory", origin_kind="chat", graph={}, - input={}, output={}) + input={}, output={}, finished_at=now) failed = Run(workflow_name="失败了", status="failed", run_class="exploratory", origin_kind="chat", graph={}, - input={}, output={}) + input={}, output={}, finished_at=now) session.add_all([fresh, failed]) await session.commit() fresh_id, failed_id = fresh.id, failed.id @@ -117,6 +120,32 @@ async def test_a_run_that_just_finished_and_is_about_to_be_sealed_is_pending(cli assert (await ledger_of(client, failed_id))["state"] == "ineligible" +async def test_a_run_that_finished_long_ago_and_was_never_sealed_says_so(client, monkeypatch): + """「刚跑完、马上封存」只是结束后的那一会儿:成功结束了好一阵、一直没封存的(封存时出了错、封存这件事之前的老数据), + 再答 pending 就是让页面一直转圈、等两分钟、点「再取一次」还是 pending。照实说没封存(ineligible,NOT_SEALED); + 结束时间没记的同样不当成刚结束。""" + from datetime import datetime, timedelta, timezone + + from app.db.models import Run + from app.ledger import view as ledger_view + + old = datetime.now(timezone.utc) - timedelta(seconds=ledger_view.SEAL_GRACE_S + 60) + async with SessionLocal() as session: + stale = Run(workflow_name="很早以前跑完", status="succeeded", run_class="exploratory", origin_kind="chat", + graph={}, input={}, output={}, finished_at=old) + undated = Run(workflow_name="没记结束时间", status="succeeded", run_class="exploratory", origin_kind="chat", + graph={}, input={}, output={}) + session.add_all([stale, undated]) + await session.commit() + stale_id, undated_id = stale.id, undated.id + scheduled: list[str] = [] + monkeypatch.setattr(ledger_match, "schedule", lambda run_id, **kw: scheduled.append(run_id) or True) + for run_id in (stale_id, undated_id): + body = await ledger_of(client, run_id) + assert body["state"] == "ineligible" and body["reason"] == ledger_match.NOT_SEALED, body + assert scheduled == [] + + async def test_runs_that_are_not_compared_say_why(client, monkeypatch): row = await S.explore(monkeypatch, S.EQUIVALENT, origin="api", text="本周销售额 [[v:Q1.r0.销售额]]。") body = await ledger_of(client, row.id) From f72e1d4a653475b5a921b75e26d22369263f3beb Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 22:18:44 +0800 Subject: [PATCH 7/8] =?UTF-8?q?=E9=97=AE=E6=95=B0=E6=8D=AE=E3=80=81?= =?UTF-8?q?=E7=94=BB=E5=B8=83=E5=8F=B3=E6=A0=8F=E3=80=81=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E8=AF=A6=E6=83=85=E7=9A=84=E6=AD=A5=E9=AA=A4=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E7=BA=BF=EF=BC=9A=E8=A2=AB=E9=A9=B3=E5=9B=9E=E7=9A=84=E9=82=A3?= =?UTF-8?q?=E4=B8=80=E6=AD=A5=E7=94=BB=E5=81=9C=E6=AD=A2=E7=9A=84=E5=89=AA?= =?UTF-8?q?=E5=BD=B1=E3=80=81=E8=A1=8C=E5=B0=BE=E5=86=99=E3=80=8C=E8=A2=AB?= =?UTF-8?q?=E9=A9=B3=E5=9B=9E=E3=80=8D=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=98=AF?= =?UTF-8?q?=E7=BB=BF=E8=89=B2=E7=9A=84=E5=AE=8C=E6=88=90=E5=8B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复核 W4R-02:decode 已经给被驳回的那一步(node.failed 带 reason=rejected)记 status=rejected,但三处共用的步骤时间线 run/AssistantStream 不认它:BADGED 里没有 rejected,徽标落到「顶层节点画完成」那一支,被驳回的那一步成了一个绿勾;字色是 正文色,行尾 STOPPED 也没有这一项——副标题写着「张工 驳回:金额不对」,图标却说做完了。细案 5.3 要的是驳回之后各处都写 「被驳回」。 - BADGED 加 rejected:画 lib/status 里 rejected 那一套(停止的剪影、取消的中性色,和画布节点卡同一个) - 这一行用次一级的中性字色(比取消、跳过的淡色重一档:运行就停在这一步),副标题(谁驳回、备注)用正体、不再是淡色斜体 - 行尾:STOPPED 加 rejected。被驳回的那一步带着耗时(node.failed 的 duration_ms),只写耗时的话停止的方块和取消分不开, 写成「被驳回 · 900 ms」 - 长列表折起来时照样露出被驳回的那一行(notable 认 rejected):运行停在这一步,不能收进「展开前面的 N 条」 - check-chat「被驳回」一段:run-rej2 的事件换成「查数」那一步 node.failed 带 reason=rejected,点开执行过程核对这一行的 状态、剪影(stop,不是 square)、图标不是完成的绿色、副标题和行尾写「被驳回」、不写「失败」。改之前这三项不过(徽标是 done、颜色是 --st-done 的绿),改之后深浅两套都过 --- frontend/src/run/AssistantStream.tsx | 26 ++++++++++++++++---- scripts/check-chat.mjs | 36 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/frontend/src/run/AssistantStream.tsx b/frontend/src/run/AssistantStream.tsx index 05c32be0..79899ade 100644 --- a/frontend/src/run/AssistantStream.tsx +++ b/frontend/src/run/AssistantStream.tsx @@ -1007,8 +1007,9 @@ const LIST_HEAD = 20 /** 点名的那一行等展开之后再找,最多等这么多帧 */ const REVEAL_TRIES = 4 +/** 长列表折起来时照样露出来的行:出了问题的、还在进行的、被驳回的(运行停在这一步,不能收进「前面的 N 条」) */ const notable = (s: Step): boolean => - s.status === 'failed' || s.status === 'running' || s.status === 'waiting' + s.status === 'failed' || s.status === 'running' || s.status === 'waiting' || s.status === 'rejected' || s.level === 'error' || s.level === 'warn' function StepList({ steps, depth, turnMs, fold = false }: { @@ -1050,8 +1051,11 @@ function StepList({ steps, depth, turnMs, fold = false }: { ) } -/** 状态有自己剪影的就画剪影(全站同一套),其余的画这一步是什么 */ -const BADGED = new Set(['running', 'waiting', 'failed', 'cancelled', 'suspended', 'skipped']) +/** + * 状态有自己剪影的就画剪影(全站同一套),其余的画这一步是什么。rejected(这一步被人驳回,node.failed 带 reason=rejected) + * 画停止的剪影:不进来的话它落到下面「顶层节点画完成」那一支,被驳回的那一步成了一个绿勾 + */ +const BADGED = new Set(['running', 'waiting', 'failed', 'cancelled', 'suspended', 'skipped', 'rejected']) function StepRow({ step, depth, turnMs }: { step: Step; depth: number; turnMs?: number }) { if (depth === 0 && step.kind === 'lifecycle' && step.stage !== 'plan') return @@ -1094,10 +1098,13 @@ function StepLine({ step, depth, turnMs }: { step: Step; depth: number; turnMs?: // 失败要压过 kind:一条 lifecycle 跑挂了还画成打勾的"完成"图标,是把失败说成了成功 const failed = status === 'failed' || step.level === 'error' const running = status === 'running' + // 被驳回是人的决定,不是故障:不画红、不画完成的绿,用中性的次一级字色(比取消、跳过的淡色重一档——运行就停在这一步) + const rejected = status === 'rejected' const top = depth === 0 && (step.kind === 'node' || step.kind === 'lifecycle') const color = failed ? 'var(--st-failed)' : status === 'waiting' ? 'var(--st-waiting)' : step.level === 'warn' ? 'var(--st-waiting)' + : rejected ? 'var(--text-dim)' : status === 'skipped' || status === 'cancelled' ? 'var(--text-faint)' : status === 'suspended' ? 'var(--st-suspended, var(--warn))' : running ? 'var(--st-running)' @@ -1160,8 +1167,9 @@ function StepLine({ step, depth, turnMs }: { step: Step; depth: number; turnMs?: // 副标题平时是淡色斜体的旁白(这次调用前在想什么、为什么跳过);出了事的行 // 它说的是为什么,用正体、跟着行的颜色,别让最要紧的那句成了最淡的字 {sub} @@ -1238,6 +1246,13 @@ function StepMeta({ step, depth, turnMs }: { step: Step; depth: number; turnMs?: {/* 「开始运行」那一行的秒表和轮次头部的是同一个数,不重复 */} {running && step.startedAt != null && step.kind !== 'lifecycle' ? + : step.status === 'rejected' + // 被驳回的那一步带着耗时(node.failed 的 duration_ms):只写耗时的话停止的方块和取消分不开,状态和耗时都写 + ? ( + + {STOPPED.rejected}{step.meta && · {step.meta}} + + ) : (step.meta || STOPPED[step.status ?? '']) && !(running && step.startedAt != null) && ( @@ -1253,6 +1268,7 @@ function StepMeta({ step, depth, turnMs }: { step: Step; depth: number; turnMs?: const STOPPED: Record = { cancelled: statusLabel('cancelled', { short: true }), suspended: statusLabel('suspended', { short: true }), + rejected: statusLabel('rejected', { short: true }), } /** diff --git a/scripts/check-chat.mjs b/scripts/check-chat.mjs index 28a140d1..688e66df 100644 --- a/scripts/check-chat.mjs +++ b/scripts/check-chat.mjs @@ -33,6 +33,7 @@ // 17. 口径账本(next-round 02):交付了的轮次底部写「正在比对口径」,按退避再取到比对出结果、比完不再取;一行摘要 // (几个数来自哪份口径)、按口径正式出具和对账按钮照服务端给的动作摆;出具、对账的写请求在浏览器层拦下并核对请求体, // 出具过的正式运行挂在轮次下面(档位、打开运行)。 +// 18. 过程里被驳回的那一步(node.failed 带 reason=rejected):停止的剪影、中性色、行尾写「被驳回」,不画成完成的绿勾。 // // 所有写请求都被拦在浏览器里,不碰任何库。 // 跑之前前端得起着(./scripts/dev.sh),默认连 5273。对别的实例(比如一份沙箱拷贝)跑时 @@ -676,6 +677,14 @@ async function fakeApi(route) { return json(ctl.approvals.filter((a) => !runId || a.run_id === runId)) } m = path.match(/^\/runs\/([^/]+)\/events$/) + if (m && method === 'GET' && m[1] === 'run-rej2') { + // 被驳回的那一轮:「查数」里的动作确认被驳回,那一步的 node.failed 带 reason=rejected(服务端 compiler 的写法) + return json([ev(1, 'run.started', null, { nodes: 3 }), ev(2, 'node.started', 'ag', { node_type: 'agent', label: '查数' }), + ev(3, 'node.failed', 'ag', { duration_ms: 900, error: '人工驳回:数字对不上', reason: 'rejected', kind: 'action', + decision: 'reject', actor: '张工', note: '数字对不上' }), + ev(4, 'run.cancelled', null, { reason: 'rejected', node_id: 'ag', label: '查数', kind: 'action', decision: 'reject', + actor: '张工', note: '数字对不上' })]) + } if (m && method === 'GET') { return json([ev(1, 'run.started', null, { nodes: 3 }), ev(2, 'node.started', 'ag', {}), ev(3, 'node.finished', 'ag', { duration_ms: 700 }), ev(4, 'run.finished', null, { output: {} })]) @@ -1496,6 +1505,33 @@ for (const theme of THEMES) { check('补救区说是审批人驳回、谁在哪一步驳回,不说「你已停止本轮」', cardText.includes('被审批人驳回') && cardText.includes('张工 驳回了「查数」:数字对不上') && !cardText.includes('你已停止本轮'), cardText) check('被驳回的没有「继续运行」', !(await card.getByRole('button', { name: '继续运行' }).count())) + // 过程里被驳回的那一步(node.failed 带 reason=rejected):停止的剪影、中性色、行尾写「被驳回」, + // 不是绿色的「完成」勾,也不是失败的红三角(总方案 X9、细案 5.3「各处都写被驳回」) + await page.locator('[data-turn]').first().getByRole('button', { name: '查看执行过程' }).click() + const stepRow = page.locator('[data-turn]').first().locator('[data-node-id="ag"][data-step-status]').first() + await stepRow.waitFor({ timeout: 4000 }).catch(() => {}) + const look = await stepRow.evaluate((el) => { + const badge = el.querySelector('svg[data-status]') + const line = el.querySelector('button') + return { status: el.dataset.stepStatus, badge: badge?.getAttribute('data-status') ?? null, + shape: badge?.getAttribute('data-shape') ?? null, badgeColor: badge ? getComputedStyle(badge).color : null, + done: getComputedStyle(document.documentElement).getPropertyValue('--st-done').trim(), + lineColor: line ? getComputedStyle(line).color : null, text: el.innerText.replace(/\n/g, ' / ') } + }).catch((e) => ({ error: String(e) })) + check('过程里被驳回的那一步:状态 rejected,剪影是停止、不是完成的勾', look.status === 'rejected' + && look.badge === 'rejected' && look.shape === 'stop', JSON.stringify(look)) + const doneRgb = await page.evaluate(() => { + const probe = document.createElement('span') + probe.style.color = 'var(--st-done)' + document.body.appendChild(probe) + const c = getComputedStyle(probe).color + probe.remove() + return c + }) + check('……图标不是绿色(完成的颜色)', !!look.badgeColor && look.badgeColor !== doneRgb, `${look.badgeColor} vs ${doneRgb}`) + check('……副标题写谁驳回、备注,行尾写「被驳回」,不写「失败」', (look.text ?? '').includes('张工 驳回:数字对不上') + && (look.text ?? '').includes('被驳回') && !(look.text ?? '').includes('失败'), look.text) + if (theme === 'dark') await page.screenshot({ path: `${SHOTS}/rejected-step-${theme}.png` }) const aside = page.locator('aside[aria-label="对话列表"]') const rowText = async (t) => (await aside.locator('div.group', { hasText: t }).innerText().catch(() => '')).replace(/\n/g, ' / ') // 标题里不带「被驳回」:标出来的是状态,不是标题里的字 From 1195c4abcbebb4d5f60b1ea045a00845cf056329 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 22:21:11 +0800 Subject: [PATCH 8/8] =?UTF-8?q?=E8=B4=A6=E6=9C=AC=E5=89=8D=E7=AB=AF?= =?UTF-8?q?=E8=A1=A5=E4=B8=A4=E6=A0=B7=EF=BC=9A=E7=AD=94=E6=A1=88=E8=BA=AB?= =?UTF-8?q?=E4=B8=8A=E7=9A=84=E5=8F=AC=E5=9B=9E=E6=A0=87=E8=AE=B0=E5=86=99?= =?UTF-8?q?=E5=88=B0=E9=97=AE=E6=95=B0=E6=8D=AE=E7=9A=84=E8=BD=AE=E6=AC=A1?= =?UTF-8?q?=E5=92=8C=E8=AF=81=E6=8D=AE=E9=9D=A2=E6=9D=BF=E3=80=8C=E5=8F=A3?= =?UTF-8?q?=E5=BE=84=E3=80=8D=E4=B8=80=E6=AD=A5=EF=BC=9B=E5=AF=B9=E8=B4=A6?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E5=8D=A1=E4=B8=8A=E9=97=AE=E3=80=8C=E8=AF=B4?= =?UTF-8?q?=E6=98=8E=E6=9C=89=E7=94=A8=20/=20=E7=9C=8B=E4=B8=8D=E6=87=82?= =?UTF-8?q?=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复核 W4R-03(a×c):召回在原答案的运行上追加 ledger.recalled、ledger.basis_changed,以前只在运行时间线(decode)里,问数据的 轮次底部、证据面板「口径」一步、账本接口都不带——使用者被标了「依据有变」、或者口径升版后「已按 v2 核对,不影响」,重开对话 什么也看不到,得点开「过程」才翻得出来,而使用者进不了记录页。W4-a 已在账本接口加上 recall(ledger/recall.answer_marks: checked / basis / tasks,几种 state 都带),这边照它画: - typesLedger:RunLedger.recall(LedgerRecallMarks) - run/LedgerStep 新增 RecallMarks(问数据的轮次和「口径」一步共用):「已按口径「X」vN 核对,不影响」(同一份口径核对过 几次只写最近那一版,数变了的不在这里写);依据有变按两类各一行——数据目录(catalog / values / catalog_edit)和表结构 (structure),认不出的种类只说「答案的依据有变」不猜,项数相加,按新目录新出现错误级问题的写几条;看的人手上有说的是 这个答案的召回待办时写一句(口径升到 vN、数变了 / 依据有变检查出新问题)并链到 /apps/inbox/{待办} - LedgerTurn:比对过的卡里写在摘要下面;没比对、不比对的答案(state 不是 matched)只要带着标记就单独写一张小卡 - LedgerPart(证据面板「口径」一步):有标签的写在脚注前;没标签但答案带着标记的,这一步只写标记 复核 W4R-10(多包):细案 02 做法 10 的 E2「说明有用 / 看不懂」以前没有入口。W4-a 已加 POST /ledger/answers/{run}/reconcile/ {对账运行}/feedback({verdict: useful | unclear},记成对账运行上的封存后事件、统计 E2 数它),账本接口的 reconciled 每一项 带 feedback {mine, useful, unclear}。这边: - api.caliberLedger.feedback;typesLedger 加 LedgerFeedback、LedgerFeedbackOut - run/LedgerReconcile 的对账卡:做完的卡问一句「「差在哪」的说明有帮助吗?」,两个按钮,看的人选过的按下(aria-pressed), 写各几个人(服务端给的数),可以改主意;交回来的反馈先画上,账本再取一次让别处挂着的同一张卡跟着变;回收站里只看不反馈; 没做完的卡不问 - 问数据的轮次里卡片上方没有「差在哪」,卡里补写一份(showWhere),反馈问的就是它;证据面板里它本来就在卡片上方,不重复 检查(写请求都在浏览器层拦下): - check-evidence 新一段 ledger-recall:比对过的答案「口径」一步写核对过(只写最近那一版)、依据有变(项数相加、新问题条数)、 链到待办;不比对的答案这一步只写依据有变 - check-chat 新一段 recall:轮次底部同上,另核对做完的对账卡写「差在哪」和反馈人数;不比对的答案单独一张小卡写表结构有变 - check-ledger 对账一段:没做完不问;点「看不懂」请求体只有 verdict、按下、写各几个人;改点「说明有用」再记一条、按下的换过来 - 共用夹具 ledger-fixtures 加 RECALL 把这几个文件的改动拿掉回跑:check-chat recall 6 项、check-evidence ledger-recall 4 项、check-ledger 对账反馈 2 项都不过; 放回去全过 --- frontend/src/api/caliberLedger.ts | 7 ++- frontend/src/lib/termsLedger.ts | 28 ++++++++++ frontend/src/run/LedgerReconcile.tsx | 79 +++++++++++++++++++++++++--- frontend/src/run/LedgerStep.tsx | 71 +++++++++++++++++++++++-- frontend/src/run/LedgerTurn.tsx | 24 +++++++-- frontend/src/typesLedger.ts | 39 ++++++++++++++ scripts/check-chat.mjs | 59 ++++++++++++++++++++- scripts/check-evidence.mjs | 36 ++++++++++++- scripts/check-ledger.mjs | 31 ++++++++++- scripts/ledger-fixtures.mjs | 19 +++++++ 10 files changed, 370 insertions(+), 23 deletions(-) diff --git a/frontend/src/api/caliberLedger.ts b/frontend/src/api/caliberLedger.ts index 5e9b8cf6..aa78ac75 100644 --- a/frontend/src/api/caliberLedger.ts +++ b/frontend/src/api/caliberLedger.ts @@ -3,7 +3,8 @@ * * - run:GET /api/runs/{id}/ledger,一次运行里每个数的口径标签、整题判断、能做的动作、出具过的正式运行、对过的账; * - issue:按口径正式出具(参数只由服务端从比对工件里取,这里只能选「按哪份口径」); - * - reconcile:口径对账(点开才跑一次确定性派生的只读图); + * - reconcile:口径对账(点开才跑一次确定性派生的只读图);feedback:对账结果上的「说明有用 / 看不懂」(记成对账运行上的 + * 封存后事件,统计 E2 数它); * - certifyQueue / dismiss:可沉淀的问题、「不是口径」(搭建者及以上); * - freeze:固化成口径草稿(/copilot/from-run 的 freeze 选项,报告引用的查询变成固定 SQL 的取数节点)。 * @@ -11,7 +12,7 @@ * 请求函数从 ./http 导入,不从 ./client 导入(client.ts 要导入这个文件,反过来就成了循环)。 */ import type { - CertifyQueue, FreezeOut, LedgerIssueOut, LedgerReconcileIn, LedgerReconcileOut, RunLedger, + CertifyQueue, FreezeOut, LedgerFeedbackOut, LedgerFeedbackVerdict, LedgerIssueOut, LedgerReconcileIn, LedgerReconcileOut, RunLedger, } from '../typesLedger' import { get, post, type RequestOptions } from './http' @@ -21,6 +22,8 @@ export const caliberLedger = { run: (runId: string, opts?: RequestOptions) => get(`/runs/${encodeURIComponent(runId)}/ledger`, opts), issue: (runId: string, body: { workflow_id: string; version: number }) => post(`${at(runId)}/issue`, body), reconcile: (runId: string, body: LedgerReconcileIn) => post(`${at(runId)}/reconcile`, body), + feedback: (runId: string, reconcileId: string, verdict: LedgerFeedbackVerdict) => + post(`${at(runId)}/reconcile/${encodeURIComponent(reconcileId)}/feedback`, { verdict }), certifyQueue: (opts?: RequestOptions) => get('/ledger/certify-queue', opts), dismiss: (body: { item_id: string; kind?: string; note: string }) => post<{ ok: boolean; item_id: string }>('/ledger/certify-queue/dismiss', body), diff --git a/frontend/src/lib/termsLedger.ts b/frontend/src/lib/termsLedger.ts index 20543f3d..5be516de 100644 --- a/frontend/src/lib/termsLedger.ts +++ b/frontend/src/lib/termsLedger.ts @@ -113,6 +113,34 @@ export const LEDGER_UI = { less: '收起', original: (text: string) => `原答案里写的是 ${text};对账时按同样的 SQL 重新取数,数据有变化时两者可能不同`, openRun: '打开对账运行', + /** 「差在哪」的说明有没有帮人看懂(统计 E2 数它,衡量差异说明写得好不好) */ + feedback: { + ask: '「差在哪」的说明有帮助吗?', + useful: '说明有用', + unclear: '看不懂', + mine: (v: 'useful' | 'unclear') => `你选了「${v === 'useful' ? '说明有用' : '看不懂'}」,可以改`, + counts: (useful: number, unclear: number) => [useful ? `${formatNumber(useful)} 人觉得有用` : '', + unclear ? `${formatNumber(unclear)} 人看不懂` : ''].filter(Boolean).join(' · '), + saved: '已记下你的反馈', + readOnly: '对话在回收站中,恢复后才能反馈', + }, + }, + + // ---- 答案身上的召回标记(问数据的轮次、证据面板「口径」一步) ---- + recall: { + /** 口径升版后在同一份数据上重算过、数没变 */ + checked: (caliber: string) => `已按口径${caliber} 核对,不影响`, + /** 依据有变:目录里影响数字的项被驳回或修改、出现新码值、处理变化时改了目录(目录类),表或列被删、类型变了(表结构) */ + basis: (what: 'catalog' | 'structure' | 'other', items: number) => + `${what === 'structure' ? '依据的表结构有变' : what === 'catalog' ? '依据的数据目录有变' : '答案的依据有变'}` + + `${items ? `(${formatNumber(items)} 项)` : ''}`, + newErrors: (n: number) => `按新目录检查新出现 ${formatNumber(n)} 条错误级问题`, + basisHint: '答案本身没有改:它依据的数据目录或表结构在答案之后有变化,请核对是否还能用', + /** 看的这个人手上说的是这个答案的 recall 待办:口径升版后数变了的、依据有变检查出新问题的 */ + taskCaliber: (version: number | null | undefined) => `口径升到 ${version != null ? `v${version}` : '新版本'},这个答案用到的数变了`, + taskBasis: '依据有变,按新目录检查出了新的问题', + taskOther: '有一条召回待办', + task: '去待办处理', }, // ---- 问数据:轮次底部的摘要 ---- diff --git a/frontend/src/run/LedgerReconcile.tsx b/frontend/src/run/LedgerReconcile.tsx index a07905e6..aa8f0ab1 100644 --- a/frontend/src/run/LedgerReconcile.tsx +++ b/frontend/src/run/LedgerReconcile.tsx @@ -1,4 +1,5 @@ import { useEffect, useMemo, useState } from 'react' +import clsx from 'clsx' import { Link } from 'react-router-dom' import { Scale } from 'lucide-react' import { ApiError, api } from '../api/client' @@ -9,8 +10,8 @@ import { LEDGER_UI } from '../lib/termsLedger' import { useAtLeast } from '../store/auth' import { useLedger } from '../store/ledger' import type { - LedgerField, LedgerPairOptions, LedgerReconcileAction, LedgerReconcileIn, LedgerReconciled, LedgerReconcileGroup, - LedgerRelated, RunLedger, + LedgerFeedback, LedgerFeedbackVerdict, LedgerField, LedgerPairOptions, LedgerReconcileAction, LedgerReconcileIn, LedgerReconciled, + LedgerReconcileGroup, LedgerRelated, RunLedger, } from '../typesLedger' import { BindingList, DiffList, caliberOf } from './LedgerStep' @@ -26,6 +27,8 @@ import { BindingList, DiffList, caliberOf } from './LedgerStep' * - 结果(ReconcileResults):每一组对照写按你的问法、按口径、差值(另附相对差),每个数按 * /runs/{对账运行}/evidence/metrics/{对账卡}/{指标} 取值,点一下打开它的出处链(apps/EvidenceDrawer,和应用页点数同一套)。 * 哪几个指标是一组由服务端给(reconciled.groups),这里不按命名规则拼。 + * - 反馈(FeedbackRow):对账跑完之后问一句「差在哪」的说明有没有帮人看懂——「说明有用 / 看不懂」,记成对账运行上的封存后 + * 事件(服务端 ledger/feedback),统计 E2 数它。同一个人改主意只算最后一次;看的人选过哪个、各几个人都由服务端给。 */ const NEEDS_PAIRS = 'ledger_reconcile_needs_pairs' @@ -229,7 +232,55 @@ function GroupRow({ runId, card, group, onOpen }: { ) } -function ReconcileCard({ item, data, original }: { item: LedgerReconciled; data?: RunLedger; original?: string }) { +/** + * 「差在哪」的说明有没有帮人看懂:说明有用 / 看不懂。按下的那个是看的人最后一次给的(服务端的 mine),可以改;回来的是这次 + * 对账现在的反馈,账本再取一次(别处挂着的同一张卡跟着变) + */ +function FeedbackRow({ runId, item, readOnly }: { runId: string; item: LedgerReconciled; readOnly: boolean }) { + const refresh = useLedger((s) => s.refresh) + const [fb, setFb] = useState(item.feedback) + const [busy, setBusy] = useState(null) + useEffect(() => { setFb(item.feedback) }, [item.feedback]) + const F = LEDGER_UI.result.feedback + const give = async (verdict: LedgerFeedbackVerdict) => { + setBusy(verdict) + try { + const out = await api.caliberLedger.feedback(runId, item.run_id, verdict) + setFb(out.feedback) + toast.ok(F.saved) + refresh(runId) + } catch (e) { + toast.error(e) + } finally { + setBusy(null) + } + } + const counts = fb ? F.counts(fb.useful, fb.unclear) : '' + return ( +
    + {F.ask} + {(['useful', 'unclear'] as const).map((v) => ( + + ))} + {fb?.mine && {F.mine(fb.mine)}} + {counts && {counts}} +
    + ) +} + +/** 这张对账卡对照的那份相关口径「差在哪」(问数据的轮次里卡片上方没有这一段,反馈要有说的是什么) */ +function whereOf(data: RunLedger | undefined, item: LedgerReconciled): LedgerRelated | undefined { + return (data?.queries ?? []).find((q) => q.artifact === item.query)?.candidates + .find((c) => c.caliber === item.caliber && c.status === 'related') +} + +function ReconcileCard({ runId, item, data, original, readOnly, showWhere }: { + runId: string; item: LedgerReconciled; data?: RunLedger; original?: string; readOnly: boolean; showWhere: boolean +}) { const builder = useAtLeast('builder') const [all, setAll] = useState(false) const [target, setTarget] = useState(null) @@ -240,6 +291,7 @@ function ReconcileCard({ item, data, original }: { item: LedgerReconciled; data? const R = LEDGER_UI.result const state = item.status === 'succeeded' ? 'succeeded' : item.status === 'failed' ? 'failed' : item.status === 'cancelled' ? 'cancelled' : 'running' + const where = showWhere ? whereOf(data, item) : undefined return (
    @@ -264,20 +316,33 @@ function ReconcileCard({ item, data, original }: { item: LedgerReconciled; data? {original &&

    {R.original(original)}

    } )} + {state === 'succeeded' && showWhere && where && ( +
    +
    {LEDGER_UI.step.where}
    + +
    + )} + {state === 'succeeded' && } setTarget(null)} />
    ) } -/** 对过的账(新的在前)。original:从证据面板打开时,正文里这个数写的是什么 */ -export function ReconcileResults({ items, data, original }: { - runId: string; items: LedgerReconciled[]; data?: RunLedger; original?: string +/** + * 对过的账(新的在前)。runId 是答案的运行(反馈记在它名下的对账上);original:从证据面板打开时,正文里这个数写的是什么; + * showWhere:卡片上方没有「差在哪」时(问数据的轮次)卡里写一份,反馈问的就是它;readOnly:对话在回收站里,只看不反馈 + */ +export function ReconcileResults({ runId, items, data, original, showWhere = false, readOnly = false }: { + runId: string; items: LedgerReconciled[]; data?: RunLedger; original?: string; showWhere?: boolean; readOnly?: boolean }) { const sorted = useMemo(() => items, [items]) if (!sorted.length) return null return (
    - {sorted.map((item) => )} + {sorted.map((item) => ( + + ))}
    ) } diff --git a/frontend/src/run/LedgerStep.tsx b/frontend/src/run/LedgerStep.tsx index ce95db74..cf511dbf 100644 --- a/frontend/src/run/LedgerStep.tsx +++ b/frontend/src/run/LedgerStep.tsx @@ -1,6 +1,6 @@ import { useState, type ReactNode } from 'react' import { Link } from 'react-router-dom' -import { BookMarked, RotateCw, Scale } from 'lucide-react' +import { BookMarked, CircleCheck, Inbox, RotateCw, Scale, TriangleAlert } from 'lucide-react' import { ApiError, api } from '../api/client' import { Spinner, StatusBadge, toast } from '../components/ui' import { errorMessage } from '../lib/errors' @@ -9,7 +9,8 @@ import { LEDGER_UI, caliberName } from '../lib/termsLedger' import { useAtLeast } from '../store/auth' import { useLedger, useRunLedger, type LedgerSlot } from '../store/ledger' import type { - LedgerBinding, LedgerIssueAction, LedgerIssued, LedgerLabel, LedgerReconcileAction, LedgerRelated, RunLedger, SegmentLedger, + LedgerBinding, LedgerIssueAction, LedgerIssued, LedgerLabel, LedgerRecallMarks, LedgerReconcileAction, LedgerRelated, RunLedger, + SegmentLedger, } from '../typesLedger' import { ReconcileDialog, ReconcileResults } from './LedgerReconcile' @@ -19,7 +20,9 @@ import { ReconcileDialog, ReconcileResults } from './LedgerReconcile' * · 按口径正式出具;相关口径——差在哪 + 看差多少(口径对账:核对参数 → 发起 → 三个数各自点得开);这次的推理—— * 写「没有相关的已发布口径」;没比对的写原因。比对还没出结果时写「正在比对口径」,store/ledger 按退避轮询, * 等满了还没结论照实说、给「再取一次」; - * - 按口径正式出具那一项(IssueControl)和出具过的正式运行(IssuedList):问数据的轮次摘要用同一份。 + * - 按口径正式出具那一项(IssueControl)和出具过的正式运行(IssuedList):问数据的轮次摘要用同一份; + * - 答案身上的召回标记(RecallMarks):「已按口径「X」vN 核对,不影响」、依据有变、说的是这个答案的召回待办(链到待办), + * 「口径」一步和问数据的轮次底部用同一份。 * * 界面层不放逻辑:标签、能不能出具、能不能自动、不能的原因、要不要先核对参数都是服务端给的(GET /runs/{id}/ledger), * 这里只照着画。比对在封存之后做,脚注写明「封存后比对,不在封存范围内」,事后补比的另写按哪种口径回看。 @@ -93,6 +96,60 @@ export function LedgerWaiting({ slot, runId, compact = false }: { slot: LedgerSl ) } +/** 依据有变的几种归成两类说:目录(目录里影响数字的项、新码值、处理变化时改了目录)和表结构;认不出的只说依据有变,不猜 */ +const BASIS_GROUP: Record = { + catalog: 'catalog', values: 'catalog', catalog_edit: 'catalog', structure: 'structure', +} + +/** 有没有要画的召回标记 */ +export const hasRecallMarks = (recall: LedgerRecallMarks | undefined) => + !!(recall?.checked?.some((c) => !c.changed) || recall?.basis?.length || recall?.tasks?.length) + +/** + * 答案身上的召回标记(细案做法 7):「已按口径「X」v3 核对,不影响」、「依据的数据目录有变(2 项)」,看的这个人手上有说的 + * 是这个答案的 recall 待办时链到待办。标记是服务端从这次运行上封存后追加的 ledger.recalled、ledger.basis_changed 读出来的 + * (ledger/recall.answer_marks),这里只照着写;同一份口径核对过几次只写最近的那一版,依据有变按两类各写一行、项数相加 + */ +export function RecallMarks({ recall }: { recall?: LedgerRecallMarks }) { + if (!hasRecallMarks(recall)) return null + const R = LEDGER_UI.recall + const checked = new Map[number]>() + for (const c of recall?.checked ?? []) if (!c.changed) checked.set(String(c.workflow_id ?? ''), c) + const basis = new Map<'catalog' | 'structure' | 'other', { items: number; errors: number }>() + for (const b of recall?.basis ?? []) { + const group = BASIS_GROUP[String(b.kind ?? '')] ?? 'other' + const cur = basis.get(group) ?? { items: 0, errors: 0 } + basis.set(group, { items: cur.items + (b.items ?? 0), errors: cur.errors + (b.new_errors ?? 0) }) + } + const tasks = recall?.tasks ?? [] + return ( +
      + {[...checked.values()].map((c) => ( +
    • + + {R.checked(caliberName(c.workflow_name, c.to_version))} +
    • + ))} + {[...basis.entries()].map(([group, b]) => ( +
    • + + + {R.basis(group, b.items)} + {b.errors > 0 && · {R.newErrors(b.errors)}} + +
    • + ))} + {tasks.map((t) => ( +
    • + + {t.reason === 'caliber' ? R.taskCaliber(t.to_version) : t.reason === 'catalog' ? R.taskBasis : R.taskOther} + {R.task} +
    • + ))} +
    + ) +} + /** 比对的来历:封存后比对,不在封存范围内;事后补比的写按哪种口径回看 */ export function LedgerFootnote({ data }: { data: RunLedger }) { return ( @@ -251,9 +308,14 @@ export function LedgerPart({ runId, runClass, report, segId, segText, segLedger, return (

    {LEDGER_UI.step.unreadable(data.reason ?? '')}

    +
    ) } + // 没比对的答案照样可能被标依据有变:标记说的是整个答案,这一步只写它 + if (data && hasRecallMarks(data.recall)) { + return
    + } return null } const queries = label.queries ?? (label.query ? [label.query] : []) @@ -304,7 +366,7 @@ export function LedgerPart({ runId, runClass, report, segId, segText, segLedger, {LEDGER_UI.reconcile.button} ) : r.comparable === false ?

    {r.reason || LEDGER_UI.step.notComparable}

    : null} - {!!done.length && } + {!!done.length && }
    ) })} @@ -316,6 +378,7 @@ export function LedgerPart({ runId, runClass, report, segId, segText, segLedger, {label.kind === 'unknown' && (

    {LEDGER_TEXT.kind.unknown}{label.reason ? `:${label.reason}` : ''}

    )} + {hasRecallMarks(data?.recall) &&
    } {data && } {dialog && data && ( setDialog(null)} /> diff --git a/frontend/src/run/LedgerTurn.tsx b/frontend/src/run/LedgerTurn.tsx index ab5e1e12..fcb7bedd 100644 --- a/frontend/src/run/LedgerTurn.tsx +++ b/frontend/src/run/LedgerTurn.tsx @@ -4,13 +4,17 @@ import { LEDGER_TEXT } from '../lib/terms' import { LEDGER_UI } from '../lib/termsLedger' import { useRunLedger } from '../store/ledger' import type { LedgerIssueAction, LedgerReconcileAction, LedgerRelated, RunLedger } from '../typesLedger' -import { IssueControl, IssuedList, LedgerFootnote, LedgerWaiting, caliberOf, ledgerEnabled, ledgerErrorShown } from './LedgerStep' +import { + IssueControl, IssuedList, LedgerFootnote, LedgerWaiting, RecallMarks, caliberOf, hasRecallMarks, ledgerEnabled, ledgerErrorShown, +} from './LedgerStep' import { ReconcileDialog, ReconcileResults } from './LedgerReconcile' /** * 问数据轮次底部的口径账本(docs/design/next-round/02-口径账本.md 做法 11):一行摘要(「3 个数来自口径「周销售」v3, * 1 个数是这次的推理」)和对应的动作——整题等价时按口径正式出具(能自动的写正在自动出具),有相关口径时对账; - * 正式出具的结果(自动的、一键的)挂在轮次下面、点开去运行;对过的账一张结果卡片,三个数各自点得开。 + * 正式出具的结果(自动的、一键的)挂在轮次下面、点开去运行;对过的账一张结果卡片,三个数各自点得开,卡里写「差在哪」、 + * 问说明有没有帮助(说明有用 / 看不懂)。答案身上的召回标记(「已按口径「X」vN 核对,不影响」、依据有变、说的是这个答案的 + * 召回待办)也写在这里:以前只在「过程」里点开才看得到,使用者又进不了记录页;没比对的答案照样可能带着,单独写一行。 * * 比对在封存之后做:轮次刚交付时写「正在比对口径」,store/ledger 按退避再取,等满了还没结论照实说、给「再取一次」。 * 不靠实时流(ledger.matched 追加时这次运行的事件总线已经关了)。界面层不放逻辑:每个数的标签、整题判断、能不能出具、 @@ -62,12 +66,21 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: { ) } - if (!data || data.state !== 'matched' || !summary) return null + if (!data) return null + // 召回标记(依据有变、已按 vN 核对)说的是整个答案:没比对过、不比对的答案照样可能带着,单独写一行 + const marked = hasRecallMarks(data.recall) + if (data.state !== 'matched' || !summary) { + return marked ? ( +
    + +
    + ) : null + } const issue = (data.actions ?? []).find((a): a is LedgerIssueAction => a.kind === 'issue') const reconciles = reconcileEntries(data) const issued = data.issued ?? [] const reconciled = data.reconciled ?? [] - if (!summary.total && !issued.length && !reconciled.length) return null + if (!summary.total && !issued.length && !reconciled.length && !marked) return null const whole = data.whole return (
    @@ -83,6 +96,7 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: { {LEDGER_UI.turn.whole(caliberOf(whole), LEDGER_TEXT.how[whole.how === 'composed' ? 'composed' : 'independent'])}

    )} + {(issue || reconciles.length > 0) && (
    {issue && } @@ -96,7 +110,7 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: {
    )} - {reconciled.length > 0 && } + {reconciled.length > 0 && } {dialog && setDialog(null)} />}
    diff --git a/frontend/src/typesLedger.ts b/frontend/src/typesLedger.ts index 982c2dfd..ae5e868a 100644 --- a/frontend/src/typesLedger.ts +++ b/frontend/src/typesLedger.ts @@ -182,6 +182,44 @@ export interface LedgerReconciled { card?: string groups?: LedgerReconcileGroup[] created_at?: string | null + /** 「说明有用 / 看不懂」(服务端 ledger/feedback.feedback_of):看的这个人最后一次给的、各几个人 */ + feedback?: LedgerFeedback +} + +export type LedgerFeedbackVerdict = 'useful' | 'unclear' + +/** 对账结果上的反馈:mine 是看的这个人最后一次给的(没给过为空),useful / unclear 是各几个人(每人只算最后一次) */ +export interface LedgerFeedback { + mine?: LedgerFeedbackVerdict | null + useful: number + unclear: number +} + +/** POST /api/ledger/answers/{run}/reconcile/{对账运行}/feedback 的答复 */ +export interface LedgerFeedbackOut { + run_id: string + feedback: LedgerFeedback +} + +/** + * 答案身上的召回标记(GET /runs/{id}/ledger 的 recall,服务端 ledger/recall.answer_marks;细案做法 7「依据有变」「已按 vN + * 核对,不影响」)。几种 state 都可能带:没比对过、不比对的答案照样可能被标依据有变。不放数、表名、取值 + */ +export interface LedgerRecallMarks { + /** 口径升版后召回重算、数没变:在这个答案上记的「已按 vN 核对,不影响」 */ + checked?: { + workflow_id?: string | null + workflow_name?: string | null + from_version?: number | null + to_version?: number | null + recall_run?: string | null + changed?: boolean + at?: string | null + }[] + /** 依据有变:kind 是 catalog(目录里影响数字的项被驳回或修改)/ structure(表结构)/ values(新码值)/ catalog_edit */ + basis?: { kind?: string | null; items?: number; new_errors?: number; at?: string | null }[] + /** 看的这个人手上、说的是这个答案的 recall 待办(还没处理的) */ + tasks?: { id: string; reason?: string; to_version?: number | null }[] } export interface LedgerCaliber { @@ -220,6 +258,7 @@ export interface RunLedger { actions?: LedgerAction[] issued?: LedgerIssued[] reconciled?: LedgerReconciled[] + recall?: LedgerRecallMarks } /** 证据片段接口(GET /runs/{id}/evidence/segments/{seg})的 ledger 键:这个片段的标签和比对的来历 */ diff --git a/scripts/check-chat.mjs b/scripts/check-chat.mjs index 688e66df..0d38c41c 100644 --- a/scripts/check-chat.mjs +++ b/scripts/check-chat.mjs @@ -33,14 +33,17 @@ // 17. 口径账本(next-round 02):交付了的轮次底部写「正在比对口径」,按退避再取到比对出结果、比完不再取;一行摘要 // (几个数来自哪份口径)、按口径正式出具和对账按钮照服务端给的动作摆;出具、对账的写请求在浏览器层拦下并核对请求体, // 出具过的正式运行挂在轮次下面(档位、打开运行)。 -// 18. 过程里被驳回的那一步(node.failed 带 reason=rejected):停止的剪影、中性色、行尾写「被驳回」,不画成完成的绿勾。 +// 18. 过程里被驳回的那一步(node.failed 带 reason=rejected):停止的剪影、中性色、行尾写「被驳回」,不画成完成的绿勾; +// 19. 答案身上的召回标记(账本接口的 recall)写在轮次底部:「已按口径「X」vN 核对,不影响」、依据有变(目录 / 表结构,几项、 +// 按新目录新出现几条错误级问题),看的人手上有说的是这个答案的召回待办时链到待办;没比对的答案照样写依据有变;做完的 +// 对账卡上写「差在哪」、问说明有没有帮助(说明有用 / 看不懂)。 // // 所有写请求都被拦在浏览器里,不碰任何库。 // 跑之前前端得起着(./scripts/dev.sh),默认连 5273。对别的实例(比如一份沙箱拷贝)跑时 // 带上地址:AGENTLAB_WEB=http://localhost:<前端端口> node scripts/check-chat.mjs import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' import { mkdirSync, readFileSync } from 'node:fs' -import { ISSUE, RECONCILE, WHOLE, WHOLE_LABELS, ledgerOf } from './ledger-fixtures.mjs' +import { ISSUE, RECALL, RECONCILE, WHOLE, WHOLE_LABELS, ledgerOf, metricDetail, reconciledOf } from './ledger-fixtures.mjs' const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' const CHROME = process.env.CHROME_PATH @@ -1653,6 +1656,58 @@ for (const theme of THEMES) { } }) + await section('recall', '口径账本:答案身上的召回标记写在轮次底部(已按 vN 核对,不影响;依据有变;有待办时链到待办)', async () => { + // 召回在原答案的运行上追加 ledger.recalled、ledger.basis_changed(封存后),账本接口的 recall 把它们交出来(02 做法 7)。 + // 以前只在「过程」里点开才看得到,使用者又进不了记录页。没比对的答案(state 不是 matched)照样可能被标依据有变 + ctl.ledgerConvs = true + try { + // 比对过的那份另带一次做完的对账(另有两个人说过说明有用):轮次里卡片上方没有「差在哪」,卡里写一份,反馈问的就是它 + const reconciled = [{ ...reconciledOf('succeeded'), feedback: { mine: null, useful: 2, unclear: 0 } }] + for (const [name, LED] of [['matched', { ...ledgerOf('run-led', { labels: WHOLE_LABELS, whole: WHOLE, actions: [], reconciled }), + recall: RECALL }], + ['ineligible', { run_id: 'run-led', state: 'ineligible', reason: '这种来源的运行不比对', note: '封存后比对,不在封存范围内', + recall: { checked: [], basis: [{ kind: 'structure', items: 1, new_errors: 0, at: iso(5) }], tasks: [] } }]]) { + const { page, ctx, errors } = await open(theme) + await page.route(/\/api\/artifacts\//, (route) => route.fulfill({ json: { id: EVIDENCE.doc_artifact, + content: { ...EVIDENCE.doc, run_id: 'run-led' } } })) + await page.route(/\/api\/runs\/run-led\/evidence(\/.*)?(\?.*)?$/, (route) => { + const m = new URL(route.request().url()).pathname.match(/\/segments\/([^/]+)$/) + return m ? route.fulfill({ json: EVIDENCE.segments[decodeURIComponent(m[1])] ?? {} }) : route.fulfill({ json: EVIDENCE.graph }) + }) + await page.route(/\/api\/runs\/run-led\/ledger$/, (route) => route.fulfill({ json: LED })) + await page.route(/\/api\/runs\/run-rec-1\/evidence\/metrics\/reconcile\/[^/]+$/, (route) => + route.fulfill({ json: metricDetail('run-rec-1', new URL(route.request().url()).pathname.split('/').at(-1)) })) + await goto(page, 'c0ledgr') + const marks = page.locator('[data-ledger-turn] [data-ledger-recall]').first() + const shown = await marks.waitFor({ timeout: 8000 }).then(() => true, () => false) + const text = shown ? (await marks.innerText()).replace(/\s+/g, ' ') : '' + if (name === 'matched') { + check('轮次底部写「已按口径「周报口径」v3 核对,不影响」(核对过两次只写最近那一版)', shown + && text.includes('已按口径「周报口径」v3 核对,不影响') && !text.includes('v2 核对'), text) + check('……依据有变:项数相加,写按新目录新出现几条错误级问题', text.includes('依据的数据目录有变(3 项)') + && text.includes('按新目录检查新出现 1 条错误级问题'), text) + const link = marks.locator('[data-ledger-recall-task="tk-recall-1"] a') + check('……有说的是这个答案的召回待办:写数变了、链到待办', text.includes('口径升到 v2,这个答案用到的数变了') + && await link.getAttribute('href').catch(() => null) === '/apps/inbox/tk-recall-1', text) + check('……和摘要在同一张账本卡里', await page.locator('[data-ledger-turn="matched"] [data-ledger-recall]').count() === 1) + const card = page.locator('[data-ledger-turn] [data-ledger-reconciled="run-rec-1"]') + const where = (await card.locator('[data-ledger-reconciled-where]').innerText().catch(() => '')).replace(/\s+/g, ' ') + check('轮次里做完的对账卡:写「差在哪」,下面问说明有没有帮助、写各几个人', where.includes('口径只保留状态为已支付的行') + && (await card.locator('[data-ledger-feedback]').innerText().catch(() => '')).includes('2 人觉得有用') + && await card.locator('[data-ledger-feedback-give]').count() === 2, where) + await page.screenshot({ path: `${SHOTS}/ledger-recall-${theme}.png` }) + } else { + check('不比对的答案:轮次底部只写依据有变(表结构)', shown && text.includes('依据的表结构有变(1 项)') + && await page.locator('[data-ledger-turn="recall"]').count() === 1 && await page.locator('[data-ledger-summary]').count() === 0, text) + } + check(`没有运行时报错(${name})`, errors.length === 0, errors[0] ?? '') + await ctx.close() + } + } finally { + ctl.ledgerConvs = false + } + }) + await section('fixfirst', '要改的东西在工具库里:先去改参数定义,「接着跑」退成次要', async () => { ctl.fixConvs = true try { diff --git a/scripts/check-evidence.mjs b/scripts/check-evidence.mjs index 84d326b8..9c06ecbd 100644 --- a/scripts/check-evidence.mjs +++ b/scripts/check-evidence.mjs @@ -17,7 +17,7 @@ // EVIDENCE_SHOTS=<目录> 时亮暗两套各截几张,供人眼复核。 import { readFileSync } from 'node:fs' import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' -import { ledgerOf } from './ledger-fixtures.mjs' +import { RECALL, ledgerOf } from './ledger-fixtures.mjs' const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' const CHROME = process.env.CHROME_PATH @@ -4207,6 +4207,40 @@ await section('ledger', '口径账本:来自口径的数字挂小标记(受 await r.ctx.close() }) +await section('ledger-recall', '口径账本:答案身上的召回标记写在「口径」一步里(已按 vN 核对,不影响;依据有变;有待办时链到待办)', async () => { + // 召回在原答案的运行上追加 ledger.recalled、ledger.basis_changed(封存后),账本接口的 recall 把它们交出来(02 做法 7)。 + // 以前它们只在运行时间线里,证据面板、问数据的轮次都看不见。没比对的答案(state 不是 matched)照样可能被标依据有变 + for (const [name, LED] of [['matched', { ...ledgerOf(fx.run_id), recall: RECALL }], + ['ineligible', { run_id: fx.run_id, state: 'ineligible', reason: '这种来源的运行不比对', note: '封存后比对,不在封存范围内', + recall: { checked: [], basis: RECALL.basis, tasks: [] } }]]) { + const r = await open('/ui-harness.html?evidence=1', { before: (page) => page.route( + (u) => new URL(u).pathname === `/api/runs/${fx.run_id}/ledger`, (route) => route.fulfill({ json: LED })) }) + const p = r.page + const part = p.locator('[data-evidence-panel] [data-ev-ledger]') + await openSeg(p, 's6', '[data-ev-ledger]') + const marks = p.locator('[data-evidence-panel] [data-ledger-recall]') + await marks.waitFor({ timeout: 4000 }).catch(() => {}) + const text = (await marks.innerText().catch(() => '')).replace(/\s+/g, ' ') + if (name === 'matched') { + check('比对过的答案:「口径」一步写「已按口径「周报口径」v3 核对,不影响」(核对过两次只写最近那一版)', + text.includes('已按口径「周报口径」v3 核对,不影响') && !text.includes('v2 核对') && await p.locator('[data-evidence-panel] [data-ledger-recall-checked]').count() === 1, + text) + check('……依据有变:目录那一类两次的项数相加,写按新目录新出现几条错误级问题', text.includes('依据的数据目录有变(3 项)') + && text.includes('按新目录检查新出现 1 条错误级问题'), text) + const link = p.locator('[data-evidence-panel] [data-ledger-recall-task="tk-recall-1"] a') + check('……看的人手上有说的是这个答案的召回待办:写数变了、链到待办', text.includes('口径升到 v2,这个答案用到的数变了') + && await link.getAttribute('href').catch(() => null) === '/apps/inbox/tk-recall-1', text) + check('……标记写在「口径」一步里,标签照旧', await part.getAttribute('data-ev-ledger').catch(() => null) === 'caliber') + if (SHOTS) await p.locator('[data-evidence-panel]').screenshot({ path: `${SHOTS}/ledger-recall.png` }).catch(() => {}) + } else { + check('不比对的答案:没有标签,「口径」一步只写依据有变', await part.getAttribute('data-ev-ledger').catch(() => null) === 'recall' + && text.includes('依据的数据目录有变(3 项)') && !text.includes('核对,不影响'), text) + } + check(`没有运行时报错(${name})`, r.errors.length === 0, r.errors.join(' | ')) + await r.ctx.close() + } +}) + check('没有运行时报错(组件预览)', harness.errors.length === 0, harness.errors.join(' | ')) await harness.ctx.close() await browser.close() diff --git a/scripts/check-ledger.mjs b/scripts/check-ledger.mjs index 62000b94..1ac25b3c 100644 --- a/scripts/check-ledger.mjs +++ b/scripts/check-ledger.mjs @@ -6,7 +6,8 @@ // 之后才追加);等满了还没有结论照实说、给「再取一次」,点了重新取、取到就画;三种情况(来自口径 / 相关口径 / 这次的 // 推理)各写各的; // - 口径对账:核对参数(推断的参数要先核对)→ 发起(认不出列怎么配时照 409 带回的选项选对照的指标,再发起)→ 结果卡片: -// 这次 / 口径 / 差值 / 相对差四个数各自取值、点开是出处链;请求体逐项核对; +// 这次 / 口径 / 差值 / 相对差四个数各自取值、点开是出处链;请求体逐项核对;做完的卡片上问「差在哪」的说明有没有帮助 +// (说明有用 / 看不懂,统计 E2):请求体只有 verdict,选过的按下、写各几个人,能改主意;没做完的不问; // - 可沉淀的问题:工作流列表弹窗里的抽屉,三类来源分开写;「固化成口径草稿」走 from-run 的 freeze(带同组的别的运行)、 // 打开画布;聚类按人挑的那一轮固化;「不是口径」要写理由; // - 使用者看到的入口照服务端的动作:不能出具的写原因(请搭建者出具)、不摆出具按钮,能对账的照样对账;出具过的正式运行 @@ -180,8 +181,15 @@ await section('「口径」一步的三种情况:来自口径、相关口径 // ---------------------------------------------------------------- 对账 await section('口径对账:核对参数 → 发起 → 选对照的指标 → 三个数各自点得开', async () => { - const state = { posts: [], reconciled: [], polls: 0 } + const state = { posts: [], reconciled: [], polls: 0, feedback: [] } const extra = (method, p, body) => { + // 「说明有用 / 看不懂」:服务端交回这次对账现在的反馈(看的人最后一次给的、各几个人;另有一个人之前说过有用) + if (method === 'POST' && p === `/ledger/answers/${RUN}/reconcile/run-rec-1/feedback`) { + state.feedback.push(body) + const fb = { mine: body?.verdict, useful: 1 + (body?.verdict === 'useful' ? 1 : 0), unclear: body?.verdict === 'unclear' ? 1 : 0 } + state.reconciled = state.reconciled.map((r) => ({ ...r, feedback: fb })) + return { json: { run_id: 'run-rec-1', feedback: fb } } + } if (method === 'POST' && p === `/ledger/answers/${RUN}/reconcile`) { state.posts.push(body) if (!body?.pairs) { @@ -236,6 +244,7 @@ await section('口径对账:核对参数 → 发起 → 选对照的指标 → const card = page.locator('[data-evidence-panel] [data-ledger-reconciled="run-rec-1"]') const running = await card.waitFor({ timeout: 6000 }).then(() => true, () => false) check('结果卡片:对账运行还在进行时写「对账进行中」', running && (await card.innerText()).includes('对账进行中')) + check('……还没做完:不问说明有没有用', await card.locator('[data-ledger-feedback-give]').count() === 0) const done = await page.locator('[data-evidence-panel] [data-ledger-reconciled-state="succeeded"]').waitFor({ timeout: 12000 }).then(() => true, () => false) check('……再取一次(运行还没结束时接着等),做完了画出每组对照', done) await until(async () => (await card.innerText()).includes(RECONCILE_VALUES.diff_0), 5000) @@ -244,6 +253,24 @@ await section('口径对账:核对参数 → 发起 → 选对照的指标 → && cardText.includes(`按口径 ${RECONCILE_VALUES.cal_0}`) && cardText.includes(`差值 ${RECONCILE_VALUES.diff_0}`) && cardText.includes(`相对差 ${RECONCILE_VALUES.rel_0}`), cardText) check('……写参数从哪来、原答案里写的是什么', cardText.includes('按核对过的参数') && cardText.includes('原答案里写的是 8.7%'), cardText) + + // 「差在哪」的说明有没有帮人看懂(02 做法 10 的 E2):做完的卡片上问一句,记成对账运行上的封存后事件 + const fbRow = card.locator('[data-ledger-feedback]') + check('做完的卡片问「差在哪」的说明有没有帮助:说明有用 / 看不懂', (await fbRow.innerText().catch(() => '')).includes('说明有用') + && await card.locator('[data-ledger-feedback-give]').count() === 2, await fbRow.innerText().catch(() => '')) + await card.locator('[data-ledger-feedback-give="unclear"]').click() + await until(() => state.feedback.length === 1) + check('点「看不懂」:请求体只有 verdict,记在这次答案的这次对账上', JSON.stringify(state.feedback[0]) === JSON.stringify({ verdict: 'unclear' }), + JSON.stringify(state.feedback[0])) + const pressed = await until(async () => await card.locator('[data-ledger-feedback-give="unclear"]').getAttribute('aria-pressed') === 'true', 4000) + const fbText = (await fbRow.innerText().catch(() => '')).replace(/\s+/g, ' ') + check('……选过的按下,写各几个人(服务端给的数)', pressed && fbText.includes('1 人觉得有用') && fbText.includes('1 人看不懂'), fbText) + await card.locator('[data-ledger-feedback-give="useful"]').click() + await until(() => state.feedback.length === 2) + const changed = await until(async () => await card.locator('[data-ledger-feedback-give="useful"]').getAttribute('aria-pressed') === 'true', 4000) + check('改主意:再点「说明有用」照样记一条,按下的换过来', changed && JSON.stringify(state.feedback[1]) === JSON.stringify({ verdict: 'useful' }) + && await card.locator('[data-ledger-feedback-give="unclear"]').getAttribute('aria-pressed') === 'false') + await card.locator('[data-ledger-value="diff_0"]').click() const drawer = page.locator('[data-evidence-panel="side"]').last() const opened = await until(async () => (await drawer.innerText().catch(() => '')).includes('差值'), 5000) diff --git a/scripts/ledger-fixtures.mjs b/scripts/ledger-fixtures.mjs index 246efcaa..049e7b35 100644 --- a/scripts/ledger-fixtures.mjs +++ b/scripts/ledger-fixtures.mjs @@ -51,6 +51,25 @@ export function ledgerOf(runId, { whole, actions, issued = [], reconciled = [], } } +/** + * 答案身上的召回标记(服务端 ledger/recall.answer_marks):周报口径升到 v3 重算过、数没变(同一份口径核对过两次,只写最近 + * 那一版);目录里影响数字的两项被驳回、按新目录检查新出现 1 条错误级问题,另有一次出现了新码值(同归「数据目录」那一类, + * 项数相加);看的这个人手上有一条说的是这个答案的 recall 待办(订单口径升到 v2,数变了) + */ +export const RECALL = { + checked: [ + { workflow_id: 'wf-weekly', workflow_name: '周报口径', from_version: 1, to_version: 2, recall_run: 'run-rc0', changed: false, + at: '2026-10-14T01:00:00+00:00' }, + { workflow_id: 'wf-weekly', workflow_name: '周报口径', from_version: 2, to_version: 3, recall_run: 'run-rc1', changed: false, + at: '2026-10-15T01:00:00+00:00' }, + ], + basis: [ + { kind: 'catalog', items: 2, new_errors: 1, at: '2026-10-15T02:00:00+00:00' }, + { kind: 'values', items: 1, new_errors: 0, at: '2026-10-15T03:00:00+00:00' }, + ], + tasks: [{ id: 'tk-recall-1', reason: 'caliber', to_version: 2 }], +} + /** 看差多少(s8 那条查询、订单口径):参数是推断的,要先核对 */ export const RECONCILE = { kind: 'reconcile', query: 'q-orders', caliber: ORDERS.caliber, workflow_id: ORDERS.workflow_id, version: 1, node_id: 'fetch',