可点击证据第一期:报告里的每个数字都点得开出处

「引用即渲染」:写报告的模型只写引用标记([[m:指标id]]、[[i:输入字段]]、[[see:…]]),数值由系统按口径卡
填进去,每个数字都挂着一条能复算的证据链。本期是数字层闭环;实体、结论句的概率性证据放在后续几期。

内核(engine/evidence.py,口径卡、出具契约、表达式等)
- 口径卡记录每个指标的来源:原式、代入式(每个输入写成「值 ← 路径」)、复算结果、口径与版本
- 出具契约的数值匹配改为按位置标注;同一个值有几个出处时记为「出处不唯一」并列出候选,不再随便挑一个
- 证据 id 由内容派生,事后对不上就是被改过;零值、结构性数字(列表序号、代码块标签)单独处理
- 口径卡新增 on_missing:缺输入时默认仍是整个节点失败,可以改成记为空值、交给契约判档

报告撰写节点(report)与引用模式的出具契约
- 流式生成时 token 里就是真实数字,不会漏出原始标记;裸数字、不存在的引用当场判违规,交回去重写
  (max_repairs,默认 1 次);仍不过时按 on_violation 失败(正式运行默认)或把违规标在报告里(探索运行默认)
- report.checked 事件记下核对结果,落在封存范围内;fail 模式下仍不过时带 failed,运行记录里画成失败
- 出具契约写了 report_from 就按引用核对:取回文档时复验哈希,独立重算一遍,全部带引用才判完整出具
- 成果字段逐字等于报告正文时标注 _evidence;复核只能加说明,不能改写带证据的答案(前后端各拦一道)

证据接口
- GET /api/runs/{id}/evidence 返回证据图;GET …/evidence/segments/{id} 返回一个片段的证据链
- 只认封存范围内的事件能追到的工件,不读 artifacts 表;封存被改过时不把任何一项标成已封存
- 没有报告的旧运行降级为 none 或 legacy_contract

界面
- EvidenceDoc 按块、句、片段渲染报告,片段是和正文一样的按钮;整份报告只占一个 Tab 位,
  ←/→ 在片段间移动、↑/↓ 按句、n/N 跳到下一处「无证据」、Enter 打开面板、Esc 关闭并把焦点还回去
- EvidencePanel:宽屏侧边、窄屏底部抽屉、360px 画布右栏里栏内展开;显示指标步骤、代入式、复算结果、
  封存状态。正文不是封存的那份报告时明确说出来,不拿别的报告的封存画绿
- 出具横幅多一行「N/N 数字有出处 · 无证据 M」和「定位下一处」;没有 _evidence 的旧回答渲染一字不差
- 画布认得报告撰写节点;Copilot 手册补上口径卡、报告节点、出具契约的写法;新增模板「⑨ 可追溯周报」

验证(沙箱):tsc 干净,生产构建通过,pytest 1601 passed,check-all 16 项检查全绿(新增 check-evidence)。
This commit is contained in:
ThearchyHelios
2026-09-28 11:47:23 +08:00
parent b418c0d951
commit e4f2693918
56 changed files with 12309 additions and 215 deletions
+2 -1
View File
@@ -587,8 +587,9 @@ function RunView({ onBack, reveal, onRevealed }: {
? { error: String(failedEvent?.data?.error ?? run.error ?? '运行失败'),
...(failedEvent?.data?.detail ? { detail: String(failedEvent.data.detail) } : {}) }
: undefined,
// #runId 已经在栏头上了(可点,去运行记录),卡片里不再重复
// #runId 已经在栏头上了(可点,去运行记录),卡片里不再重复;成果里的报告取证据链照样要它
runClass: run.run_class,
outputRun: run.id,
startedAt: trace.startedAt,
// 栏头只在不跑的时候写它;跑着的时候耗时细条按各步自己的耗时比
elapsedMs: phase === 'waiting' || isSettled(phase) ? stoppedActiveMs(run.usage, trace) : undefined,
+78 -30
View File
@@ -5,7 +5,7 @@ import {
import { Link } from 'react-router-dom'
import {
AlertCircle, AlertTriangle, ArrowDown, Brain, ChevronRight, CircleCheck, CircleDot, CornerDownRight,
Database, Download, ExternalLink, FileCode, FileDown, GitBranch, Hand, Info, Play, Settings2,
Database, Download, ExternalLink, FileCode, FileDown, GitBranch, Hand, Info, ListChecks, Play, Settings2,
ShieldCheck, Sparkles, Table2, Terminal, UserX, Users, Wrench, XCircle,
} from 'lucide-react'
import clsx from 'clsx'
@@ -15,13 +15,16 @@ import { humanizeError } from '../lib/errors'
import { explainRunError } from '../lib/explain'
import { formatClock, formatDuration, formatNumber, NONE, shortId } from '../lib/format'
import { statusLabel } from '../lib/status'
import { issuanceLabel, nodeTypeLabel } from '../lib/terms'
import { EVIDENCE_TEXT, evidenceTally, issuanceLabel, nodeTypeLabel } from '../lib/terms'
import {
childrenByExec, compactSteps, parseQueryResult, progressOf, spread, teamVerdictOf,
type Exec, type FixKind, type ResultTable as Table, type Step, type StepKind, type TeamMemberEx,
type TeamRun,
} from './decode'
import { CODE_COLUMN, CopyChip, LEADING_ZERO, Markdown, type MarkSpec } from './Markdown'
import { EvidenceField, type EvidenceDocHandle } from './EvidenceDoc'
import { docTally, evidenceFields, issuanceMarks, type EvidenceTally } from '../lib/evidence'
import type { EvidenceDocData } from '../types'
import { useRunClock } from './useRunClock'
import type { ReviewResult } from '../types'
@@ -81,6 +84,11 @@ export interface StreamTurn {
*/
queries?: number
runId?: string
/**
* 成果出自哪次运行:成果里的报告点开片段时按它取证据链。不给就用 runId。运行页、画布
* 右栏的头上已经有运行号、不给 runId(给了会在轮次头再挂一个运行链接),就给它
*/
outputRun?: string
/** formal / exploratory。出具横幅要据此标注"不进正式归档" */
runClass?: string
/** 这一轮建出来的图,可展开看、可放到画布 */
@@ -510,7 +518,7 @@ function TurnCard({ turn, last, approvals, onOpenGraph, onFollowUp }: {
{turn.output && (
<Output output={turn.output} runClass={turn.runClass} broken={broken}
question={turn.question} onFollowUp={onFollowUp} />
question={turn.question} onFollowUp={onFollowUp} runId={turn.outputRun ?? turn.runId} />
)}
{turn.rawOutput && (
@@ -519,7 +527,7 @@ function TurnCard({ turn, last, approvals, onOpenGraph, onFollowUp }: {
复核改写过这个答案,看改写前的原文
</summary>
<div className="mt-1.5">
<Output output={turn.rawOutput} />
<Output output={turn.rawOutput} runId={turn.outputRun ?? turn.runId} />
</div>
</details>
)}
@@ -1897,17 +1905,29 @@ function unwrapArtifact(content: unknown): { table: Table | null; text: string;
// 成果
// -------------------------------------------------------------------------
function Output({ output, runClass, broken, question, onFollowUp }: {
function Output({ output, runClass, broken, question, onFollowUp, runId }: {
output: Record<string, any>; runClass?: string; broken?: boolean
question?: string; onFollowUp?: (text: string) => void
/** 这份成果出自哪次运行:带证据的字段点开片段时按它取证据链 */
runId?: string
}) {
const { dense } = useContext(Ctx)
// _issuance 这类下划线开头的是内部字段,不是给人看的成果。
// 空值也要滤掉:output 里留一个 {"result": ""} 很常见(图跑通了但出口
// 没接上),它会渲染出一条什么都没有的分隔线——用户只会以为界面坏了
const entries = Object.entries(output)
.filter(([k, v]) => !k.startsWith('_') && !isBlank(v))
const issuance = (output as any)._issuance
const marks = useMemo(() => marksOf(issuance), [issuance])
const marks = useMemo(() => issuanceMarks(issuance), [issuance])
// 逐字等于报告撰写节点原文的字段:换成可逐段点开的文档,其余照旧。没有 _evidence 的
// 成果(旧运行、没有报告节点的图)一个字段都不会进这里,渲染和以前完全一样
const evidence = useMemo(() => evidenceFields(output), [output])
const firstEvidence = entries.find(([k, v]) => evidence.has(k) && typeof v === 'string')?.[0]
const docRef = useRef<EvidenceDocHandle>(null)
// 第一份报告文档取到之后,出具横幅多一行「N/N 数字有出处 · 无证据 M」
const [tallyDoc, setTallyDoc] = useState<EvidenceDocData | null>(null)
const tally = useMemo(() => (tallyDoc ? docTally(tallyDoc) : null), [tallyDoc])
const banner = !!issuance?.tier
const follow = useMemo(() => (onFollowUp ? followUpsOf(entries.map(([, v]) => v)) : []),
// eslint-disable-next-line react-hooks/exhaustive-deps
[output, onFollowUp])
@@ -1915,7 +1935,16 @@ function Output({ output, runClass, broken, question, onFollowUp }: {
return (
<div className="group/answer relative mt-2 space-y-2 border-t pt-2">
{issuance && <IssuanceBanner issuance={issuance} runClass={runClass} />}
{issuance && (
// 成果里有报告字段就告诉横幅:正文换成了报告文档,回指不上的数字不再是 Markdown 上的
// 虚线(列表序号里的画不了线),而是在报告的违规清单里。文档取到后再给计数和两个动作
<IssuanceBanner issuance={issuance} runClass={runClass}
evidence={firstEvidence ? {
counts: tally ?? undefined,
onNext: tally ? () => docRef.current?.next() : undefined,
onList: tallyDoc?.violations?.length ? () => docRef.current?.list() : undefined,
} : undefined} />
)}
{broken && (
// 复核判了不可信:答案照常给(可能有参考价值),但先说清楚它不能当结论。
// 不降透明度——那会让它更难读,而不是更不可信
@@ -1936,7 +1965,16 @@ function Output({ output, runClass, broken, question, onFollowUp }: {
{entries.length > 1 && (
<div className="mb-0.5 text-2xs font-semibold text-dim">{key}</div>
)}
<OutputValue value={value} marks={marks} label={key} />
{evidence.has(key) && typeof value === 'string'
? (
<EvidenceField
ref={key === firstEvidence ? docRef : undefined}
artifact={evidence.get(key)!.artifact} text={value} runId={runId} dense={dense} label={key}
tally={!banner}
onDoc={key === firstEvidence ? setTallyDoc : undefined}
/>
)
: <OutputValue value={value} marks={marks} label={key} />}
</div>
))}
</div>
@@ -2030,26 +2068,6 @@ function followUpsOf(values: unknown[]): string[] {
return []
}
/** 出具里无法回指的数字,在正文原句上画出来 */
function marksOf(issuance: any): MarkSpec[] | undefined {
const unmatched: any[] = issuance?.unmatched_numbers ?? []
const matched: any[] = Array.isArray(issuance?.matched) ? issuance.matched : []
const marks: MarkSpec[] = [
...unmatched.map((u) => ({
token: String(u?.token ?? u),
tone: 'warn' as const,
title: `这个数字在口径卡里找不到来源${u?.context ? `:「${u.context}」` : ''}`,
})),
// 后端给了逐个数字的回指(matched: [{token, metric}])就标出来源;目前只给计数
...matched.map((m) => ({
token: String(m?.token ?? ''),
tone: 'ok' as const,
title: `来自口径卡指标「${m?.metric ?? ''}」${m?.caliber ? ` · ${m.caliber}` : ''}`,
})),
].filter((m) => m.token)
return marks.length ? marks : undefined
}
const TEXT_CAP = 3000
/**
@@ -2158,8 +2176,13 @@ const TIER_META: Record<string, { color: string; soft: string; hint: string }> =
* 为空」「指标集为空」这类校验根本没跑起来的缺口(gaps)一条都不显示——横幅
* 说「请对照下方声明」,下方什么都没有。
*/
export function IssuanceBanner({ issuance, runClass }: {
export function IssuanceBanner({ issuance, runClass, evidence }: {
issuance: any; runClass?: string
/**
* 成果里有报告文档时给:它的计数(文档取到之后才有)、跳到下一处无证据、打开违规清单。
* 给了它,正文里带证据的字段就不是 Markdown 了,「正文里已用虚线标出」不再成立
*/
evidence?: { counts?: EvidenceTally; onNext?: () => void; onList?: () => void }
}) {
const tier = String(issuance?.tier ?? '')
if (!tier) return null
@@ -2195,6 +2218,20 @@ export function IssuanceBanner({ issuance, runClass }: {
</span>
</div>
{meta.hint && <div className="mt-1 text-2xs leading-relaxed text-dim">{meta.hint}</div>}
{evidence?.counts && (evidence.counts.total > 0 || evidence.counts.other > 0) && (
// 逐段证据的计数:和报告核对那一行、证据条同一种说法。有无证据的地方才给「定位下一处」
<div className="mt-1 flex flex-wrap items-center gap-2 text-2xs" data-evidence-line="">
<span className="tnum" style={{
color: evidence.counts.none || evidence.counts.other ? 'var(--st-waiting)' : 'var(--st-done)' }}>
{evidenceTally(evidence.counts.cited, evidence.counts.total, evidence.counts.other)}
</span>
{(evidence.counts.none > 0 || evidence.counts.other > 0) && evidence.onNext && (
<button type="button" className="btn btn-xs" data-evidence-next="" onClick={evidence.onNext}>
{EVIDENCE_TEXT.locateNext}
</button>
)}
</div>
)}
{!!gaps.length && (
<div className="mt-1.5 text-2xs leading-relaxed" style={{ color: 'var(--st-waiting)' }}>
@@ -2216,13 +2253,24 @@ export function IssuanceBanner({ issuance, runClass }: {
)}
{!!unmatched.length && (
<div className="mt-1 text-2xs leading-relaxed" style={{ color: 'var(--st-waiting)' }}>
<span>无法回指的数字(正文里已用虚线标出):</span>
{/* 带报告文档时正文是 EvidenceDoc:列表序号里的数字画不了线,逐条都在违规清单里;
文档还没取到(或取不到)时正文是不带标记的普通文本,什么都不许诺 */}
<span data-unmatched-note="">
{!evidence ? '无法回指的数字(正文里已用虚线标出):'
: evidence.onList ? EVIDENCE_TEXT.unmatchedInDoc : EVIDENCE_TEXT.unmatchedPlain}
</span>
{unmatched.map((u: any, i: number) => (
<span key={i} className="mr-1.5 inline-block" title={u?.context ? `「${u.context}」` : undefined}>
<span className="mono tnum">{u?.token ?? String(u)}</span>
{u?.context && <span className="text-dim">({String(u.context).slice(0, 24)})</span>}
</span>
))}
{evidence?.onList && (
<button type="button" className="btn btn-xs btn-ghost align-middle" data-evidence-list=""
onClick={evidence.onList}>
<ListChecks size={11} aria-hidden /> {EVIDENCE_TEXT.violations}
</button>
)}
</div>
)}
{!!calibers.length && (
+573
View File
@@ -0,0 +1,573 @@
import {
Fragment, forwardRef, memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo,
useRef, useState, type CSSProperties, type FocusEvent as ReactFocusEvent,
type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent,
} from 'react'
import { createPortal } from 'react-dom'
import { ListChecks } from 'lucide-react'
import clsx from 'clsx'
import { rovingTarget } from '../components/ui'
import {
EVIDENCE_STATE, docTally, segmentLabel, segmentState, tallySummary, unitText, type EvidenceStateCode,
type EvidenceTally as Tally,
} from '../lib/evidence'
import { formatNumber } from '../lib/format'
import { EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, evidenceTally } from '../lib/terms'
import { useEvidence } from '../store/evidence'
import type { EvidenceBlock, EvidenceDocData, EvidenceSegment, EvidenceUnit } from '../types'
import { EvidencePanel, type PanelMode, type PanelView } from './EvidencePanel'
import { BlockView, Markdown, StyledSlice, inlineStyles, numericColumns, type InlineStyles } from './Markdown'
/**
* 报告撰写节点的文档:逐段可点的证据。
*
* 按后端切好的块、句、片段画,不再解析 Markdown:片段的边界、每个数字的出处都是后端
* 算定、进了封存的,前端重新解析一遍只会切出另一套边界。块的外观借 Markdown.tsx 的
* BlockView,和普通答案长得一模一样;有出处的数字画细实线,没有出处的画点状线、
* 句末挂「无证据」。
*
* 键盘:整份报告只占一个 Tab 位(roving tabindex)。←/→ 在有状态的片段间走,↑/↓ 按
* 句子走,n / N 跳到下一处 / 上一处无证据,回车打开证据面板,Esc 关掉并留在原片段;
* 面板开着时方向键走到哪、面板跟到哪,Tab 进面板。
*
* 长报告:事件都挂在容器上(片段只带 data-seg),块用 memo,外加
* content-visibility: auto;超过 TEXT_CAP 的部分先折叠,跳转到折叠里的片段时自动展开。
*/
export interface EvidenceDocHandle {
/** 跳到下一处(dir=-1 上一处)无证据并打开面板。一处都画不出来时打开违规清单;什么都没有返回 false */
next: (dir?: 1 | -1) => boolean
/** 打开违规清单。没有违规返回 false */
list: () => boolean
}
/** 和 AssistantStream 的长文本折叠同一个量级:先显示这么多字,后面的折起来 */
const TEXT_CAP = 3000
interface Model {
/** 可点的片段,按正文顺序 */
order: string[]
index: Map<string, number>
seg: Map<string, { seg: EvidenceSegment; unit: EvidenceUnit; block: number }>
/** 每个有可点片段的句子里第一个可点片段,按正文顺序(↑/↓ 用) */
unitFirst: string[]
unitOf: Map<string, number>
/** 无证据的片段,按正文顺序(n / N 用) */
alerts: string[]
/** 每块到它为止的累计字数(折叠用) */
chars: number[]
}
function buildModel(blocks: EvidenceBlock[]): Model {
const order: string[] = []
const index = new Map<string, number>()
const seg = new Map<string, { seg: EvidenceSegment; unit: EvidenceUnit; block: number }>()
const unitFirst: string[] = []
const unitOf = new Map<string, number>()
const alerts: string[] = []
const chars: number[] = []
let total = 0
blocks.forEach((block, b) => {
for (const unit of block.units ?? []) {
let first = true
for (const s of unit.segments ?? []) {
if (s.kind !== 'structural') total += s.text.length
const state = segmentState(s)
if (!state) continue
seg.set(s.id, { seg: s, unit, block: b })
index.set(s.id, order.length)
order.push(s.id)
if (first) { unitFirst.push(s.id); first = false }
unitOf.set(s.id, unitFirst.length - 1)
if (EVIDENCE_STATE[state].alert) alerts.push(s.id)
}
}
chars.push(total)
})
return { order, index, seg, unitFirst, unitOf, alerts, chars }
}
/** 片段的外观:线型走 data 属性(CSS 里只管线型),颜色写成两个变量交给 index.css */
function segStyle(state: EvidenceStateCode): CSSProperties {
const meta = EVIDENCE_STATE[state]
return { '--ev-line': meta.decoration, '--ev-soft': meta.soft } as CSSProperties
}
export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
doc: EvidenceDocData
/**
* 这份文档的工件 id(成果上 _evidence.doc_artifact 指的那件)。证据接口会报它答的是哪份
* 封存的文档,两边不一致时面板不信接口给的链和封存状态
*/
artifact?: string
/** 属于哪次运行。有它才能取片段的证据链和封存状态;没有(预览、导出的文档)只看文档里记下的出处 */
runId?: string
dense?: boolean
/** 成果字段名,读屏用 */
label?: string
/** 面板放哪:窄栏里栏内展开,宽屏从右侧弹出,窄屏从底部抽出。auto 按 dense 和屏宽定 */
panel?: 'auto' | PanelMode
/** 自己显示「N/N 数字有出处」那一条。上面已经有出具横幅(它会写这一行)时不用 */
tally?: boolean
}>(function EvidenceDoc({ doc, artifact, runId, dense = false, label, panel = 'auto', tally = false }, ref) {
const blocks = useMemo(() => doc.blocks ?? [], [doc])
const model = useMemo(() => buildModel(blocks), [blocks])
const counts = useMemo(() => docTally(doc), [doc])
const rootRef = useRef<HTMLDivElement>(null)
const instance = useId()
const panelId = `${instance}-panel`
const summaryId = `${instance}-summary`
const [current, setCurrent] = useState<string | null>(() => model.order[0] ?? null)
const [view, setView] = useState<PanelView | null>(null)
const [announce, setAnnounce] = useState('')
const [expanded, setExpanded] = useState(false)
const pendingFocus = useRef<string | null>(null)
const mode = usePanelMode(panel, dense)
// 换了一份文档:焦点位回到第一个片段,面板关掉
useEffect(() => {
setCurrent(model.order[0] ?? null)
setView(null)
}, [model])
// 同一时刻只开一个面板:另一份报告打开了自己的面板,这边的就收起
const owner = useEvidence((s) => s.owner)
const claim = useEvidence((s) => s.claim)
useEffect(() => {
if (view && owner && owner !== instance) setView(null)
}, [owner, instance, view])
const foldAt = useMemo(() => {
const total = model.chars[model.chars.length - 1] ?? 0
if (total <= TEXT_CAP * 1.2) return blocks.length
const at = model.chars.findIndex((c) => c > TEXT_CAP)
return Math.max(1, at < 0 ? blocks.length : at)
}, [model, blocks.length])
const shownBlocks = expanded ? blocks.length : foldAt
const totalChars = model.chars[model.chars.length - 1] ?? 0
const segEl = useCallback((id: string) =>
rootRef.current?.querySelector<HTMLElement>(`[data-seg="${CSS.escape(id)}"]`) ?? null, [])
/** 把焦点挪到某个片段上。在折叠里的先展开,渲染出来再聚焦 */
const focusSeg = useCallback((id: string, opts?: { flash?: boolean }) => {
const hit = model.seg.get(id)
if (!hit) return
setCurrent(id)
if (hit.block >= shownBlocks) {
pendingFocus.current = id
setExpanded(true)
return
}
const el = segEl(id)
if (!el) return
el.focus({ preventScroll: false })
if (opts?.flash) flashOnce(el)
}, [model, shownBlocks, segEl])
useLayoutEffect(() => {
const id = pendingFocus.current
if (!id || !expanded) return
pendingFocus.current = null
const el = segEl(id)
if (el) { el.focus(); flashOnce(el) }
}, [expanded, segEl])
const openSeg = useCallback((id: string) => {
const hit = model.seg.get(id)
if (!hit) return
claim(instance)
setView({ kind: 'seg', id })
setAnnounce(`${EVIDENCE_TEXT.panelTitle}:${segmentLabel(hit.seg, doc)}`)
}, [model, doc, claim, instance])
const openViolations = useCallback(() => {
claim(instance)
setView({ kind: 'violations' })
setAnnounce(`${EVIDENCE_TEXT.violations}:${formatNumber(doc.violations?.length ?? 0)} 条`)
}, [claim, instance, doc])
const close = useCallback((refocus = true) => {
const back = view?.kind === 'seg' ? view.id : current
setView(null)
setAnnounce('')
if (refocus && back) requestAnimationFrame(() => segEl(back)?.focus())
}, [view, current, segEl])
const step = useCallback((list: string[], from: string | null, dir: 1 | -1): string | null => {
if (!list.length) return null
const pos = from ? model.index.get(from) ?? -1 : -1
if (dir > 0) return list.find((id) => (model.index.get(id) ?? 0) > pos) ?? list[0]
for (let i = list.length - 1; i >= 0; i--) if ((model.index.get(list[i]) ?? 0) < pos) return list[i]
return list[list.length - 1]
}, [model])
useImperativeHandle(ref, () => ({
next: (dir = 1) => {
const target = step(model.alerts, view?.kind === 'seg' ? view.id : current, dir)
if (target) {
focusSeg(target, { flash: true })
openSeg(target)
return true
}
if (doc.violations?.length) { openViolations(); return true }
return false
},
list: () => {
if (!doc.violations?.length) return false
openViolations()
return true
},
}), [step, model, view, current, focusSeg, openSeg, openViolations, doc])
// 事件委托:片段只带 data-seg,点击和按键都在容器上认
const segOf = (target: EventTarget | null): string | null => {
const el = (target as HTMLElement | null)?.closest?.<HTMLElement>('[data-seg]')
return el && rootRef.current?.contains(el) ? el.dataset.seg ?? null : null
}
const onClick = (e: ReactMouseEvent) => {
const id = segOf(e.target)
if (!id) return
e.preventDefault()
setCurrent(id)
if (view?.kind === 'seg' && view.id === id) close(false)
else openSeg(id)
}
const onFocus = (e: ReactFocusEvent) => {
const id = segOf(e.target)
if (id && id !== current) setCurrent(id)
}
const onKeyDown = (e: ReactKeyboardEvent) => {
const id = segOf(e.target)
if (!id || e.altKey || e.metaKey || e.ctrlKey) return
const i = model.index.get(id) ?? 0
let target: string | null = null
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End') {
const to = rovingTarget(e, i, model.order.length, 'horizontal')
target = to >= 0 ? model.order[to] : null
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
const u = model.unitOf.get(id) ?? 0
const n = model.unitFirst.length
target = model.unitFirst[(u + (e.key === 'ArrowDown' ? 1 : -1) + n) % n] ?? null
} else if (e.key === 'n' || e.key === 'N') {
target = step(model.alerts, id, e.shiftKey || e.key === 'N' ? -1 : 1)
if (!target) return
} else if (e.key === 'Escape' && view) {
e.preventDefault()
e.stopPropagation()
close()
return
} else if (e.key === 'Tab' && !e.shiftKey && view && mode !== 'inline') {
// 面板在页面末尾(portal):Tab 直接进面板,不让人穿过整页去找
const heading = document.getElementById(`${panelId}-title`)
if (heading) { e.preventDefault(); heading.focus() }
return
} else {
return
}
e.preventDefault()
e.stopPropagation()
if (!target) return
focusSeg(target)
// 面板开着:跟着走,读屏从 live region 听到新片段
if (view) openSeg(target)
}
const activeSeg = view?.kind === 'seg' ? view.id : null
const activeBlock = activeSeg ? model.seg.get(activeSeg)?.block ?? -1 : -1
const currentBlock = current ? model.seg.get(current)?.block ?? -1 : -1
const visual = blocks.length > 40
const panelNode = view && (
<EvidencePanel
id={panelId}
mode={mode}
doc={doc}
artifact={artifact}
runId={runId}
view={view}
onClose={() => close()}
onLocate={(id) => { focusSeg(id, { flash: true }); openSeg(id) }}
onViolations={openViolations}
/>
)
// 画不了线的两种分开说:列表序号、代码块标签里的数字,和正文里根本没有对应字的(句末依据里的引用)
const summary = tallySummary(counts, model.order.length > 0)
return (
<div ref={rootRef} data-evidence-doc="" className="min-w-0">
<p id={summaryId} className="sr-only" data-evidence-summary="">{summary}</p>
<div className="sr-only" aria-live="polite" aria-atomic="true">{announce}</div>
{tally && (counts.total > 0 || counts.other > 0) && (
<EvidenceTally counts={counts} onNext={() => {
const target = step(model.alerts, current, 1)
if (target) { focusSeg(target, { flash: true }); openSeg(target) } else openViolations()
}} onList={doc.violations?.length ? openViolations : undefined} />
)}
<div
role="group"
aria-label={label ? `报告:${label}` : '报告'}
aria-describedby={summaryId}
className={clsx('space-y-2 leading-relaxed', dense ? 'text-[11.5px]' : 'text-sm')}
onClick={onClick}
onKeyDown={onKeyDown}
onFocus={onFocus}
>
{blocks.slice(0, shownBlocks).map((block, b) => (
// 栏内面板紧跟在片段所在的块后面:片段和它的证据在视线上挨着
<Fragment key={block.id ?? b}>
<DocBlock block={block} dense={dense} doc={doc} visual={visual}
current={b === currentBlock ? current : null}
active={b === activeBlock ? activeSeg : null}
panelId={panelId} />
{mode === 'inline' && b === activeBlock && panelNode}
</Fragment>
))}
{mode === 'inline' && view?.kind === 'violations' && panelNode}
</div>
{shownBlocks < blocks.length && (
<div className="mt-1 flex items-center gap-2 text-2xs">
<span className="text-dim">…后面还有,这里先折叠了</span>
<button type="button" className="text-[var(--accent)] hover:underline" onClick={() => setExpanded(true)}>
展开全部({formatNumber(totalChars)} 字)
</button>
</div>
)}
{expanded && foldAt < blocks.length && (
<div className="mt-1 text-2xs">
<button type="button" className="text-[var(--accent)] hover:underline" onClick={() => setExpanded(false)}>收起</button>
</div>
)}
{mode !== 'inline' && panelNode && createPortal(panelNode, document.body)}
</div>
)
})
/** 定位到的片段描一下边(CSS 的 [data-flash]),同 AssistantStream 的 flash */
function flashOnce(el: HTMLElement) {
el.dataset.flash = 'focus'
setTimeout(() => { if (el.dataset.flash === 'focus') delete el.dataset.flash }, 1600)
}
/** 面板放哪。auto:窄栏(dense)里栏内展开,宽屏侧边,窄屏底部抽屉;屏宽变了跟着变 */
function usePanelMode(panel: 'auto' | PanelMode, dense: boolean): PanelMode {
const query = '(min-width: 900px)'
const [wide, setWide] = useState(() => typeof matchMedia !== 'function' || matchMedia(query).matches)
useEffect(() => {
if (panel !== 'auto' || dense || typeof matchMedia !== 'function') return
const mq = matchMedia(query)
const on = () => setWide(mq.matches)
on()
mq.addEventListener('change', on)
return () => mq.removeEventListener('change', on)
}, [panel, dense])
if (panel !== 'auto') return panel
if (dense) return 'inline'
return wide ? 'side' : 'drawer'
}
/** 证据条:没有出具横幅时由文档自己说「7/12 数字有出处 · 无证据 5 · 另有 1 处引用解析不了」 */
export function EvidenceTally({ counts, onNext, onList }: {
counts: Pick<Tally, 'total' | 'cited' | 'none' | 'other'>
onNext?: () => void
onList?: () => void
}) {
const clean = !counts.none && !counts.other
return (
<div className="mb-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-2xs" data-evidence-tally="">
<span className="tnum" style={{ color: clean ? 'var(--st-done)' : 'var(--st-waiting)' }}>
{evidenceTally(counts.cited, counts.total, counts.other)}
</span>
{!clean && onNext && (
<button type="button" className="btn btn-xs" data-evidence-next="" onClick={onNext}>
{EVIDENCE_TEXT.locateNext}
</button>
)}
{onList && (
<button type="button" className="btn btn-xs btn-ghost" onClick={onList} data-evidence-list="">
<ListChecks size={11} aria-hidden /> {EVIDENCE_TEXT.violations}
</button>
)}
</div>
)
}
// -------------------------------------------------------------------------
// 块与片段
// -------------------------------------------------------------------------
/** 列表项的开头:结构片段里带着行首的 - / 1. 。列表项被分成几句时,后面几句接在同一项里 */
const ITEM_START = /(^|\n)[ \t]*([-*+]|\d+[.)])[ \t]+$/
const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, active, panelId }: {
block: EvidenceBlock
dense: boolean
doc: EvidenceDocData
/**
* 长文档:块上加 content-visibility,屏幕外的块不排版不绘制。短文档不加:它自带 paint
* containment,贴着块边的片段的焦点描边会被裁掉一截,而短文档本来就不慢
*/
visual: boolean
/** 这一块里拿着 Tab 位的片段 */
current: string | null
/** 这一块里面板正开着的片段 */
active: string | null
panelId: string
}) {
const units = block.units ?? []
const root = {
'data-block': block.id,
...(visual ? { style: { contentVisibility: 'auto', containIntrinsicSize: 'auto 2.5em' } as CSSProperties } : {}),
}
const unit = (u: EvidenceUnit, opts?: { code?: boolean; tag?: boolean }) => (
<UnitView key={u.id} unit={u} doc={doc} current={current} active={active} panelId={panelId}
code={opts?.code} tag={opts?.tag ?? true} />
)
switch (block.type) {
case 'heading':
return <BlockView dense={dense} root={root} shape={{ kind: 'h', level: block.level ?? 2, body: units.map((u) => unit(u)) }} />
case 'hr':
return <BlockView dense={dense} root={root} shape={{ kind: 'hr' }} />
case 'quote':
return <BlockView dense={dense} root={root} shape={{ kind: 'quote', body: units.map((u) => unit(u)) }} />
case 'code':
return (
<BlockView dense={dense} root={root} shape={{
kind: 'code', lang: block.lang ?? '', code: units.map(unitText).join(''),
body: units.map((u) => unit(u, { code: true, tag: false })),
}} />
)
case 'list': {
const items: { key: string; depth: number; units: EvidenceUnit[] }[] = []
for (const u of units) {
const lead = u.segments?.[0]
const starts = !items.length || (lead?.kind === 'structural' && ITEM_START.test(lead.text))
if (starts) items.push({ key: u.id, depth: u.depth ?? 0, units: [u] })
else items[items.length - 1].units.push(u)
}
return (
<BlockView dense={dense} root={root} shape={{
kind: 'list', ordered: !!block.ordered, start: block.start, fitMarkers: true,
items: items.map((it) => ({ key: it.key, depth: it.depth, body: it.units.map((u) => unit(u)) })),
}} />
)
}
case 'table': {
// 表头 row = -1;一格可能被分成几句,按位置归拢
const cells = new Map<string, EvidenceUnit[]>()
let cols = 0
const rowIds: number[] = []
for (const u of units) {
const loc = u.loc ?? { row: 0, col: 0 }
const k = `${loc.row}:${loc.col}`
cells.set(k, [...(cells.get(k) ?? []), u])
cols = Math.max(cols, loc.col + 1)
if (loc.row >= 0 && !rowIds.includes(loc.row)) rowIds.push(loc.row)
}
rowIds.sort((a, b) => a - b)
const text = (row: number, col: number) => (cells.get(`${row}:${col}`) ?? []).map(unitText).join('')
const node = (row: number, col: number) =>
(cells.get(`${row}:${col}`) ?? []).map((u) => unit(u, { tag: false }))
const head = Array.from({ length: cols }, (_, c) => text(-1, c))
const rows = rowIds.map((r) => Array.from({ length: cols }, (_, c) => text(r, c)))
return (
<BlockView dense={dense} root={root} shape={{
kind: 'table',
head: Array.from({ length: cols }, (_, c) => node(-1, c)),
rows: rowIds.map((r) => Array.from({ length: cols }, (_, c) => node(r, c))),
numeric: numericColumns(head, rows),
csv: () => [head, ...rows].map((r) => r.map((v) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v)).join(',')).join('\n'),
}} />
)
}
default:
return <BlockView dense={dense} root={root} shape={{ kind: 'p', body: units.map((u) => unit(u)) }} />
}
})
/**
* 一句话:文字按行内 Markdown 渲染(整句算一次样式,跨片段的 `code`、**粗体** 不会
* 被切坏),有状态的片段包成按钮。含无证据片段的句子末尾挂「? 无证据」
*/
function UnitView({ unit, doc, current, active, panelId, code, tag }: {
unit: EvidenceUnit; doc: EvidenceDocData; current: string | null; active: string | null; panelId: string
code?: boolean; tag: boolean
}) {
const segs = (unit.segments ?? []).filter((s) => s.kind !== 'structural')
const text = segs.map((s) => s.text).join('')
const styles = useMemo<InlineStyles | null>(() => (code ? null : inlineStyles(text)), [text, code])
let pos = 0
let alert = false
const nodes = segs.map((s) => {
const from = pos
pos += s.text.length
const state = segmentState(s)
const body = styles
? <StyledSlice text={text} styles={styles} from={from} to={pos} links={!state} />
: s.text
if (!state) return <span key={s.id}>{s.strong ? <strong className="font-semibold">{body}</strong> : body}</span>
const meta = EVIDENCE_STATE[state]
if (meta.alert) alert = true
const open = active === s.id
return (
<button
key={s.id}
type="button"
className="ev-seg"
data-seg={s.id}
data-ev-state={state}
data-ev-line={meta.line}
tabIndex={current === s.id ? 0 : -1}
aria-label={segmentLabel(s, doc)}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
style={segStyle(state)}
>
{s.strong ? <strong className="font-semibold">{body}</strong> : body}
</button>
)
})
return (
<>
{nodes}
{alert && tag && (
<span className="ev-tag" aria-hidden="true" title={EVIDENCE_STATE.none.hint}>
{EVIDENCE_STATE.none.glyph}{EVIDENCE_STATE_LABEL.none}
</span>
)}
</>
)
}
/**
* 成果里带证据的那个字段:按工件 id 取文档,取到之前和取不到时照普通答案显示——
* 证据是锦上添花,拿不到不能让答案本身消失。以下情况也不画,免得把证据挂到别的字上:
* - 文档的正文和字段对不上(字段被模板加工过),或者文档根本没记正文;
* - 文档记着的运行和这份成果的运行不是同一个(成果上的 doc_artifact 是可以改写的一列)
*/
export const EvidenceField = forwardRef<EvidenceDocHandle, {
artifact: string; text: string; runId?: string; dense?: boolean; label?: string; tally?: boolean
onDoc?: (doc: EvidenceDocData | null) => void
}>(function EvidenceField({ artifact, text, runId, dense, label, tally, onDoc }, ref) {
const slot = useEvidence((s) => s.docs[artifact])
const loadDoc = useEvidence((s) => s.loadDoc)
useEffect(() => { void loadDoc(artifact) }, [artifact, loadDoc])
const doc = slot?.status === 'ok' ? slot.data ?? null : null
const mismatch = !!doc && (typeof doc.markdown !== 'string' || doc.markdown.trim() !== text.trim())
const otherRun = !!doc && !!runId && typeof doc.run_id === 'string' && !!doc.run_id && doc.run_id !== runId
const usable = doc && !mismatch && !otherRun ? doc : null
useEffect(() => { onDoc?.(usable) }, [usable, onDoc])
if (usable) {
return <EvidenceDoc ref={ref} doc={usable} artifact={artifact} runId={runId} dense={dense} label={label} tally={tally} />
}
const note = slot?.status === 'error' ? EVIDENCE_TEXT.docMissing
: otherRun ? EVIDENCE_TEXT.docOtherRun : mismatch ? EVIDENCE_TEXT.docMismatch : ''
return (
<div data-evidence-fallback={otherRun ? 'other-run' : mismatch ? 'mismatch' : slot?.status ?? 'loading'}>
<Markdown text={text} dense={dense} />
{note && <div className="mt-1 text-2xs text-faint">{note}</div>}
</div>
)
})
+452
View File
@@ -0,0 +1,452 @@
import { useEffect, useMemo, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react'
import { ArrowLeft, ListChecks, X } from 'lucide-react'
import clsx from 'clsx'
import { StatusBadge, isComposing } from '../components/ui'
import {
EVIDENCE_STATE, docForeign, graphDoc, integrityFailures, locatable, reasonOf, sealVerdict, segmentState, sourceOf,
type SealStatus,
} from '../lib/evidence'
import { formatNumber, NONE, shortId } from '../lib/format'
import { EVIDENCE_TEXT } from '../lib/terms'
import { segmentKey, useEvidence } from '../store/evidence'
import type {
EvidenceDocData, EvidenceInput, EvidenceSeal, EvidenceSegment, EvidenceStep, EvidenceUnit, EvidenceViolation,
} from '../types'
/**
* 证据面板:点开报告里的一个片段,看它从哪来。
*
* 本期(数字层)展示:片段和它所在的句子;指标步骤——名称、值、口径与版本、原式、
* 代入式(每个输入是「值 ← 路径」的小标签)、复算结果;封存状态。没有证据的片段说清
* 为什么(裸数字、引用解析不了),另有一份违规清单:列表序号、代码块标签里的数字
* 在正文里画不了线,只能在清单里找到。
*
* 数据两层来源:文档自己记着的出处(doc.catalog,打开就有),和证据接口的证据链
* (原式、代入式、输入、封存,点开才取)。接口取不到(老后端、没有运行 id 的预览)
* 就只显示第一层,并照实说缺了什么。
*
* 只信封存链:正文是按成果上的 _evidence.doc_artifact 取的(成果可以改写、工件表可以
* 事后插行),接口是从封存范围内的事件找的文档。两边不是同一份时,接口的封存状态和
* 证据链说的是另一份报告——不能挂到正文上画成绿的,要醒目地说正文不是封存的那一份。
*
* 三种摆法:side 从右侧弹出(宽屏),drawer 从底部抽出(窄屏),inline 在 360px 的
* 画布右栏里直接栏内展开。都不是模态的:开着面板照样能在正文里走。
*/
export type PanelMode = 'side' | 'drawer' | 'inline'
export type PanelView = { kind: 'seg'; id: string } | { kind: 'violations' }
export function EvidencePanel({ id, mode, doc, artifact, runId, view, onClose, onLocate, onViolations }: {
id: string
mode: PanelMode
doc: EvidenceDocData
/** 正文这份文档的工件 id:和证据接口报的封存文档比对,不是同一份就不信接口给的链 */
artifact?: string
runId?: string
view: PanelView
onClose: () => void
/** 跳到正文里的某个片段(违规清单里的「定位」) */
onLocate: (segId: string) => void
onViolations: () => void
}) {
const titleId = `${id}-title`
const found = useMemo(() => (view.kind === 'seg' ? findSeg(doc, view.id) : null), [doc, view])
const state = found ? segmentState(found.seg) : null
const meta = state ? EVIDENCE_STATE[state] : null
const onKeyDown = (e: ReactKeyboardEvent) => {
if (e.key !== 'Escape' || isComposing(e) || e.defaultPrevented) return
e.preventDefault()
// 画布上在 window 上听 Esc 的(收起检查器之类)不该跟着动
e.stopPropagation()
onClose()
}
const title = view.kind === 'violations' ? EVIDENCE_TEXT.violations : found?.seg.text ?? EVIDENCE_TEXT.panelTitle
const frame = mode === 'side'
? 'ev-panel-side fixed bottom-0 right-0 top-0 z-40 flex flex-col border-l bg-panel shadow-elev-3'
: mode === 'drawer'
? 'ev-panel-rise fixed bottom-0 left-0 right-0 z-40 flex flex-col rounded-t-lg border-t bg-panel shadow-elev-3'
: 'ev-panel-rise my-2 flex flex-col rounded-lg border bg-panel'
return (
<section
id={id}
role="region"
aria-labelledby={titleId}
data-evidence-panel={mode}
className={clsx(frame, 'text-xs')}
style={mode === 'side' ? { width: 'min(380px, 100vw)' } : mode === 'drawer' ? { maxHeight: '65vh' } : undefined}
onKeyDown={onKeyDown}
>
<header className="flex items-center gap-2 border-b px-3 py-2">
{mode === 'inline' && (
<button type="button" className="btn btn-xs btn-ghost -ml-1" onClick={onClose} aria-label={EVIDENCE_TEXT.back}>
<ArrowLeft size={12} aria-hidden /> {EVIDENCE_TEXT.back}
</button>
)}
{meta && (
<span className="chip shrink-0" style={{ color: meta.color, borderColor: meta.color }} data-ev-badge={meta.code}>
{meta.glyph && <span aria-hidden>{meta.glyph}</span>}{meta.label}
</span>
)}
<h3 id={titleId} tabIndex={-1} className="mono min-w-0 flex-1 truncate text-sm font-semibold outline-none">
{title}
</h3>
{mode !== 'inline' && (
<button type="button" className="btn btn-xs btn-ghost -mr-1" onClick={onClose} aria-label={EVIDENCE_TEXT.close}
title={`${EVIDENCE_TEXT.close}(Esc)`}>
<X size={13} aria-hidden />
</button>
)}
</header>
<div className={clsx('space-y-3 px-3 py-2.5 leading-relaxed', mode !== 'inline' && 'min-h-0 flex-1 overflow-y-auto')}>
{view.kind === 'violations'
? <ViolationList doc={doc} onLocate={onLocate} />
: found
? <SegmentBody doc={doc} artifact={artifact} runId={runId} seg={found.seg} unit={found.unit}
onViolations={onViolations} />
: <p className="text-dim">{NONE}</p>}
</div>
</section>
)
}
function findSeg(doc: EvidenceDocData, id: string): { seg: EvidenceSegment; unit: EvidenceUnit } | null {
for (const block of doc.blocks ?? []) {
for (const unit of block.units ?? []) {
const seg = (unit.segments ?? []).find((s) => s.id === id)
if (seg) return { seg, unit }
}
}
return null
}
/** 面板里的一节:小标题 + 内容 */
function Part({ title, children, ...rest }: { title: string; children: ReactNode } & Record<`data-${string}`, string>) {
return (
<div {...rest}>
<div className="mb-1 text-2xs font-medium text-faint">{title}</div>
{children}
</div>
)
}
/** 值怎么写:数带千分位、不丢小数;拿不到写「—」 */
function valueText(v: unknown): string {
if (v == null || v === '') return NONE
if (typeof v === 'number') return Number.isFinite(v) ? v.toLocaleString('en-US', { maximumFractionDigits: 20 }) : String(v)
if (typeof v === 'boolean') return v ? '是' : '否'
if (typeof v === 'object') return JSON.stringify(v)
return String(v)
}
function SegmentBody({ doc, artifact, runId, seg, unit, onViolations }: {
doc: EvidenceDocData; artifact?: string; runId?: string; seg: EvidenceSegment; unit: EvidenceUnit
onViolations: () => void
}) {
const report = doc.node_id || undefined
const key = runId ? segmentKey(runId, seg.id, report) : ''
const slot = useEvidence((s) => (key ? s.segments[key] : undefined))
const graph = useEvidence((s) => (runId ? s.graphs[runId] : undefined))
const loadSegment = useEvidence((s) => s.loadSegment)
const loadGraph = useEvidence((s) => s.loadGraph)
useEffect(() => {
if (runId) void loadSegment(runId, seg.id, report)
}, [runId, seg.id, report, loadSegment])
const answered = slot?.status === 'ok' ? slot.data : undefined
// 接口答的是另一份报告(封存的那份不是正文这份):它的链和封存状态一概不用
const foreign = docForeign(answered, { artifact, node: report, seg })
const detail = foreign ? undefined : answered
// 片段接口没给封存状态(或者取不到)时,退回整次运行的证据图
const needGraph = !!runId && !foreign && (slot?.status === 'error' || (slot?.status === 'ok' && !answered?.seal))
useEffect(() => {
if (needGraph && runId) void loadGraph(runId)
}, [needGraph, runId, loadGraph])
const graphData = needGraph && graph?.status === 'ok' ? graph.data : undefined
// 证据图兜底时也得先认出正文这份文档在不在封存的报告里
const inGraph = graphDoc(graphData, artifact)
const docIssue: 'foreign' | 'tampered' | null = foreign || inGraph === 'foreign' ? 'foreign'
: inGraph === 'tampered' ? 'tampered' : null
const state = segmentState(seg)
const cite = seg.cite
const entry = cite?.alias ? doc.catalog?.[cite.alias] : undefined
const chain: EvidenceStep[] = Array.isArray(detail?.chain) ? detail.chain : []
const metricStep = chain.find((s) => s.step === 'metric')
const inputStep = chain.find((s) => s.step === 'run_input')
const isMetric = cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep
const isInput = cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep
const violations = (doc.violations ?? []).filter((v) => v.segment === seg.id)
const seal: EvidenceSeal | undefined = docIssue ? undefined : detail?.seal ?? graphData?.seal
const reason = reasonOf(seg) || detail?.note || ''
const verdict = sealVerdict(seal, {
foreign: !!docIssue,
pending: !!runId && !seal && (slot?.status === 'loading' || graph?.status === 'loading'),
noRun: !runId,
docOnly: state !== 'deterministic',
viaGraph: slot?.status === 'error',
})
const chainFailed = !runId ? EVIDENCE_TEXT.noRun
: docIssue ? EVIDENCE_TEXT.chainForeign
: slot?.status === 'error' ? EVIDENCE_TEXT.chainMissing : ''
return (
<>
{docIssue && (
// 正文不是封存的那一份:比「有出处」三个字重要得多,放在最前面
<IntegrityList code="doc" items={[
docIssue === 'tampered' ? EVIDENCE_TEXT.integrity.docHash : EVIDENCE_TEXT.integrity.doc,
...(foreign?.sealedText != null ? [EVIDENCE_TEXT.integrity.sealedText(foreign.sealedText)] : []),
]} />
)}
<Part title={EVIDENCE_TEXT.sentence} data-ev-sentence="">
<Sentence unit={unit} active={seg.id} />
</Part>
{state === 'none' && (
<Part title="为什么没有证据" data-ev-reason="">
<p style={{ color: 'var(--st-waiting)' }}>{reason}</p>
{/* 违规的原话多半是「引用 … 解析不了:<原因>」,和上面那句重复的不再列;裸数字那条说的是怎么改,留着 */}
{violations.filter((v) => v.message && !(reason && v.message.includes(reason))).map((v, i) => (
<p key={i} className="mt-1 text-dim">{v.message}</p>
))}
{seg.ref && <p className="mono mt-1 text-2xs text-faint">[[{seg.ref}]]</p>}
</Part>
)}
{isMetric && (
<MetricPart step={metricStep} entry={entry} chain={chain} runId={runId} seal={seal}
pending={!!runId && !docIssue && (!slot || slot.status === 'loading')}
failed={chainFailed}
resolved={state === 'deterministic'} />
)}
{isInput && !isMetric && (
<Part title={EVIDENCE_TEXT.input} data-ev-input-step="">
<p className="mono">
{inputStep?.field ?? entry?.locator?.field ?? cite?.locator?.field ?? cite?.ref} ={' '}
<span className="tnum">{valueText(inputStep?.value ?? entry?.value ?? cite?.value)}</span>
</p>
<Integrity step={inputStep} seal={seal} />
</Part>
)}
{state === 'deterministic' && !isMetric && !isInput && (
<p className="text-dim">{sourceOf(seg, doc) || detail?.note}</p>
)}
<Part title={EVIDENCE_TEXT.seal} data-ev-seal="">
<SealLine status={verdict.status} label={verdict.label} />
</Part>
{!!doc.violations?.length && (
<button type="button" className="btn btn-xs btn-ghost -ml-1" onClick={onViolations} data-ev-open-violations="">
<ListChecks size={11} aria-hidden /> {EVIDENCE_TEXT.violations}({formatNumber(doc.violations.length)})
</button>
)}
</>
)
}
/** 所在的句子:点开的那一段描底,句子里的数字加粗 */
function Sentence({ unit, active }: { unit: EvidenceUnit; active: string }) {
return (
<p className="leading-relaxed">
{(unit.segments ?? []).filter((s) => s.kind !== 'structural').map((s) => {
const state = segmentState(s)
const on = s.id === active
const number = s.kind === 'number' || s.kind === 'value'
return (
<span key={s.id}
className={clsx(number && 'font-semibold tnum', on && 'rounded-sm px-0.5')}
style={on && state ? { background: EVIDENCE_STATE[state].soft, color: 'var(--text)' } : undefined}
data-ev-here={on ? '' : undefined}>
{s.text}
</span>
)
})}
</p>
)
}
/** 指标步骤:名称、值、口径与版本、原式、代入式(输入标签)、复算 */
function MetricPart({ step, entry, chain, runId, seal, pending, failed, resolved }: {
step?: EvidenceStep
entry?: Record<string, any>
chain: EvidenceStep[]
runId?: string
/** 封存状态:逐项复核里「在不在封存范围内」只在封存完好时单独报 */
seal?: EvidenceSeal
pending: boolean
/** 证据链为什么没有:没有运行 id、接口取不到、接口答的是另一份报告 */
failed: string
/** 片段的引用解析成功了(有出处);解析不了的也画这一节,好说清缺的是哪个指标 */
resolved: boolean
}) {
const name = step?.name ?? entry?.name ?? step?.metric ?? entry?.locator?.metric ?? NONE
const value = step?.value !== undefined ? step.value : entry?.value
const rendered = step?.rendered ?? entry?.rendered
const caliber = step?.caliber ?? entry?.caliber
const version = step?.version ?? entry?.version
const artifact = step?.artifact ?? entry?.artifact
const inputs: EvidenceInput[] = step?.inputs?.length
? step.inputs
: chain.filter((s) => s.step === 'input').map((s) => s as EvidenceInput)
// 口径卡里 rendered 为「—」有两种:value 为 null 是缺输入,不为 null 是有值但按格式显示不出来
const dash = rendered === NONE || entry?.rendered === NONE
const missing = entry?.status === 'missing_input' || (value == null && (dash || !resolved))
const unshowable = !missing && dash && value != null
return (
<Part title={EVIDENCE_TEXT.metric} data-ev-metric="">
<div className="flex flex-wrap items-baseline gap-x-2">
<span className="font-medium">{name}</span>
{resolved && rendered && <span className="mono tnum text-sm" data-ev-value="">{rendered}</span>}
</div>
{(caliber || version || artifact) && (
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-2xs text-dim">
{(caliber || version) && <span>口径卡「{caliber || NONE}」<span className="mono">{version}</span></span>}
{artifact && <span className="mono text-faint" title={`口径卡工件 ${artifact}`}>工件 {shortId(artifact)}</span>}
</div>
)}
<Integrity step={step} seal={seal} />
{missing && <p className="mt-1" style={{ color: 'var(--st-waiting)' }} data-ev-missing="">{EVIDENCE_TEXT.missingValue}</p>}
{unshowable && (
<p className="mt-1" style={{ color: 'var(--st-waiting)' }} data-ev-unshowable="">
{EVIDENCE_TEXT.unshowable(valueText(value))}
</p>
)}
{step ? (
<dl className="mt-2 space-y-1.5">
<div>
<dt className="text-2xs text-faint">{EVIDENCE_TEXT.expression}</dt>
<dd><code className="mono block whitespace-pre-wrap break-all rounded bg-bg px-1.5 py-1 text-2xs" data-ev-expression="">
{step.expression || NONE}
</code></dd>
</div>
<div>
<dt className="text-2xs text-faint">{EVIDENCE_TEXT.substituted}</dt>
<dd>
<code className="mono block whitespace-pre-wrap break-all rounded bg-bg px-1.5 py-1 text-2xs" data-ev-substituted="">
{step.substituted || NONE}
</code>
{!!inputs.length && (
<ul className="mt-1 flex flex-wrap gap-1" aria-label={EVIDENCE_TEXT.inputs}>
{inputs.map((inp, i) => <InputChip key={`${inp.path}-${i}`} input={inp} />)}
</ul>
)}
</dd>
</div>
<div>
<dt className="text-2xs text-faint">{EVIDENCE_TEXT.recompute}</dt>
<dd data-ev-recompute={step.recompute_ok == null ? 'none' : step.recompute_ok ? 'ok' : 'bad'}
style={{ color: step.recompute_ok == null ? 'var(--st-cancelled)'
: step.recompute_ok ? 'var(--st-done)' : 'var(--st-failed)' }}>
{step.recompute_ok == null ? EVIDENCE_TEXT.recomputeNone
: step.recompute_ok ? EVIDENCE_TEXT.recomputeOk : EVIDENCE_TEXT.recomputeBad}
</dd>
</div>
</dl>
) : resolved && (
<p className="mt-1.5 text-2xs text-faint" data-ev-chain={pending ? 'loading' : 'missing'}>
{pending ? EVIDENCE_TEXT.chainPending : failed || (runId ? EVIDENCE_TEXT.chainMissing : EVIDENCE_TEXT.noRun)}
</p>
)}
</Part>
)
}
/**
* 证据接口逐项复核的结果:eid 能重算、工件哈希复验、重新渲染一致、在封存范围内。
* 全过的时候不说(正常态安静);哪一项明确没过就用失败色写出来——这时候这件证据
* 不能信,比「有出处」三个字重要得多。「不在封存范围内」只在封存完好时报:没封存、
* 封存核对失败时后端把每一步都记成 sealed=false,那由封存那一行说,不能说成「事后补进来的」
*/
function Integrity({ step, seal }: { step?: EvidenceStep; seal?: EvidenceSeal }) {
const bad = integrityFailures(step, seal)
if (!bad.length) return null
return <IntegrityList code={bad.join(' ')} items={bad.map((k) => EVIDENCE_TEXT.integrity[k])} />
}
function IntegrityList({ code, items }: { code: string; items: string[] }) {
return (
<ul className="mt-1.5 space-y-0.5 rounded border px-2 py-1" data-ev-integrity={code}
style={{ color: 'var(--st-failed)', borderColor: 'var(--st-failed)', background: 'var(--st-failed-soft)' }}>
{items.map((t) => <li key={t}>{t}</li>)}
</ul>
)
}
/** 「45,678.5 ← vars.kpi.gmv」:值从哪条路径取的。缺的写「—」、标成提醒色 */
function InputChip({ input }: { input: EvidenceInput }) {
const missing = input.status === 'missing' || input.value == null
const from = [input.node_id && `来自节点 ${input.node_id}`, input.via && `(${input.via})`, input.role && ` · ${input.role}`]
.filter(Boolean).join('')
return (
<li className="chip mono tnum max-w-full" data-ev-input={input.path ?? ''}
style={missing ? { color: 'var(--st-waiting)', borderColor: 'var(--st-waiting)' } : { color: 'var(--text)' }}
title={from || undefined}>
<span className="truncate">{valueText(input.value)} ← {input.path ?? NONE}{missing ? '(缺)' : ''}</span>
</li>
)
}
/**
* 封存状态:StatusBadge 的剪影 + 一句话。说什么由 lib/evidence 的 sealVerdict 定(顺序、
* 正文不是封存那份时的失败态都在那里);没有证据的片段封存的只是报告文档本身,
* 不能说成「这个数已封存」
*/
function SealLine({ status, label }: { status: SealStatus; label: string }) {
return (
<p className="flex items-center gap-1.5" data-ev-seal-state={status}>
<StatusBadge status={status} size={12} decorative animate={false} />
<span className={status === 'idle' ? 'text-dim' : undefined}>{label}</span>
</p>
)
}
const CODE_LABEL: Record<string, string> = {
uncited_number: '裸数字',
unresolved_ref: '引用解析不了',
}
/** 违规清单:报告撰写节点核对出来的全部问题,画得出线的能定位,画不出的说清在哪 */
function ViolationList({ doc, onLocate }: { doc: EvidenceDocData; onLocate: (segId: string) => void }) {
const list: EvidenceViolation[] = doc.violations ?? []
if (!list.length) return <p className="text-dim">{EVIDENCE_TEXT.allCited(docNumbers(doc))}</p>
return (
<>
<p className="text-2xs text-faint">{EVIDENCE_TEXT.violationsHint}</p>
<ul className="space-y-2" data-ev-violations="">
{list.map((v, i) => {
const seg = locatable(doc, v)
return (
<li key={i} className="rounded border px-2 py-1.5" data-ev-violation={v.code}
data-ev-locatable={seg ? 'yes' : 'no'}>
<div className="flex items-center gap-2">
<span className="mono font-semibold">{v.text ?? (v.ref ? `[[${v.ref}]]` : NONE)}</span>
<span className="chip" style={{ color: 'var(--st-waiting)' }}>{CODE_LABEL[v.code] ?? '文档核对没通过'}</span>
<span className="flex-1" />
{seg && (
<button type="button" className="btn btn-xs" onClick={() => onLocate(seg.id)}>定位</button>
)}
</div>
{v.message && <p className="mt-1 text-dim">{v.message}</p>}
{v.context && <p className="mono mt-0.5 text-2xs text-faint [overflow-wrap:anywhere]">「{v.context.trim()}」</p>}
{!seg && (
<p className="mt-0.5 text-2xs" style={{ color: 'var(--st-waiting)' }}>
{v.segment ? EVIDENCE_TEXT.structural : EVIDENCE_TEXT.noSegment}
</p>
)}
</li>
)
})}
</ul>
</>
)
}
const docNumbers = (doc: EvidenceDocData): number => doc.stats?.numbers ?? 0
+368 -89
View File
@@ -1,7 +1,10 @@
import { createContext, Fragment, useContext, useState, type ReactNode } from 'react'
import {
createContext, Fragment, useContext, useMemo, useState, type HTMLAttributes, type ReactNode,
} from 'react'
import { Check, Copy } from 'lucide-react'
import clsx from 'clsx'
import { toast } from '../components/ui'
import { codePointIndex } from '../lib/evidence'
/**
* 模型输出的 Markdown 渲染。
@@ -22,6 +25,9 @@ import { toast } from '../components/ui'
*
* 全程构造 React 元素,一处 dangerouslySetInnerHTML 都没有。模型输出是不
* 可信内容,走 innerHTML 就等于给自己开了个 XSS 口子。
*
* 块的外观(BlockView)单独导出:报告撰写节点的文档(run/EvidenceDoc)是后端切好的
* 块和片段,不再解析 Markdown,但长得必须和这里一模一样。
*/
export function Markdown({ text, dense, marks }: {
text: string
@@ -29,11 +35,12 @@ export function Markdown({ text, dense, marks }: {
/** 要在正文里标出来的词:出具时无法回指的数字、能回指到口径卡的数字 */
marks?: MarkSpec[]
}) {
const ctx = useMemo(() => prepareMarks(text ?? '', marks), [text, marks])
if (!text?.trim()) return null
return (
<MarksContext.Provider value={marks?.length ? marks : null}>
<MarksContext.Provider value={ctx}>
<div className={clsx('space-y-2 leading-relaxed', dense ? 'text-[11.5px]' : 'text-sm')}>
{parseBlocks(text).map((b, i) => <Block key={i} block={b} dense={dense} />)}
{parseBlocks(text).map((b, i) => <MdBlock key={i} block={b} dense={dense} />)}
</div>
</MarksContext.Provider>
)
@@ -45,35 +52,109 @@ export function Markdown({ text, dense, marks }: {
* 出具校验认得出「哪些数字回指不到口径卡」,但以前只在横幅里列一串孤零零的
* token——读的人得自己回正文里找「6」是哪句话里的那个 6。直接在原句上画出来,
* 悬停说明原因,证据才落到读的地方。
*
* 带 start / end(后端 trace_numbers 给的码点偏移)的只标那一处:按字符串标的话,
* 同一个数出现几次就画几处,日期「2026-09-15」里的 15 也会被当成回指不上的 15。
* 老运行没有位置,位置和这段文字对不上(叙述模板在字段外面加了字)时,也退回按字符串标
*/
export interface MarkSpec {
token: string
title: string
tone: 'warn' | 'ok'
/** ambiguous:回指上了,但同一个值对得上好几个指标,出处不唯一 */
tone: 'warn' | 'ok' | 'ambiguous'
/** 在原文里的码点偏移 [start, end) */
start?: number
end?: number
}
const MarksContext = createContext<MarkSpec[] | null>(null)
interface MarksCtx {
/** 按字符串认的 */
loose: MarkSpec[] | null
/** 按位置认的:UTF-16 起点 → 终点和说明 */
at: Map<number, { end: number; spec: MarkSpec }> | null
}
const MarksContext = createContext<MarksCtx | null>(null)
/** 位置换成 UTF-16 下标并逐个核对:切出来的字就是 token 才按位置标,否则交给字符串匹配 */
function prepareMarks(text: string, marks: MarkSpec[] | undefined): MarksCtx | null {
if (!marks?.length) return null
const loose: MarkSpec[] = []
const at = new Map<number, { end: number; spec: MarkSpec }>()
// 换行归一会挪动偏移:带 \r 的文字位置一律不认
const toUtf16 = text.includes('\r') ? null : codePointIndex(text)
for (const m of marks) {
if (toUtf16 && typeof m.start === 'number' && typeof m.end === 'number' && m.end > m.start) {
const s = toUtf16(m.start)
const e = toUtf16(m.end)
if (s >= 0 && e > s && text.slice(s, e) === m.token) {
at.set(s, { end: e, spec: m })
continue
}
}
loose.push(m)
}
return { loose: loose.length ? loose : null, at: at.size ? at : null }
}
/**
* 一段文字在原文里的位置:连续的给起点,拼接过的(引用的多行、列表的续行)给逐字的
* 下标表。只有按位置标记时用得上,其余时候跟着传一下,不做任何事
*/
type At = number | number[]
const offsetAt = (at: At | undefined, i: number): number =>
at == null ? -1 : typeof at === 'number' ? at + i : at[i] ?? -1
const shiftAt = (at: At | undefined, i: number): At | undefined =>
at == null ? undefined : typeof at === 'number' ? at + i : at.slice(i)
function markSpan(spec: MarkSpec, text: string, key: string): ReactNode {
const color = spec.tone === 'ok' ? 'var(--st-done)' : 'var(--st-waiting)'
return (
<span key={key} title={spec.title}
className="cursor-help underline decoration-dotted underline-offset-[3px]"
style={{ textDecorationColor: color }}
data-mark={spec.tone}>
{text}
</span>
)
}
/** 纯文本段里的标记词包一层。数字按词边界认:「6」不能命中「94.26」里的那个 6 */
function markText(text: string, marks: MarkSpec[] | null, keyBase: number): ReactNode[] {
if (!marks || !text) return [text]
const alts = [...marks].sort((a, b) => b.token.length - a.token.length)
.map((m) => m.token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
const re = new RegExp(`(?<![\\d.])(?:${alts.join('|')})(?![\\d]|\\.\\d)`, 'g')
function markText(text: string, ctx: MarksCtx | null, keyBase: number, at?: At): ReactNode[] {
if (!ctx || !text) return [text]
const hits: { start: number; end: number; spec: MarkSpec }[] = []
// 按位置:这一段里每个字在原文里的下标,撞上某个标记的起点、并且整段都落在这一段里
if (ctx.at && at != null) {
for (let i = 0; i < text.length; i++) {
const hit = ctx.at.get(offsetAt(at, i))
if (!hit) continue
// 末字也得正好落在标记的末尾:拼接过的文字(引用的多行)里,字面相同不等于位置相同
const len = hit.spec.token.length
if (text.slice(i, i + len) === hit.spec.token && offsetAt(at, i + len - 1) === hit.end - 1) {
hits.push({ start: i, end: i + len, spec: hit.spec })
i += len - 1
}
}
}
if (ctx.loose) {
const alts = [...ctx.loose].sort((a, b) => b.token.length - a.token.length)
.map((m) => m.token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
const re = new RegExp(`(?<![\\d.])(?:${alts.join('|')})(?![\\d]|\\.\\d)`, 'g')
for (let m = re.exec(text); m; m = re.exec(text)) {
const start = m.index
const end = start + m[0].length
if (hits.some((h) => start < h.end && h.start < end)) continue
hits.push({ start, end, spec: ctx.loose.find((x) => x.token === m![0])! })
}
}
if (!hits.length) return [text]
hits.sort((a, b) => a.start - b.start)
const out: ReactNode[] = []
let last = 0
for (let m = re.exec(text); m; m = re.exec(text)) {
if (m.index > last) out.push(text.slice(last, m.index))
const spec = marks.find((x) => x.token === m![0])!
out.push(
<span key={`mk${keyBase}-${m.index}`} title={spec.title}
className="cursor-help underline decoration-dotted underline-offset-[3px]"
style={{ textDecorationColor: spec.tone === 'warn' ? 'var(--st-waiting)' : 'var(--st-done)' }}
data-mark={spec.tone}>
{m[0]}
</span>,
)
last = m.index + m[0].length
for (const h of hits) {
if (h.start > last) out.push(text.slice(last, h.start))
out.push(markSpan(h.spec, text.slice(h.start, h.end), `mk${keyBase}-${h.start}`))
last = h.end
}
if (last < text.length) out.push(text.slice(last))
return out
@@ -83,14 +164,17 @@ function markText(text: string, marks: MarkSpec[] | null, keyBase: number): Reac
// 块级
// -------------------------------------------------------------------------
/** 带着在原文里位置的一段文字(位置只给按位置标记用) */
interface Src { text: string; at: At }
type Block =
| { kind: 'p'; text: string }
| { kind: 'h'; level: number; text: string }
| { kind: 'p'; text: string; at: At }
| { kind: 'h'; level: number; text: string; at: At }
| { kind: 'code'; lang: string; code: string }
| { kind: 'quote'; text: string }
| { kind: 'quote'; text: string; at: At }
| { kind: 'hr' }
| { kind: 'list'; ordered: boolean; start?: number; items: { text: string; depth: number }[] }
| { kind: 'table'; head: string[]; rows: string[][] }
| { kind: 'list'; ordered: boolean; start?: number; items: { text: string; at: At; depth: number }[] }
| { kind: 'table'; head: Src[]; rows: Src[][] }
const FENCE = /^\s*```(\w*)\s*$/
const HEADING = /^(#{1,6})\s+(.*)$/
@@ -101,8 +185,23 @@ const QUOTE = /^\s*>\s?(.*)$/
const TABLE_ROW = /^\s*\|(.+)\|\s*$/
const TABLE_SEP = /^\s*\|[\s:|-]+\|\s*$/
/** 逐字下标表:几段不相连的文字拼成一段时,每个字记着它原来在哪 */
function joinAt(parts: { text: string; at: number }[], sep: string): number[] {
const out: number[] = []
parts.forEach((p, k) => {
if (k > 0) for (let j = 0; j < sep.length; j++) out.push(-1)
for (let j = 0; j < p.text.length; j++) out.push(p.at + j)
})
return out
}
function parseBlocks(text: string): Block[] {
const lines = text.replace(/\r\n?/g, '\n').split('\n')
// 每一行在原文里从哪开始
const starts: number[] = []
for (let i = 0, pos = 0; i < lines.length; i++) { starts.push(pos); pos += lines[i].length + 1 }
/** 这一行里 content 这段(它总是顶到行尾)的起点 */
const tail = (i: number, content: string) => starts[i] + lines[i].length - content.length
const out: Block[] = []
let i = 0
@@ -127,29 +226,30 @@ function parseBlocks(text: string): Block[] {
const heading = line.match(HEADING)
if (heading) {
out.push({ kind: 'h', level: heading[1].length, text: heading[2] })
out.push({ kind: 'h', level: heading[1].length, text: heading[2], at: tail(i, heading[2]) })
i += 1
continue
}
// 表格:一行 | ... | 后面紧跟一行分隔行,两者都有才算
if (TABLE_ROW.test(line) && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1])) {
const head = splitRow(line)
const rows: string[][] = []
const head = splitRow(line, starts[i])
const rows: Src[][] = []
i += 2
while (i < lines.length && TABLE_ROW.test(lines[i])) { rows.push(splitRow(lines[i])); i += 1 }
while (i < lines.length && TABLE_ROW.test(lines[i])) { rows.push(splitRow(lines[i], starts[i])); i += 1 }
out.push({ kind: 'table', head, rows })
continue
}
const quote = line.match(QUOTE)
if (quote) {
const body = [quote[1]]
const body = [{ text: quote[1], at: tail(i, quote[1]) }]
i += 1
while (i < lines.length && QUOTE.test(lines[i])) {
body.push(lines[i].match(QUOTE)![1]); i += 1
const q = lines[i].match(QUOTE)![1]
body.push({ text: q, at: tail(i, q) }); i += 1
}
out.push({ kind: 'quote', text: body.join('\n') })
out.push({ kind: 'quote', text: body.map((b) => b.text).join('\n'), at: joinAt(body, '\n') })
continue
}
@@ -159,34 +259,44 @@ function parseBlocks(text: string): Block[] {
// 一段连续的列表算一块。有序和无序混排时按第一条定性——模型不常这么写,
// 真遇上了也比拆成两块好看
const isOrdered = !!ordered
const items: { text: string; depth: number }[] = []
const items: { parts: { text: string; at: number }[]; depth: number }[] = []
while (i < lines.length) {
const b = lines[i].match(BULLET)
const o = b ? null : lines[i].match(ORDERED)
if (b || o) {
const indent = (b ?? o)![1]
items.push({ text: b ? b[2] : o![3], depth: Math.floor(indent.replace(/\t/g, ' ').length / 2) })
const body = b ? b[2] : o![3]
items.push({ parts: [{ text: body, at: tail(i, body) }], depth: Math.floor(indent.replace(/\t/g, ' ').length / 2) })
i += 1
} else if (lines[i].trim() && !isBlockStart(lines[i]) && items.length) {
// 悬挂缩进的续行接到上一条上,不要另起一段
items[items.length - 1].text += '\n' + lines[i].trim()
const t = lines[i].trim()
items[items.length - 1].parts.push({ text: t, at: starts[i] + lines[i].indexOf(t) })
i += 1
} else break
}
// 模型常把有序列表写成被空行隔开的几段,每段各自一块。不记起始序号的话
// 三段都从 1 开始,「1. 1. 1.」读起来像三条并列的第一条
out.push({ kind: 'list', ordered: isOrdered, items,
...(ordered ? { start: Number(ordered[2]) } : {}) })
out.push({
kind: 'list', ordered: isOrdered,
items: items.map((it) => ({
text: it.parts.map((p) => p.text).join('\n'),
at: it.parts.length === 1 ? it.parts[0].at : joinAt(it.parts, '\n'),
depth: it.depth,
})),
...(ordered ? { start: Number(ordered[2]) } : {}),
})
continue
}
// 普通段落:一直吃到空行或下一个块开头
// 普通段落:一直吃到空行或下一个块开头。行是原样接起来的,位置连续
const para = [line]
const at = starts[i]
i += 1
while (i < lines.length && lines[i].trim() && !isBlockStart(lines[i])) {
para.push(lines[i]); i += 1
}
out.push({ kind: 'p', text: para.join('\n') })
out.push({ kind: 'p', text: para.join('\n'), at })
}
return out
}
@@ -196,79 +306,142 @@ function isBlockStart(line: string): boolean {
|| BULLET.test(line) || ORDERED.test(line) || QUOTE.test(line) || TABLE_ROW.test(line)
}
function splitRow(line: string): string[] {
return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim())
/** 表格的一行拆成格:去掉首尾竖线、每格去掉两边空白。记下每格去空白之后从哪开始 */
function splitRow(line: string, lineStart: number): Src[] {
const lead = line.length - line.trimStart().length
let body = line.trim()
let base = lineStart + lead
if (body.startsWith('|')) { body = body.slice(1); base += 1 }
if (body.endsWith('|')) body = body.slice(0, -1)
const out: Src[] = []
let pos = 0
for (const raw of body.split('|')) {
out.push({ text: raw.trim(), at: base + pos + (raw.length - raw.trimStart().length) })
pos += raw.length + 1
}
return out
}
function Block({ block, dense }: { block: Block; dense?: boolean }) {
/** 解析出来的块交给 BlockView:每段文字按行内语法渲染 */
function MdBlock({ block, dense }: { block: Block; dense?: boolean }) {
switch (block.kind) {
case 'h': return <BlockView dense={dense} shape={{ kind: 'h', level: block.level, body: <Inline text={block.text} at={block.at} /> }} />
case 'hr': return <BlockView dense={dense} shape={{ kind: 'hr' }} />
case 'code': return <BlockView dense={dense} shape={{ kind: 'code', lang: block.lang, code: block.code }} />
case 'quote': return <BlockView dense={dense} shape={{ kind: 'quote', body: <Inline text={block.text} at={block.at} /> }} />
case 'list':
return (
<BlockView dense={dense} shape={{
kind: 'list', ordered: block.ordered, start: block.start,
items: block.items.map((it) => ({ depth: it.depth, body: <Inline text={it.text} at={it.at} /> })),
}} />
)
case 'table': {
const head = block.head.map((h) => h.text)
const rows = block.rows.map((r) => r.map((c) => c.text))
return (
<BlockView dense={dense} shape={{
kind: 'table',
head: block.head.map((h, i) => <Inline key={i} text={h.text} at={h.at} />),
// 用表头的列数对齐:模型偶尔会少写一格,少的补空,多的截掉——否则整张表会错位
rows: block.rows.map((row) => block.head.map((_, j) => (
row[j] ? <Inline text={row[j].text} at={row[j].at} /> : null))),
numeric: numericColumns(head, rows),
csv: () => toCsv(head, rows),
}} />
)
}
default:
return <BlockView dense={dense} shape={{ kind: 'p', body: <Inline text={block.text} at={block.at} /> }} />
}
}
/**
* 一个块的外观,内容由调用方给。Markdown 给的是按行内语法渲染的文字,EvidenceDoc
* 给的是后端切好的片段——两处长得一模一样,改外观只改这里
*/
export type BlockShape =
| { kind: 'p'; body: ReactNode }
| { kind: 'h'; level: number; body: ReactNode }
| { kind: 'code'; lang: ReactNode; code: string; body?: ReactNode }
| { kind: 'quote'; body: ReactNode }
| { kind: 'hr' }
| { kind: 'list'; ordered: boolean; start?: number; items: { body: ReactNode; depth: number; key?: string }[]
/** 序号按位数留宽(「100.」比 1rem 宽)。普通答案不开,保持原样 */
fitMarkers?: boolean }
| { kind: 'table'; head: ReactNode[]; rows: ReactNode[][]; numeric: boolean[]; csv: () => string }
/** 块最外层那个元素上额外要挂的属性(EvidenceDoc 挂 data-block 和 content-visibility) */
type RootProps = HTMLAttributes<HTMLElement> & Record<`data-${string}`, string | undefined>
export function BlockView({ shape, dense, root }: { shape: BlockShape; dense?: boolean; root?: RootProps }) {
const { className: rootClass, ...rest } = root ?? {}
switch (shape.kind) {
case 'h': {
// 侧栏只有 360px 宽,一级标题按 h1 的字号会大得不像话。
// 按层级递减但整体压扁,保住层次感就够了
const size = dense
? ['text-[13px]', 'text-[12px]', 'text-[11.5px]'][Math.min(block.level, 3) - 1]
: ['text-base', 'text-sm', 'text-sm'][Math.min(block.level, 3) - 1]
? ['text-[13px]', 'text-[12px]', 'text-[11.5px]'][Math.min(shape.level, 3) - 1]
: ['text-base', 'text-sm', 'text-sm'][Math.min(shape.level, 3) - 1]
return (
<div className={clsx('mt-3 font-semibold first:mt-0', size)}>
<Inline text={block.text} />
<div {...rest} className={clsx('mt-3 font-semibold first:mt-0', size, rootClass)}>
{shape.body}
</div>
)
}
case 'hr':
return <hr className="my-2 border-t" />
return <hr {...rest} className={clsx('my-2 border-t', rootClass)} />
case 'code':
return <CodeBlock lang={block.lang} code={block.code} dense={dense} />
return <CodeBlock lang={shape.lang} code={shape.code} dense={dense} root={root}>{shape.body}</CodeBlock>
case 'quote':
return (
<blockquote className="border-l-2 pl-2.5 text-dim" style={{ borderColor: 'var(--accent)' }}>
<Inline text={block.text} />
<blockquote {...rest} className={clsx('border-l-2 pl-2.5 text-dim', rootClass)} style={{ borderColor: 'var(--accent)', ...rest.style }}>
{shape.body}
</blockquote>
)
case 'list': {
const Tag = block.ordered ? 'ol' : 'ul'
const Tag = shape.ordered ? 'ol' : 'ul'
// 缩进用 padding 不用 margin:列表符号画在这一段里,块上加了 content-visibility
// (长报告)时,画在 margin 里的符号会被裁掉。序号到了两三位(「100.」)时符号比
// 1rem 宽,fitMarkers 时按位数加宽,不然序号伸到块外面、被裁掉
const digits = shape.ordered && shape.fitMarkers ? String((shape.start ?? 1) + shape.items.length - 1).length : 1
return (
<Tag start={block.ordered && block.start && block.start !== 1 ? block.start : undefined}
className={clsx('space-y-1', block.ordered ? 'list-decimal' : 'list-disc',
'ml-4 marker:text-faint')}>
{block.items.map((it, i) => (
<li key={i} style={{ marginLeft: it.depth * 14 }}>
<Inline text={it.text} />
<Tag {...rest} start={shape.ordered && shape.start && shape.start !== 1 ? shape.start : undefined}
className={clsx('space-y-1', shape.ordered ? 'list-decimal' : 'list-disc',
'pl-4 marker:text-faint', rootClass)}
style={digits > 1 ? { paddingLeft: `calc(1rem + ${(digits - 1) * 0.6}em)`, ...rest.style } : rest.style}>
{shape.items.map((it, i) => (
<li key={it.key ?? i} style={{ marginLeft: it.depth * 14 }}>
{it.body}
</li>
))}
</Tag>
)
}
case 'table': {
case 'table':
// 数值列右对齐、等宽数字:一列金额左对齐时小数点对不上,没法一眼比大小
const numeric = block.head.map((h, j) => {
if (CODE_COLUMN.test(h.replace(/[*`]/g, '').trim())) return false
const cells = block.rows.map((r) => (r[j] ?? '').replace(/[*`]/g, '').trim()).filter(Boolean)
return cells.length > 0 && cells.every((c) => NUMERIC_CELL.test(c) && !LEADING_ZERO.test(c))
})
return (
<div className="group/table relative overflow-x-auto rounded-lg border">
<CopyChip label="复制为 CSV" text={() => toCsv(block.head, block.rows)}
<div {...rest} className={clsx('group/table relative overflow-x-auto rounded-lg border', rootClass)}>
<CopyChip label="复制为 CSV" text={shape.csv}
className="absolute right-1 top-1 opacity-0 group-hover/table:opacity-100 focus-visible:opacity-100" />
<table className={clsx('w-full', dense ? 'text-[10.5px]' : 'text-xs')}>
<thead>
<tr className="border-b bg-elev">
{block.head.map((h, i) => (
{shape.head.map((h, i) => (
<th key={i} className={clsx('px-2 py-1 font-medium text-dim',
numeric[i] ? 'text-right' : 'text-left')}>
<Inline text={h} />
shape.numeric[i] ? 'text-right' : 'text-left')}>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{block.rows.map((row, i) => (
{shape.rows.map((row, i) => (
<tr key={i} className="border-b last:border-0">
{/* 用表头的列数对齐:模型偶尔会少写一格,少的补空,
多的截掉——否则整张表会错位 */}
{block.head.map((_, j) => (
{row.map((cell, j) => (
<td key={j} className={clsx('px-2 py-1 align-top text-dim',
numeric[j] && 'tnum text-right')}>
<Inline text={row[j] ?? ''} />
shape.numeric[j] && 'tnum text-right')}>
{cell}
</td>
))}
</tr>
@@ -277,12 +450,20 @@ function Block({ block, dense }: { block: Block; dense?: boolean }) {
</table>
</div>
)
}
default:
return <p className="whitespace-pre-wrap"><Inline text={block.text} /></p>
return <p {...rest} className={clsx('whitespace-pre-wrap', rootClass)}>{shape.body}</p>
}
}
/** 哪几列是数值列:列名不像编号 / 分组,非空的格全是数 */
export function numericColumns(head: string[], rows: string[][]): boolean[] {
return head.map((h, j) => {
if (CODE_COLUMN.test(h.replace(/[*`]/g, '').trim())) return false
const cells = rows.map((r) => (r[j] ?? '').replace(/[*`]/g, '').trim()).filter(Boolean)
return cells.length > 0 && cells.every((c) => NUMERIC_CELL.test(c) && !LEADING_ZERO.test(c))
})
}
// -------------------------------------------------------------------------
// 行内
// -------------------------------------------------------------------------
@@ -299,7 +480,12 @@ const INLINE = new RegExp([
'~~([^~]+?)~~', // ~~strike~~
].join('|'))
function Inline({ text, depth = 0 }: { text: string; depth?: number }): ReactNode {
/**
* 行内语法:代码、链接、粗体、斜体、删除线。EvidenceDoc 的文字片段也走它——后端说
* 不含标记的粗体、`code`、链接原样留在文字片段里,由前端按行内 Markdown 渲染
*/
export function Inline({ text, depth = 0, at }: { text: string; depth?: number; at?: At }): ReactNode {
const marks = useContext(MarksContext)
if (!text) return null
const out: ReactNode[] = []
let last = 0
@@ -308,18 +494,17 @@ function Inline({ text, depth = 0 }: { text: string; depth?: number }): ReactNod
// 里可以套行内代码),不每次重置就会从上一层留下的位置接着扫
const re = new RegExp(INLINE.source, 'g')
const marks = useContext(MarksContext)
const plain = (t: string) => out.push(...markText(t, marks, key++))
const plain = (t: string, from: number) => out.push(...markText(t, marks, key++, shiftAt(at, from)))
for (let m = re.exec(text); m; m = re.exec(text)) {
if (m.index > last) plain(text.slice(last, m.index))
const [, , code, linkText, href, bold1, bold2, italic, strike] = m
if (m.index > last) plain(text.slice(last, m.index), last)
const [whole, , code, linkText, href, bold1, bold2, italic, strike] = m
// 强调的内容要再解析一层。模型很爱写 **`table_name`**(粗体里套代码),
// 而粗体在扫描顺序上先命中,不递归的话那对反引号就原样显示出来了。
// 深度有限:每层的文本都严格更短,且这里也卡了三层
const sub = (t: string) =>
depth < 3 ? <Inline text={t} depth={depth + 1} /> : t
depth < 3 ? <Inline text={t} depth={depth + 1} at={shiftAt(at, m!.index + whole.indexOf(t))} /> : t
if (code !== undefined) {
// 代码内部不再解析——这正是代码的含义
@@ -335,12 +520,101 @@ function Inline({ text, depth = 0 }: { text: string; depth?: number }): ReactNod
} else if (strike !== undefined) {
out.push(<s key={key++} className="text-faint">{sub(strike)}</s>)
}
last = m.index + m[0].length
last = m.index + whole.length
}
if (last < text.length) plain(text.slice(last))
if (last < text.length) plain(text.slice(last), last)
return <>{out.map((n, i) => <Fragment key={i}>{n}</Fragment>)}</>
}
/** 行内样式位。EvidenceDoc 的片段按它把一段文字切成几截、分别包上 code / strong / em */
export const INLINE_BIT = { code: 1, bold: 2, em: 4, strike: 8, link: 16 } as const
export interface InlineStyles {
/** 语法字符(反引号、星号、链接的方括号和网址):不显示 */
hide: Uint8Array
/** 每个字的样式位 */
style: Uint8Array
/** 链接文字所在的字 → 网址。只收 http/https/mailto,别的协议当纯文本,同 Link */
href: Map<number, string>
}
/**
* 一段文字的行内样式,逐字给出。和 Inline 用同一个 INLINE 语法、同样最多套三层。
*
* 为什么不直接用 Inline:报告文档里一句话已经被后端切成了好几个片段,行内语法可能
* 跨片段——`limit 100` 里的 100 是一个裸数字片段,两边的反引号在别的片段里。对整句
* 算一次样式、每个片段取自己那一截,代码就还是代码,数字还能单独点
*/
export function inlineStyles(text: string): InlineStyles {
const hide = new Uint8Array(text.length)
const style = new Uint8Array(text.length)
const href = new Map<number, string>()
const walk = (from: number, to: number, inherited: number, depth: number) => {
const part = text.slice(from, to)
const re = new RegExp(INLINE.source, 'g')
let last = 0
for (let m = re.exec(part); m; m = re.exec(part)) {
for (let i = last; i < m.index; i++) style[from + i] = inherited
const [whole, ticks, code, linkText, url, bold1, bold2, italic, strike] = m
const base = from + m.index
const inner = code ?? linkText ?? bold1 ?? bold2 ?? italic ?? strike ?? ''
// 内容紧跟在开头的定界符后面:反引号按实际个数,其余 indexOf 找到的就是第一处
const off = code !== undefined ? ticks.length : whole.indexOf(inner)
for (let i = 0; i < whole.length; i++) hide[base + i] = 1
for (let i = 0; i < inner.length; i++) hide[base + off + i] = 0
const safe = linkText !== undefined && /^(https?:|mailto:)/i.test(url.trim())
const bit = code !== undefined ? INLINE_BIT.code
: linkText !== undefined ? (safe ? INLINE_BIT.link : 0)
: bold1 !== undefined || bold2 !== undefined ? INLINE_BIT.bold
: italic !== undefined ? INLINE_BIT.em : INLINE_BIT.strike
if (code !== undefined || linkText !== undefined || depth >= 3) {
for (let i = 0; i < inner.length; i++) {
style[base + off + i] = inherited | bit
if (safe) href.set(base + off + i, url)
}
} else {
walk(base + off, base + off + inner.length, inherited | bit, depth + 1)
}
last = m.index + whole.length
}
for (let i = last; i < part.length; i++) style[from + i] = inherited
}
walk(0, text.length, 0, 0)
return { hide, style, href }
}
/**
* 按 inlineStyles 渲染 [from, to) 这一截。links=false 时链接只画样子不给 <a>:片段本身
* 是个 button,button 里不能再套可交互的元素
*/
export function StyledSlice({ text, styles, from, to, links = true }: {
text: string; styles: InlineStyles; from: number; to: number; links?: boolean
}): ReactNode {
const out: ReactNode[] = []
let i = from
while (i < to) {
if (styles.hide[i]) { i += 1; continue }
const st = styles.style[i]
const href = styles.href.get(i)
let j = i + 1
while (j < to && !styles.hide[j] && styles.style[j] === st && styles.href.get(j) === href) j += 1
let node: ReactNode = text.slice(i, j)
if (st & INLINE_BIT.code) node = <code className="mono rounded bg-bg px-1 py-px text-[0.92em]">{node}</code>
if (st & INLINE_BIT.link) {
node = links && href
? <a href={href} target="_blank" rel="noopener noreferrer" className="underline decoration-dotted underline-offset-2"
style={{ color: 'var(--accent)' }}>{node}</a>
: <span style={{ color: 'var(--accent)' }}>{node}</span>
}
if (st & INLINE_BIT.strike) node = <s className="text-faint">{node}</s>
if (st & INLINE_BIT.em) node = <em>{node}</em>
if (st & INLINE_BIT.bold) node = <strong className="font-semibold">{node}</strong>
out.push(<Fragment key={i}>{node}</Fragment>)
i = j
}
return <>{out}</>
}
/**
* 链接。
*
@@ -390,16 +664,21 @@ function toCsv(head: string[], rows: string[][]): string {
* 代码块带语言标签和复制按钮。模型给的 SQL、脚本十有八九要被拿去别处跑,
* 手动框选容易漏掉首尾一行
*/
function CodeBlock({ lang, code, dense }: { lang: string; code: string; dense?: boolean }) {
function CodeBlock({ lang, code, dense, root, children }: {
lang: ReactNode; code: string; dense?: boolean; root?: RootProps
/** 要显示的内容,不给就是 code 原文(EvidenceDoc 给的是片段,代码里的裸数字要画线) */
children?: ReactNode
}) {
const { className: rootClass, ...rest } = root ?? {}
return (
<div className="group/code relative overflow-hidden rounded-lg border bg-bg">
<div {...rest} className={clsx('group/code relative overflow-hidden rounded-lg border bg-bg', rootClass)}>
<div className="flex items-center gap-2 border-b px-2.5 py-1 text-2xs text-faint">
<span className="mono">{lang || '代码'}</span>
<span className="flex-1" />
<CopyChip label="复制" text={() => code} />
</div>
<pre className={clsx('mono overflow-x-auto px-2.5 py-2 leading-relaxed', dense ? 'text-[10.5px]' : 'text-xs')}>
<code>{code}</code>
<code>{children ?? code}</code>
</pre>
</div>
)
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+37 -1
View File
@@ -1,7 +1,8 @@
import type { RunEvent, TeamMember, TeamRound, TeamRun, ToolChange } from '../types'
import type { NodeState, RunPhase } from './trace'
import { formatDuration, formatNumber } from '../lib/format'
import { TYPE_LABEL, issuanceLabel, nodeTypeLabel } from '../lib/terms'
import { TYPE_LABEL, evidenceTally, issuanceLabel, nodeTypeLabel } from '../lib/terms'
import { statsTally } from '../lib/evidence'
// 泳道数据画布也要用(supervisor 节点要展开成协作矩阵),所以类型放在
// types.ts 里;这里再导出一遍,老引用不用改
@@ -675,6 +676,16 @@ function explainLog(code: string | undefined, message: string): Pick<Step, 'titl
fix: 'canvas',
}
}
case 'report_repair': {
// 「报告里有 3 处没通过核对(「12」「m:nope」),已要求写作者重写(第 1 次)」。没通过的
// 不只是裸数字,还有解析不了的引用(m:nope),标题不能只说「没写引用」
const n = message.match(/报告里有\s*(\d+)\s*处/)?.[1]
const round = message.match(/第\s*(\d+)\s*次/)?.[1]
return {
title: `报告${n ? `有 ${n} 处` : ''}没通过核对,已让模型按清单重写${round ? `(第 ${round} 次)` : ''}`,
sub: message.match(/没通过核对((.+?))/)?.[1],
}
}
case 'repair_invented': {
// 「第 1 次修复作废:修复时出现了原文没有的值:total_count=0」
const values = message.match(/原文没有的值[::]\s*(.+)$/)?.[1]?.trim()
@@ -1574,6 +1585,31 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
break
}
case 'report.checked': {
// 报告撰写节点核对完自己写的报告:几个数字有出处、哪些地方没有证据。说法和出具
// 横幅那一行同一种(evidenceTally)。载荷缺字段(别的版本的后端)就只说核对过
// 前半句只数数字(无证据 = 总数 − 有出处,算得平),不是数字的解析不了的引用另起一句
const counts = statsTally(d.stats && typeof d.stats === 'object' ? d.stats : null)
const none = counts ? counts.none + counts.other : 0
const violations: any[] = Array.isArray(d.violations) ? d.violations : []
const repairs = num(d.repairs) ?? 0
const tally = counts ? evidenceTally(counts.cited, counts.total, counts.other) : ''
const listed = violations.slice(0, 8)
.map((v) => `· ${String(v?.message ?? v?.text ?? v?.code ?? '')}`).filter((x) => x.length > 2)
const more = violations.length > listed.length ? [`…另有 ${violations.length - listed.length} 处`] : []
// on_violation=fail 且重写后仍不过:节点接着就失败,这一步不能画成完成。老后端没有 failed 字段,照旧
const failed = d.failed === true
push({
id: `rc-${seq}`, seq, kind: 'issuance', nodeId, status: failed ? 'failed' : 'done', code: 'report_checked',
level: failed ? 'error' : none || violations.length ? 'warn' : 'info',
title: tally ? `核对报告:${tally}` : '核对报告',
...(listed.length ? { detail: [...listed, ...more].join('\n') } : {}),
...(repairs ? { meta: `重写 ${repairs} 次` } : {}),
...(typeof d.doc_artifact === 'string' && d.doc_artifact ? { artifact: d.doc_artifact } : {}),
}, nodeId)
break
}
case 'caliber.upgrade':
out.push({
id: `cu-${seq}`, seq, kind: 'note', level: 'warn', status: 'done',