import {
useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
} from 'react'
import { createPortal } from 'react-dom'
import { ArrowLeft, CornerDownRight, ListChecks, ShieldCheck, X } from 'lucide-react'
import clsx from 'clsx'
import { StatusBadge, isComposing } from '../components/ui'
import {
EVIDENCE_KIND_STYLE, EVIDENCE_STATE, caliberSourceText, caliberUpgradeText, closestNames, docForeign, entitySources,
evidenceTrace, evidenceValue as valueText, graphDoc, inputSource, integrityFailures, locatable, locatorText, notableInput,
queryOf, queryWindow, quoteWhere, quoteWindow, reasonOf, sealVerdict, segName, segmentKind, segmentState, sourceOf,
type SealStatus, type SourceTone,
} from '../lib/evidence'
import { formatDateTime, formatNumber, NONE, shortId } from '../lib/format'
import { EVIDENCE_TEXT } from '../lib/terms'
import { useCatalog } from '../store/catalog'
import { segmentKey, useEvidence } from '../store/evidence'
import type {
EvidenceDocData, EvidenceInput, EvidenceQuoteSource, EvidenceSeal, EvidenceSegment, EvidenceStep, EvidenceUnit,
EvidenceViolation,
} from '../types'
import { ArtifactViewer, ResultTable } from './AssistantStream'
import { useEvidenceHost } from './evidenceHost'
import { CopyChip } from './Markdown'
/**
* 证据面板:点开报告里的一个片段,看它从哪来。
*
* 展示:片段和它所在的句子;指标步骤——名称、值、口径与版本(钉在别的工作流上的写明来源
* 和升版处置)、原式、代入式(每个输入是「值 ← 路径」的小标签,点一下跳到对应的查询)、
* 复算结果;输入来源——agent 字段、cell() 取数和快照核对得上没有,代码节点的数醒目提醒;
* 查询步骤——SQL、被引用的行和格高亮的结果窗口、打开完整快照、遮罩;封存状态。没有证据
* 的片段说清为什么(裸数字、引用解析不了),另有一份违规清单:列表序号、代码块标签里的数字
* 在正文里画不了线,只能在清单里找到。
*
* 数据两层来源:文档自己记着的出处(doc.catalog,打开就有),和证据接口的证据链
* (原式、代入式、输入、封存,点开才取)。接口取不到(老后端、没有运行 id 的预览)
* 就只显示第一层,并照实说缺了什么。
*
* 只信封存链:正文是按成果上的 _evidence.doc_artifact 取的(成果可以改写、工件表可以
* 事后插行),接口是从封存范围内的事件找的文档。两边不是同一份时,接口的封存状态和
* 证据链说的是另一份报告——不能挂到正文上画成绿的,要醒目地说正文不是封存的那一份。
*
* 三期多了两种步骤:表或字段(出现在哪几次查询里、表结构快照的同步时间、字段类型;可疑的
* 名字给出最接近的已知名字),逐字引文(原文所在的文档和片段,引文在原文里的位置高亮)。
* 画布右栏里点开片段时,把证据路径交给画布(evidenceHost),节点名点一下就对准那个节点。
*
* 四种摆法:side 从右侧弹出(宽屏),drawer 从底部抽出(窄屏),inline 在 360px 的
* 画布右栏里直接栏内展开,dock 放进页面给的一块常驻位置(记录页的「证据」页签)。
* 都不是模态的:开着面板照样能在正文里走。
*/
export type PanelMode = 'side' | 'drawer' | 'inline' | 'dock'
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 ? segName(found.seg) : EVIDENCE_TEXT.panelTitle
// 有出处的实体、引文:徽标写得更具体(「有出处 · 逐字引文」),颜色和字形照同一套
const kind = found && state === 'deterministic' ? segmentKind(found.seg) : null
const badge = kind ? { ...meta!, label: EVIDENCE_KIND_STYLE[kind].label, glyph: EVIDENCE_KIND_STYLE[kind].glyph } : meta
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'
: mode === 'dock'
? 'flex h-full min-h-0 flex-col bg-panel'
: 'ev-panel-rise my-2 flex flex-col rounded-lg border bg-panel'
return (
{mode === 'inline' && (
)}
{badge && (
{badge.glyph && {badge.glyph}}{badge.label}
)}
{title}
{mode !== 'inline' && (
)}
{view.kind === 'violations'
?
: found
?
:
{NONE}
}
)
}
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 (
)
}
/** 定位到的那一步描一下边(CSS 的 [data-flash],减少动效时由全局规则停掉) */
function flashOnce(el: HTMLElement) {
el.dataset.flash = 'focus'
setTimeout(() => { if (el.dataset.flash === 'focus') delete el.dataset.flash }, 1600)
}
function SegmentBody({ panelId, doc, artifact, runId, seg, unit, onViolations }: {
panelId: string
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[] = useMemo(() => (Array.isArray(detail?.chain)
? detail.chain.filter((s) => s && typeof s === 'object') : []), [detail])
const metricStep = chain.find((s) => s.step === 'metric')
const inputStep = chain.find((s) => s.step === 'run_input')
const entityStep = chain.find((s) => s.step === 'entity')
const quoteStep = chain.find((s) => s.step === 'quote')
const queries = chain.filter((s) => s.step === 'query')
const isMetric = cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep
const isInput = cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep
// 三期:有出处的表名字段名、引文(原话对不上的引文也画这一节:说清原文在哪、对不上)
const isEntity = !isMetric && !isInput && seg.kind === 'entity' && state === 'deterministic'
const isQuote = !isMetric && !isInput && seg.kind === 'quote'
// 报告直接引用的查询单元格([[v:Q3.r5.amount]]、整表里的一格):证据链就是那一次查询
const isCell = !isMetric && !isInput && !isEntity && !isQuote
&& (cite?.kind === 'cell' || entry?.kind === 'query' || !!queries.length)
const bad = state === 'none' || state === 'suspect' || state === 'unverified'
const closest = closestNames(detail?.closest ?? entityStep?.closest)
// 画布右栏:点开片段时把证据路径交给画布(产出证据的节点实线、报告虚线),链取回来后再补全
const host = useEvidenceHost()
const onTrace = host.onTrace
const trace = useMemo(() => evidenceTrace(seg, doc, chain), [seg, doc, chain])
const traceKey = `${trace.producers.join(',')}|${trace.consumers.join(',')}`
useEffect(() => {
if (!onTrace) return
const text = segName(seg)
onTrace({ label: `证据 ${text.length > 16 ? `${text.slice(0, 15)}…` : text}`, ...trace })
return () => onTrace(null)
// trace 按内容比(traceKey):同一条路径不重画
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [onTrace, seg.id, traceKey])
const inputs: EvidenceInput[] = metricStep?.inputs?.length
? metricStep.inputs
: chain.filter((s) => s.step === 'input').map((s) => s as EvidenceInput)
const masked = (Array.isArray(detail?.redacted?.columns) ? detail.redacted.columns : []).map(String).filter(Boolean)
const workflows = useCatalog((s) => s.workflows)
const workflowName = (id?: string) => (id ? workflows.find((w) => w.id === id)?.name : undefined)
// 输入标签、输入来源那一行点一下:焦点跳到对应的查询步骤,描一下边
const queryId = (i: number) => `${panelId}-q${i}`
const jumpTo = useCallback((i: number) => {
const part = document.getElementById(`${panelId}-q${i}`)
const head = part?.querySelector('[data-ev-query-head]')
if (!part || !head) return
head.focus({ preventScroll: true })
head.scrollIntoView({ block: 'nearest' })
flashOnce(part)
}, [panelId])
const linkOf = (inp: EvidenceInput) => {
const i = queryOf(inp, queries)
return i >= 0 ? { index: i, alias: queries[i].alias ?? '', go: () => jumpTo(i) } : undefined
}
const violations = (doc.violations ?? []).filter((v) => v.segment === seg.id)
const seal: EvidenceSeal | undefined = docIssue ? undefined : detail?.seal ?? graphData?.seal
const reason = reasonOf(seg) || detail?.note || ''
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 pending = !!runId && !docIssue && (!slot || slot.status === 'loading')
const chainFailed = !runId ? EVIDENCE_TEXT.noRun
: docIssue ? EVIDENCE_TEXT.chainForeign
: slot?.status === 'error' ? EVIDENCE_TEXT.chainMissing : ''
return (
<>
{docIssue && (
// 正文不是封存的那一份:比「有出处」三个字重要得多,放在最前面
)}
{bad && (
{reason}
{/* 违规的原话多半是「引用 … 解析不了:<原因>」,和上面那句重复的不再列;裸数字那条说的是怎么改,留着 */}
{violations.filter((v) => v.message && !(reason && v.message.includes(reason))).map((v, i) => (
{v.message}
))}
{seg.ref && [[{seg.ref}]]
}
{(state === 'suspect' || state === 'unverified') && runId && !docIssue && (
// 可疑的名字:给最接近的已知名字,多半是写错了一个字(接口按封存的台账重建目录找的)
{EVIDENCE_TEXT.closest}
{closest.length ? (
{closest.map((n) => - {n}
)}
) : (
{pending ? EVIDENCE_TEXT.entityPending : EVIDENCE_TEXT.closestNone}
)}
{entityStep?.checked && (
{EVIDENCE_TEXT.checked(entityStep.checked.schemas ?? 0, entityStep.checked.queries ?? 0)}
)}
)}
)}
{isEntity && (
)}
{isQuote && (
)}
{isMetric && (
)}
{isMetric && inputs.some(notableInput) && (
)}
{isInput && !isMetric && (
{inputStep?.field ?? entry?.locator?.field ?? cite?.locator?.field ?? cite?.ref} ={' '}
{valueText(inputStep?.value ?? entry?.value ?? cite?.value)}
)}
{isCell && !queries.length && state === 'deterministic' && (
// 接口没给查询步骤(取不到、老后端、正在取):只说文档目录里记着的那次查询,不画假的行。
// 解析不了的单元格引用(行越界、没有这一列、受管没声明 cells)接口本来就不给链,上面已经说了原因,
// 再摆一块「这一次没取到」就像是接口出了错
)}
{queries.map((q, i) => (
))}
{state === 'deterministic' && !isMetric && !isInput && !isCell && !isEntity && !isQuote && (
{sourceOf(seg, doc) || detail?.note}
)}
{host.onNode && (trace.producers.length > 0 || trace.consumers.length > 0) && (
// 画布右栏:这段证据经过的节点,点一下在画布上选中并对准
{trace.producers.map((n) => )}
{trace.consumers.length > 0 && trace.producers.length > 0 && →}
{trace.consumers.map((n) => )}
)}
{!!doc.violations?.length && (
)}
{!!masked.length && (
// 用户拍板:界面上写明遮罩不是安全边界。放在最后,读完证据再看到这句
{EVIDENCE_TEXT.maskNote(masked)}
)}
>
)
}
type InputLink = { index: number; alias: string; go: () => void } | undefined
/**
* 面板里提到的节点。画布右栏里是按钮:点一下在画布上选中并对准它(画布上已经没有这个节点
* 时不给按钮,点了会落空);别处照旧写节点 id
*/
function NodeChip({ id, prefix }: { id?: string | null; prefix?: string }) {
const host = useEvidenceHost()
if (!id) return null
const label = host.nodeLabel?.(id)
if (host.onNode && label !== undefined) {
return (
)
}
return {prefix}{id}
}
/**
* 表或字段:是什么、字段类型、出现在哪几次查询里、从哪来的(表结构快照、查询 SQL、查询结果列)、
* 表结构快照什么时候同步的。证据接口没取到时照文档目录里记着的来历写,缺的照实说
*/
function EntityPart({ step, entry, cite, seal, pending, failed, catalog }: {
step?: EvidenceStep
entry?: Record
cite?: EvidenceSegment['cite']
seal?: EvidenceSeal
pending: boolean
failed: string
catalog?: EvidenceDocData['catalog']
}) {
const kind = step?.kind ?? entry?.kind ?? cite?.kind
const table = step?.table ?? entry?.table ?? entry?.locator?.table ?? cite?.locator?.table
const column = step?.column ?? entry?.locator?.column ?? cite?.locator?.column
const name = kind === 'table' ? (step?.name ?? entry?.name ?? table ?? cite?.ref)
: table && column ? `${table}.${column}` : (step?.name ?? entry?.name ?? column ?? cite?.ref)
const queries: string[] = (Array.isArray(step?.queries) ? step.queries : Array.isArray(entry?.queries) ? entry.queries : [])
.map(String).filter(Boolean)
const sources = entitySources(step?.sources ?? entry?.sources)
const truncated = sources.some((s) => s.truncated) || step?.snapshot_truncated === true || (step as any)?.truncated === true
const owners: string[] = Array.isArray(step?.tables) ? step.tables : Array.isArray(entry?.tables) ? entry.tables : []
const nodes = [...new Set(queries.map((q) => catalog?.[q]?.node_id).filter((n): n is string => typeof n === 'string'))]
return (
{kind === 'table' ? EVIDENCE_TEXT.table : EVIDENCE_TEXT.column}
{name || NONE}
{step?.type && (
{EVIDENCE_TEXT.columnType} {step.type}
)}
{kind === 'table' && typeof (step as any)?.columns === 'number' && (
{EVIDENCE_TEXT.tableColumns((step as any).columns, !!step?.is_view)}
)}
{step?.comment && {step.comment}
}
{owners.length > 1 && {EVIDENCE_TEXT.ownerTables(owners)}
}
{step?.types && !step.type && Object.keys(step.types).length > 0 && (
{EVIDENCE_TEXT.columnTypes(step.types)}
)}
{queries.length ? EVIDENCE_TEXT.entityQueries(queries) : EVIDENCE_TEXT.entityNoQuery}
{nodes.length > 0 && (
{nodes.map((n) => )}
)}
{sources.length > 0 && (
{sources.map((src) => - · {src.text}
)}
)}
{step?.synced_at && (
{EVIDENCE_TEXT.syncedAt(formatDateTime(step.synced_at))}
)}
{truncated && (
{EVIDENCE_TEXT.snapshotPartial}
)}
{!step && (
{pending ? EVIDENCE_TEXT.entityPending : failed && failed !== EVIDENCE_TEXT.chainMissing ? failed : EVIDENCE_TEXT.entityMissing}
)}
)
}
/**
* 逐字引文:原文所在的文档和片段,引文在原文里的位置高亮(前后带一截上下文)。检索快照哈希对不上时
* 不摆原文——那一段不能当证据。原话对不上的引文也画这一节,只写目录里记着的是哪次检索
*/
function QuotePart({ step, cite, quote, resolved, seal, pending, failed, node, label }: {
step?: EvidenceStep
cite?: EvidenceSegment['cite']
quote: string
resolved: boolean
seal?: EvidenceSeal
pending: boolean
failed: string
node?: string
/** 目录里这次检索的说明:「知识库「运营手册」 · 2 条」 */
label?: string
}) {
const source = (step?.source && typeof step.source === 'object' ? step.source as EvidenceQuoteSource : undefined)
?? cite?.source
const where = quoteWhere(source)
const bad = integrityFailures(step, seal)
// 原文:接口给在 content 里(text 是引文本身);content 为 null 是快照不在封存范围里、取不回来——不拿引文冒充原文
const original = step && 'content' in step ? step.content ?? undefined : step?.text
const loc = cite?.locator
const mismatch = step?.match_ok === false
const win = original && !bad.includes('hash') && !mismatch
? quoteWindow(original, step?.match ?? (loc ? { start: loc.start, end: loc.end } : null), step?.quote ?? quote)
: null
const collection = step?.collection
return (
{step?.alias ?? cite?.alias ?? NONE}
{where ? {where} : label && {label}}
{collection && where && {EVIDENCE_TEXT.quoteCollection(collection)}}
{source?.document && (
{shortId(source.document, 12)}
)}
{(bad.length > 0 || mismatch) && (
(k === 'hash' ? 'quote-hash' : k)), ...(mismatch ? ['quote-match'] : [])].join(' ')}
items={[...bad.map((k) => (k === 'hash' ? EVIDENCE_TEXT.quoteHash : EVIDENCE_TEXT.integrity[k])),
...(mismatch ? [EVIDENCE_TEXT.quoteBad] : [])]} />
)}
{win && (
<>
{win.cutBefore && '…'}{win.before}
{win.hit}
{win.after}{win.cutAfter && '…'}
{EVIDENCE_TEXT.quoteHit}
>
)}
{resolved && !win && !bad.length && !mismatch && (
// 接口说了为什么没有原文(不在封存范围里、取不回来)就照原话
{pending ? EVIDENCE_TEXT.quotePending : step?.note
|| (failed && failed !== EVIDENCE_TEXT.chainMissing ? failed : EVIDENCE_TEXT.quoteMissing)}
)}
{!resolved && {EVIDENCE_TEXT.quoteMiss}
}
)
}
/** 口径卡钉住的上游工作流 id:方案写在 caliber_from,接口给在 source 上 */
function pinnedWorkflow(step?: EvidenceStep): string | undefined {
const from = step?.caliber_from ?? (step?.source && typeof step.source === 'object' ? step.source : undefined)
return from?.workflow_id || undefined
}
/** 所在的句子:点开的那一段描底,句子里的数字加粗 */
function Sentence({ unit, active }: { unit: EvidenceUnit; active: string }) {
return (
{(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'
// 反引号里的表名字段名照行内代码写,不露反引号
const code = s.kind === 'entity' && !!s.code
return (
{code ? segName(s) : s.text}
)
})}
)
}
/** 指标步骤:名称、值、口径与版本(来源、升版处置)、原式、代入式(输入标签)、复算 */
function MetricPart({ step, entry, inputs, runId, seal, pending, failed, resolved, linkOf, workflowName }: {
step?: EvidenceStep
entry?: Record
inputs: EvidenceInput[]
runId?: string
/** 封存状态:逐项复核里「在不在封存范围内」只在封存完好时单独报 */
seal?: EvidenceSeal
pending: boolean
/** 证据链为什么没有:没有运行 id、接口取不到、接口答的是另一份报告 */
failed: string
/** 片段的引用解析成功了(有出处);解析不了的也画这一节,好说清缺的是哪个指标 */
resolved: boolean
/** 输入对应的查询步骤:有的话输入标签是按钮,点一下跳过去 */
linkOf: (input: EvidenceInput) => InputLink
/** 钉住的上游工作流在目录里的名字(接口没给名字时用) */
workflowName?: string
}) {
const host = useEvidenceHost()
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 pinned = step?.caliber_from ?? (step?.source && typeof step.source === 'object' ? step.source : undefined)
?? entry?.caliber_from ?? entry?.source
const from = caliberSourceText(caliber, version, typeof pinned === 'object' ? pinned : undefined, workflowName)
const upgrade = caliberUpgradeText(step?.caliber_upgrade ?? entry?.caliber_upgrade)
// 口径卡里 rendered 为「—」有两种:value 为 null 是缺输入,不为 null 是有值但按格式显示不出来
const dash = rendered === NONE || entry?.rendered === NONE
const missing = entry?.status === 'missing_input' || (value == null && (dash || !resolved))
const unshowable = !missing && dash && value != null
return (
{name}
{resolved && rendered && {rendered}}
{(caliber || version || artifact || from) && (
{from
? {from}
: (caliber || version) && 口径卡「{caliber || NONE}」{version}}
{artifact && 工件 {shortId(artifact)}}
{host.onNode && }
)}
{upgrade && (
{upgrade}
)}
{missing && {EVIDENCE_TEXT.missingValue}
}
{unshowable && (
{EVIDENCE_TEXT.unshowable(valueText(value))}
)}
{step ? (
- {EVIDENCE_TEXT.expression}
{step.expression || NONE}
- {EVIDENCE_TEXT.substituted}
-
{step.substituted || NONE}
{!!inputs.length && (
{inputs.map((inp, i) => )}
)}
- {EVIDENCE_TEXT.recompute}
-
{step.recompute_ok == null ? EVIDENCE_TEXT.recomputeNone
: step.recompute_ok ? EVIDENCE_TEXT.recomputeOk : EVIDENCE_TEXT.recomputeBad}
) : resolved && (
{pending ? EVIDENCE_TEXT.chainPending : failed || (runId ? EVIDENCE_TEXT.chainMissing : EVIDENCE_TEXT.noRun)}
)}
)
}
/**
* 证据接口逐项复核的结果:eid 能重算、工件哈希复验、重新渲染一致、在封存范围内。
* 全过的时候不说(正常态安静);哪一项明确没过就用失败色写出来——这时候这件证据
* 不能信,比「有出处」三个字重要得多。「不在封存范围内」只在封存完好时报:没封存、
* 封存核对失败时后端把每一步都记成 sealed=false,那由封存那一行说,不能说成「事后补进来的」
*/
function Integrity({ step, seal }: { step?: EvidenceStep; seal?: EvidenceSeal }) {
const bad = integrityFailures(step, seal)
if (!bad.length) return null
return EVIDENCE_TEXT.integrity[k])} />
}
function IntegrityList({ code, items }: { code: string; items: string[] }) {
return (
)
}
/**
* 「45,678.5 ← vars.kpi.gmv」:值从哪条路径取的。缺的写「—」、标成提醒色。
* 能对到链里某一次查询的(agent 字段、cell() 取数)是按钮:点一下跳到那个查询步骤
*/
function InputChip({ input, link }: { input: EvidenceInput; link?: InputLink }) {
const missing = input.status === 'missing' || input.value == null
const from = [input.node_id && `来自节点 ${input.node_id}`, input.via && `(${input.via})`, input.role && ` · ${input.role}`]
.filter(Boolean).join('')
const style = missing ? { color: 'var(--st-waiting)', borderColor: 'var(--st-waiting)' } : { color: 'var(--text)' }
const body = {valueText(input.value)} ← {input.path ?? NONE}{missing ? '(缺)' : ''}
return (
{link ? (
) : (
{body}
)}
)
}
const TONE: Record = {
ok: { color: 'var(--st-done)', border: 'var(--border)' },
warn: { color: 'var(--st-waiting)', border: 'var(--border)' },
// 计算角色的代码节点:沙箱里的算术绕开了口径卡,比别的提醒都醒目
alert: { color: 'var(--st-failed)', border: 'var(--st-failed)', background: 'var(--st-failed-soft)' },
muted: { color: 'var(--text-dim)', border: 'var(--border)' },
}
/**
* 输入来源:每个能核对到快照的输入(agent 字段、cell() 取数)、代码节点的输入、缺的输入各一行——
* 路径、从哪个节点哪一格来、核对结果。能对到查询步骤的给「看查询 Qn」
*/
function SourcesPart({ inputs, linkOf }: { inputs: EvidenceInput[]; linkOf: (input: EvidenceInput) => InputLink }) {
return (
)
}
/**
* 查询步骤:SQL(带复制)、结果窗口(被引用的行和格高亮)、窗口说明、打开完整快照、复核。
*
* 接口只给被引用的行加前后各 2 行,窗口没盖住整份快照时写明;完整快照走工件接口(取回时
* 复验哈希),复用工件查看。被遮罩的列在表里写「已遮罩」。查询快照哈希对不上时用失败色写出来:
* 这时候这些行不能当证据,比「有出处」重要得多
*/
function QueryPart({ id, step, seal, masked }: { id: string; step: EvidenceStep; seal?: EvidenceSeal; masked: string[] }) {
const host = useEvidenceHost()
const win = useMemo(() => queryWindow(step), [step])
const [open, setOpen] = useState(false)
const scroller = useRef(null)
const alias = step.alias ?? ''
const hidden = [...new Set([...masked, ...(Array.isArray(step.masked) ? step.masked.map(String) : [])])]
.filter((c) => win.columns.includes(c))
const bad = integrityFailures(step, seal)
// 完整快照只在这一步自己画得出行、复核也都过了时给:快照不在封存范围里(接口一行不给,工件 id 照样带着)、
// 哈希对不上时,按钮一点就绕过证据接口把整份快照打开,还挂着「哈希已校验」
const snapshot = !!step.artifact && step.sealed !== false && step.hash_ok !== false && !bad.length && win.rows.length > 0
// 知道每一行在快照里是第几行时,最前面加一列行号:窗口不连续(被引用的行隔得远)也看得出跳过了哪几行
const table = useMemo(() => (win.index
? { columns: [ROW_NO, ...win.columns], rows: win.rows.map((r, i) => [win.index![i] + 1, ...r]), truncated: false }
: { columns: win.columns, rows: win.rows, truncated: false }), [win])
// 被引用的格可能在右边几列:窄栏里表格横向滚到它,不让人以为没高亮
useLayoutEffect(() => {
const box = scroller.current
const cell = box?.querySelector('td[data-highlight="cell"]')
const inner = cell?.closest('.overflow-x-auto')
if (!cell || !inner) return
const left = cell.offsetLeft
if (left < inner.scrollLeft || left + cell.offsetWidth > inner.scrollLeft + inner.clientWidth) {
inner.scrollLeft = Math.max(0, left - 8)
}
}, [win])
return (
// 从输入标签跳过来时描一下边(flashOnce 设 data-flash):静态描边,减少动效时照样看得见
{/* 键盘跳过来时焦点落在这里:得看得见落在哪(不能 outline-none) */}
{EVIDENCE_TEXT.query(alias)}
{step.tool && {step.tool}}
{host.onNode && }
{step.sql && step.sql ?? ''} />}
{step.sql && (
{step.sql}
)}
{bad.length > 0 && (
(k === 'hash' ? 'query-hash' : k)).join(' ')}
items={bad.map((k) => (k === 'hash' ? EVIDENCE_TEXT.queryHash : EVIDENCE_TEXT.integrity[k]))} />
)}
{win.columns.length > 0 && win.rows.length > 0 && (
0 && 'mt-1.5')}>
)}
{!win.rows.length && (
// 没有行:快照不在封存范围里、哈希对不上、取不回来。接口说了原因就照原话
{step.note || EVIDENCE_TEXT.queryMissing}
)}
{win.windowed && win.total != null && (
{EVIDENCE_TEXT.windowed}({win.span},共 {formatNumber(win.total)} 行)
)}
{step.window_truncated && {EVIDENCE_TEXT.windowCut(win.rows.length)}}
{step.truncated && {EVIDENCE_TEXT.truncatedSnapshot}}
{/* 数据源改名或删掉了:遮罩按查询当时记下的那份处理,行照样给。这句要看得见——
现在的数据源设置已经管不到这份快照了 */}
{step.mask_note && (
{step.mask_note}
)}
{snapshot && (
)}
{/* 弹窗挂到 body 上:侧边面板是 fixed 的一层,里面的遮罩盖不住整页 */}
{/* 完整快照里同样遮掉这几列:工件接口还是原值(面板底部写明了),面板自己的入口不多暴露 */}
{open && snapshot && step.artifact && createPortal(
setOpen(false)} />,
document.body,
)}
)
}
/** 窗口表格最前面那一列:快照里的行号,从 1 数 */
const ROW_NO = '#'
/** 接口没给查询步骤时:文档目录里记着的那次查询(编号、工具、行数),并照实说行没取到 */
function QueryFallback({ entry, alias, where, pending, failed }: {
entry?: Record; alias?: string; where: string; pending: boolean; failed: string
}) {
const rows = typeof entry?.rows === 'number' ? `${formatNumber(entry.rows)} 行` : ''
return (
{[entry?.tool ?? entry?.source, rows, where].filter(Boolean).join(' · ') || NONE}
{pending ? EVIDENCE_TEXT.queryPending : failed === EVIDENCE_TEXT.chainMissing ? EVIDENCE_TEXT.queryMissing : failed || EVIDENCE_TEXT.queryMissing}
)
}
/**
* 封存状态:StatusBadge 的剪影 + 一句话。说什么由 lib/evidence 的 sealVerdict 定(顺序、
* 正文不是封存那份时的失败态都在那里);没有证据的片段封存的只是报告文档本身,
* 不能说成「这个数已封存」
*/
function SealLine({ status, label }: { status: SealStatus; label: string }) {
return (
{label}
)
}
const CODE_LABEL: Record = {
uncited_number: '裸数字',
unresolved_ref: '引用解析不了',
unknown_entity: '可能是编造的名字',
unverified_entity: '核对不了的名字',
}
/** 违规清单:报告撰写节点核对出来的全部问题,画得出线的能定位,画不出的说清在哪 */
function ViolationList({ doc, onLocate }: { doc: EvidenceDocData; onLocate: (segId: string) => void }) {
const list: EvidenceViolation[] = doc.violations ?? []
if (!list.length) return {EVIDENCE_TEXT.allCited(docNumbers(doc))}
return (
<>
{EVIDENCE_TEXT.violationsHint}
>
)
}
const docNumbers = (doc: EvidenceDocData): number => doc.stats?.numbers ?? 0