Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โœจ feat(acceptance): render structured verification data (#17633)

Arvin Xud89b20faae24
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 2570e38b839..21d0b79884e 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -168,6 +168,27 @@ in the renderer graph, which makes Vite optimize and execute `vitest` in the app
import the locale resource there. Restart the isolated Electron instance after a
bad scan because the optimized dependency graph can remain poisoned.
+### Shared agent-browser session names can cross-wire concurrent acceptance runs
+
+**Situation:** a Web acceptance run uses the adapter's default `lobehub-dev`
+session while another local run is active against a different port.
+
+**Doesn't work:** reusing `lobehub-dev` and trusting the URL printed immediately
+after `open`. Another process can steer the same session between commands, so a
+later click or screenshot lands on a different acceptance and port.
+
+**Works:** create a run-specific session name and load the seeded auth state
+directly:
+
+```bash
+RUN_SESSION=visualization-acceptance
+agent-browser --session "$RUN_SESSION" \
+ --state ~/.lobehub-agent-testing/web-state.json open "$SERVER_URL/acceptance"
+```
+
+Then assert `get url` and `app-probe.sh auth` on that exact session before
+capturing evidence.
+
## Detailed references
- [Probe field notes](./references/probe-field-notes.md) โ€” all historical
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index 55c8468896b..57b3990e98f 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -563,8 +563,12 @@ report directory for every execution round.
Notes:
-- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;
- `evidence` is a path (or array) relative to `$DIR`. `result`/`verdict` map onto
+- `result.json` cases use
+ `{ id?, name, result, observation?, evidence?, datasets?, visualizations? }`;
+ structured views should retain raw benchmark/profile/vector files as evidence;
+ `evidence` is a path (or array) relative to `$DIR`. Supported structured views are
+ `metric-comparison`, `line-chart`, `bar-chart`, `scatter-plot`, `heatmap`, and `table`.
+ `result`/`verdict` map onto
`passed | failed | uncertain`.
- Finer control is available through the atomic commands โ€” `acceptance run create`,
`acceptance run result ingest`, `acceptance run evidence upload` (`--file` or `--content`),
diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.md
index c87830887cf..587ed303e8d 100644
--- a/.agents/skills/agent-testing/references/report.md
+++ b/.agents/skills/agent-testing/references/report.md
@@ -260,6 +260,53 @@ REQUIRED on every ingest:**
"status": "pass",
"observation": "root returned 3 nested children, depth 2",
"evidence": ["assets/task-tree.txt"]
+ },
+ {
+ "category": "Tab responsiveness",
+ "id": "2",
+ "name": "conversation tab switching avoids duplicate parsing",
+ "surface": "desktop",
+ "status": "pass",
+ "observation": "The switch-time parsing hotspot disappeared and GC time fell.",
+ "evidence": ["assets/benchmark.json", "assets/cpu-profile.json"],
+ "datasets": [
+ {
+ "id": "switch-metrics",
+ "fields": [
+ { "key": "name", "type": "string" },
+ { "key": "before", "type": "number", "unit": "ms" },
+ { "key": "after", "type": "number", "unit": "ms" },
+ { "key": "direction", "type": "category" },
+ { "key": "target", "type": "number", "unit": "ms" }
+ ],
+ "rows": [
+ {
+ "name": "GC self-time",
+ "before": 257,
+ "after": 24.8,
+ "direction": "lower",
+ "target": 50
+ }
+ ]
+ }
+ ],
+ "visualizations": [
+ {
+ "id": "switch-comparison",
+ "type": "metric-comparison",
+ "version": 1,
+ "dataset": "switch-metrics",
+ "title": "Performance comparison",
+ "context": "Electron 40, warm cache, identical tool-heavy topic fixture",
+ "encoding": {
+ "label": "name",
+ "before": "before",
+ "after": "after",
+ "direction": "direction",
+ "target": "target"
+ }
+ }
+ ]
}
],
"commit": "abc1234",
@@ -282,6 +329,16 @@ REQUIRED on every ingest:**
"method": "<cli> task list --tree against a 3-level fixture",
"expected": "root shows 3 nested children at depth 2",
"requiredEvidence": ["text"]
+ },
+ {
+ "id": "2",
+ "title": "conversation tab switching avoids duplicate parsing",
+ "category": "Tab responsiveness",
+ "surface": "desktop",
+ "verifier": "program",
+ "method": "Run the same warm-cache CDP switch profile before and after the change",
+ "expected": "GC self-time is at or below 50 ms",
+ "requiredEvidence": ["text"]
}
],
"pullRequest": {
@@ -290,8 +347,8 @@ REQUIRED on every ingest:**
"url": "https://github.com/<org>/<repo>/pull/17152"
},
"summary": {
- "total": 1,
- "passed": 1,
+ "total": 2,
+ "passed": 2,
"failed": 0,
"blocked": 0,
"score": 100,
@@ -342,6 +399,30 @@ to `desktop`. Anything else fails the ingest:
`entry` is the command or URL exercised (`<cli> task list --tree`, `/chat/settings`)
โ€” **not** a PR title and not a description of the change.
+### Structured visualizations
+
+A case may provide `datasets[]` plus `visualizations[]`. The ingest stores the
+versioned manifest on the check result and the Acceptance page renders each view.
+The first supported renderers are `metric-comparison`, `line-chart`, `bar-chart`,
+`scatter-plot`, `heatmap`, and `table` (all `version: 1`). Each view references one dataset by id
+and maps its fields through `encoding`.
+
+Use `line-chart.encoding.series[].style` (`muted` | `primary` | `accent`) to keep a
+baseline visually quiet and emphasize the compared run. Tables can mark best-in-column
+values with `encoding.highlights[]` (`{ field, mode: "min" | "max" }`); ties are all
+marked SOTA. `bar-chart` is the default for grouped model or benchmark score comparisons.
+
+Inline datasets use declared `fields[]` and object `rows[]`; undeclared cells,
+unsupported renderers, missing dataset references, and more than 10,000 total
+rows fail ingest. Use inline data only for a review-sized summary. Keep raw
+benchmark output, traces, vectors, or profiles in `evidence`; visualization is a
+decision aid, not a replacement for evidence.
+
+For comparable metrics, only publish before/after values produced by the same
+harness, fixture, environment, warm-up policy, statistic, and sample window. If
+those differ, use separate series or mark the case uncertain instead of presenting
+a misleading delta.
+
`pullRequest` is optional: when absent, the ingest asks `gh` for the PR of `branch`
and fills it in. Write it explicitly only when the report verifies a PR that isn't
the branch's own.
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 99922147507..2e5aed0a44c 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -32,6 +32,7 @@ import {
subjectFromResult,
surfacesFromResult,
toVerdict,
+ visualizationMetadata,
} from './verifyHelpers';
// โ”€โ”€ Actions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -504,6 +505,19 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
}
const cases: any[] = Array.isArray(result.cases) ? result.cases : [];
+ // Validate every schemaless visualization before the first remote mutation.
+ // An ingest that cannot render must not create or attach a partial immutable round.
+ const caseMetadata = cases.map((item, index) => {
+ try {
+ return visualizationMetadata(item);
+ } catch (error) {
+ const checkItemId = String(item.id ?? item.checkItemId ?? `case-${index + 1}`);
+ throw new Error(
+ `case ${checkItemId}: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ });
const summary = result.summary ?? {};
const reportMdPath = path.join(dir, 'report.md');
const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
@@ -626,6 +640,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
checkItemId,
checkItemIndex: index,
checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
+ metadata: caseMetadata[index],
required: c.required ?? true,
// The case's key observation is recorded as Toulmin evidence; a real
// remediation hint (if the report provides one) goes to `suggestion`.
diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.ts
index 70cca339e1e..ee781f462d6 100644
--- a/apps/cli/src/commands/verify.test.ts
+++ b/apps/cli/src/commands/verify.test.ts
@@ -19,6 +19,7 @@ import {
subjectFromEnv,
subjectFromResult,
surfacesFromResult,
+ visualizationMetadata,
} from './verify';
import { registerAcceptanceCommands } from './verifyAcceptance';
@@ -312,6 +313,116 @@ describe('reportEvidence โ€” comparison normalization', () => {
});
});
+describe('visualizationMetadata', () => {
+ const input = {
+ datasets: [
+ {
+ fields: [
+ { key: 'name', type: 'string' },
+ { key: 'before', type: 'number', unit: 'ms' },
+ { key: 'after', type: 'number', unit: 'ms' },
+ ],
+ id: 'metrics',
+ rows: [{ after: 24.8, before: 257, name: 'GC self-time' }],
+ },
+ ],
+ visualizations: [
+ {
+ dataset: 'metrics',
+ encoding: { after: 'after', before: 'before', label: 'name' },
+ id: 'performance',
+ type: 'metric-comparison',
+ version: 1,
+ },
+ ],
+ };
+
+ it('normalizes datasets and views into versioned check-result metadata', () => {
+ expect(visualizationMetadata(input)).toEqual({
+ visualization: {
+ datasets: input.datasets,
+ schemaVersion: 1,
+ views: input.visualizations,
+ },
+ });
+ });
+
+ it('rejects a view that references a missing dataset', () => {
+ expect(() =>
+ visualizationMetadata({
+ ...input,
+ visualizations: [{ ...input.visualizations[0], dataset: 'missing' }],
+ }),
+ ).toThrow('dataset');
+ });
+
+ it('rejects cells outside the declared field schema', () => {
+ expect(() =>
+ visualizationMetadata({
+ ...input,
+ datasets: [{ ...input.datasets[0], rows: [{ unexpected: 1 }] }],
+ }),
+ ).toThrow('does not match');
+ });
+
+ it('accepts grouped bar charts and SOTA table highlights', () => {
+ expect(
+ visualizationMetadata({
+ ...input,
+ visualizations: [
+ {
+ dataset: 'metrics',
+ encoding: { category: 'name', series: [{ field: 'before' }] },
+ id: 'scores',
+ type: 'bar-chart',
+ version: 1,
+ },
+ {
+ dataset: 'metrics',
+ encoding: { highlights: [{ field: 'after', mode: 'min' }] },
+ id: 'score-table',
+ type: 'table',
+ version: 1,
+ },
+ ],
+ })?.visualization?.views.map((view) => view.type),
+ ).toEqual(['bar-chart', 'table']);
+ });
+
+ it.each([
+ ['bar-chart', {}],
+ ['heatmap', { x: 'name', y: 'before' }],
+ ['line-chart', { series: [], x: 'name' }],
+ ['metric-comparison', { after: 'after', before: 'before' }],
+ ['scatter-plot', { x: 'before', y: 'missing' }],
+ ['table', { columns: ['missing'] }],
+ ])('rejects malformed %s encodings', (type, encoding) => {
+ expect(() =>
+ visualizationMetadata({
+ ...input,
+ visualizations: [{ dataset: 'metrics', encoding, id: 'invalid-view', type, version: 1 }],
+ }),
+ ).toThrow();
+ });
+
+ it('rejects duplicate dataset field keys', () => {
+ expect(() =>
+ visualizationMetadata({
+ ...input,
+ datasets: [
+ {
+ ...input.datasets[0],
+ fields: [
+ { key: 'name', type: 'string' },
+ { key: 'name', type: 'number' },
+ ],
+ },
+ ],
+ }),
+ ).toThrow('field keys must be unique');
+ });
+});
+
describe('evidenceTypeForFile โ€” markdown evidence', () => {
it('maps .md / .markdown to the markdown medium, keeping .txt as text', () => {
expect(evidenceTypeForFile('assets/root-cause.md')).toBe('markdown');
@@ -588,6 +699,43 @@ describe('verify ingest-report โ€” every run is an immutable acceptance round',
}
});
+ it('validates every visualization before creating or attaching an immutable round', async () => {
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ writeFileSync(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ {
+ datasets: [
+ {
+ fields: [{ key: 'score', type: 'number' }],
+ id: 'scores',
+ rows: [{ score: 1 }],
+ },
+ ],
+ id: 'broken-chart',
+ visualizations: [
+ {
+ dataset: 'scores',
+ encoding: {},
+ id: 'chart',
+ type: 'bar-chart',
+ version: 1,
+ },
+ ],
+ },
+ ],
+ }),
+ );
+
+ await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow(
+ 'case broken-chart: visualizations[0].encoding.category',
+ );
+ expect(verify.createRun.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();
+ });
+
it('creates another run when the same report directory is ingested again', async () => {
const verify = mockTrpcClient.verify as Record<string, any>;
verify.createRun.mutate
diff --git a/apps/cli/src/commands/verifyHelpers.ts b/apps/cli/src/commands/verifyHelpers.ts
index c97d2736315..c6c5355f722 100644
--- a/apps/cli/src/commands/verifyHelpers.ts
+++ b/apps/cli/src/commands/verifyHelpers.ts
@@ -15,6 +15,14 @@ import {
verifyRunScenarios,
verifySurfaces,
} from '@lobechat/const/verify';
+import type {
+ VerifyCheckResultMetadata,
+ VerifyVisualizationDataset,
+ VerifyVisualizationField,
+ VerifyVisualizationManifest,
+ VerifyVisualizationValue,
+ VerifyVisualizationView,
+} from '@lobechat/types';
import pc from 'picocolors';
import { printTable, truncate } from '../utils/format';
@@ -124,6 +132,246 @@ export interface ReportEvidenceInput {
path: string;
}
+const VISUALIZATION_FIELD_TYPES = new Set(['boolean', 'category', 'number', 'string', 'temporal']);
+const VISUALIZATION_TYPES = new Set([
+ 'bar-chart',
+ 'heatmap',
+ 'line-chart',
+ 'metric-comparison',
+ 'scatter-plot',
+ 'table',
+]);
+const MAX_INLINE_VISUALIZATION_ROWS = 10_000;
+
+const visualizationValue = (value: unknown): value is VerifyVisualizationValue =>
+ value === null || ['boolean', 'number', 'string'].includes(typeof value);
+
+const visualizationField = (
+ encoding: Record<string, unknown>,
+ key: string,
+ fieldKeys: Set<string>,
+ path: string,
+) => {
+ const field = firstString(encoding[key]);
+ if (!field || !fieldKeys.has(field)) {
+ throw new Error(`${path}.${key} must reference a declared dataset field`);
+ }
+ return field;
+};
+
+const optionalVisualizationField = (
+ encoding: Record<string, unknown>,
+ key: string,
+ fieldKeys: Set<string>,
+ path: string,
+) => {
+ if (encoding[key] === undefined) return;
+ visualizationField(encoding, key, fieldKeys, path);
+};
+
+const optionalVisualizationString = (value: Record<string, unknown>, key: string, path: string) => {
+ if (value[key] !== undefined && !firstString(value[key])) {
+ throw new Error(`${path}.${key} must be a non-empty string`);
+ }
+};
+
+const visualizationSeries = (
+ encoding: Record<string, unknown>,
+ fieldKeys: Set<string>,
+ path: string,
+ options?: { styles?: boolean },
+) => {
+ if (!Array.isArray(encoding.series) || encoding.series.length === 0) {
+ throw new Error(`${path}.series must be a non-empty array`);
+ }
+ encoding.series.forEach((rawSeries, seriesIndex) => {
+ const series = objectValue(rawSeries);
+ const seriesPath = `${path}.series[${seriesIndex}]`;
+ if (!series) throw new Error(`${seriesPath} must be an object`);
+ visualizationField(series, 'field', fieldKeys, seriesPath);
+ if (series.label !== undefined && !firstString(series.label)) {
+ throw new Error(`${seriesPath}.label must be a non-empty string`);
+ }
+ if (
+ options?.styles &&
+ series.style !== undefined &&
+ !['accent', 'muted', 'primary'].includes(String(series.style))
+ ) {
+ throw new Error(`${seriesPath}.style is invalid`);
+ }
+ });
+};
+
+const validateVisualizationEncoding = (
+ view: Record<string, unknown>,
+ fieldKeys: Set<string>,
+ index: number,
+) => {
+ const path = `visualizations[${index}].encoding`;
+ if (view.type === 'table' && view.encoding === undefined) return;
+ const encoding = objectValue(view.encoding);
+ if (!encoding) throw new Error(`${path} is required for ${String(view.type)}`);
+
+ switch (view.type) {
+ case 'bar-chart': {
+ visualizationField(encoding, 'category', fieldKeys, path);
+ visualizationSeries(encoding, fieldKeys, path);
+ optionalVisualizationString(encoding, 'valueLabel', path);
+ break;
+ }
+ case 'heatmap': {
+ visualizationField(encoding, 'x', fieldKeys, path);
+ visualizationField(encoding, 'y', fieldKeys, path);
+ visualizationField(encoding, 'value', fieldKeys, path);
+ break;
+ }
+ case 'line-chart': {
+ visualizationField(encoding, 'x', fieldKeys, path);
+ visualizationSeries(encoding, fieldKeys, path, { styles: true });
+ optionalVisualizationString(encoding, 'xLabel', path);
+ optionalVisualizationString(encoding, 'yLabel', path);
+ break;
+ }
+ case 'metric-comparison': {
+ visualizationField(encoding, 'label', fieldKeys, path);
+ visualizationField(encoding, 'before', fieldKeys, path);
+ visualizationField(encoding, 'after', fieldKeys, path);
+ for (const key of [
+ 'afterSamples',
+ 'beforeSamples',
+ 'direction',
+ 'statistic',
+ 'target',
+ 'unit',
+ ]) {
+ optionalVisualizationField(encoding, key, fieldKeys, path);
+ }
+ break;
+ }
+ case 'scatter-plot': {
+ visualizationField(encoding, 'x', fieldKeys, path);
+ visualizationField(encoding, 'y', fieldKeys, path);
+ optionalVisualizationField(encoding, 'color', fieldKeys, path);
+ optionalVisualizationField(encoding, 'label', fieldKeys, path);
+ optionalVisualizationString(encoding, 'xLabel', path);
+ optionalVisualizationString(encoding, 'yLabel', path);
+ break;
+ }
+ case 'table': {
+ if (encoding.columns !== undefined) {
+ if (!Array.isArray(encoding.columns) || encoding.columns.length === 0) {
+ throw new Error(`${path}.columns must be a non-empty array`);
+ }
+ encoding.columns.forEach((field, fieldIndex) =>
+ visualizationField({ field }, 'field', fieldKeys, `${path}.columns[${fieldIndex}]`),
+ );
+ }
+ if (encoding.highlights !== undefined) {
+ if (!Array.isArray(encoding.highlights)) {
+ throw new Error(`${path}.highlights must be an array`);
+ }
+ encoding.highlights.forEach((rawHighlight, highlightIndex) => {
+ const highlight = objectValue(rawHighlight);
+ const highlightPath = `${path}.highlights[${highlightIndex}]`;
+ if (!highlight) throw new Error(`${highlightPath} must be an object`);
+ visualizationField(highlight, 'field', fieldKeys, highlightPath);
+ if (highlight.mode !== 'max' && highlight.mode !== 'min') {
+ throw new Error(`${highlightPath}.mode must be max or min`);
+ }
+ });
+ }
+ break;
+ }
+ }
+};
+
+/** Parse the case's datasets + views into versioned check-result metadata. */
+export function visualizationMetadata(value: unknown): VerifyCheckResultMetadata | undefined {
+ const input = objectValue(value);
+ if (!input || (input.datasets === undefined && input.visualizations === undefined))
+ return undefined;
+ if (!Array.isArray(input.datasets) || !Array.isArray(input.visualizations)) {
+ throw new Error('datasets and visualizations must both be arrays');
+ }
+
+ let rowCount = 0;
+ const datasets = input.datasets.map((rawDataset, datasetIndex) => {
+ const dataset = objectValue(rawDataset);
+ const id = firstString(dataset?.id);
+ if (!id || !Array.isArray(dataset?.fields) || !Array.isArray(dataset.rows)) {
+ throw new Error(`datasets[${datasetIndex}] needs id, fields, and rows`);
+ }
+
+ const fields = dataset.fields.map((rawField, fieldIndex) => {
+ const field = objectValue(rawField);
+ const key = firstString(field?.key);
+ const type = field?.type;
+ if (!key || typeof type !== 'string' || !VISUALIZATION_FIELD_TYPES.has(type)) {
+ throw new Error(`datasets[${datasetIndex}].fields[${fieldIndex}] is invalid`);
+ }
+ return {
+ key,
+ label: firstString(field.label),
+ type,
+ unit: firstString(field.unit),
+ } as VerifyVisualizationField;
+ });
+ const fieldKeys = new Set(fields.map((field) => field.key));
+ if (fieldKeys.size !== fields.length) {
+ throw new Error(`datasets[${datasetIndex}] field keys must be unique`);
+ }
+
+ const rows = dataset.rows.map((rawRow, rowIndex) => {
+ const row = objectValue(rawRow);
+ if (
+ !row ||
+ Object.entries(row).some(([key, cell]) => !fieldKeys.has(key) || !visualizationValue(cell))
+ ) {
+ throw new Error(`datasets[${datasetIndex}].rows[${rowIndex}] does not match its fields`);
+ }
+ return row as Record<string, VerifyVisualizationValue>;
+ });
+ rowCount += rows.length;
+ return { fields, id, rows } satisfies VerifyVisualizationDataset;
+ });
+
+ if (rowCount > MAX_INLINE_VISUALIZATION_ROWS) {
+ throw new Error(`visualization metadata exceeds ${MAX_INLINE_VISUALIZATION_ROWS} inline rows`);
+ }
+ const datasetIds = new Set(datasets.map((dataset) => dataset.id));
+ if (datasetIds.size !== datasets.length) throw new Error('dataset ids must be unique');
+ const fieldKeysByDataset = new Map(
+ datasets.map((dataset) => [dataset.id, new Set(dataset.fields.map((field) => field.key))]),
+ );
+
+ const views = input.visualizations.map((rawView, index) => {
+ const view = objectValue(rawView);
+ const id = firstString(view?.id);
+ const type = view?.type;
+ const dataset = firstString(view?.dataset);
+ if (
+ !id ||
+ typeof type !== 'string' ||
+ !VISUALIZATION_TYPES.has(type) ||
+ !dataset ||
+ !datasetIds.has(dataset) ||
+ view.version !== 1
+ ) {
+ throw new Error(`visualizations[${index}] has an invalid id, type, version, or dataset`);
+ }
+ optionalVisualizationString(view, 'context', `visualizations[${index}]`);
+ optionalVisualizationString(view, 'title', `visualizations[${index}]`);
+ validateVisualizationEncoding(view, fieldKeysByDataset.get(dataset)!, index);
+ return view as unknown as VerifyVisualizationView;
+ });
+ if (new Set(views.map((view) => view.id)).size !== views.length) {
+ throw new Error('visualization ids must be unique');
+ }
+
+ const visualization: VerifyVisualizationManifest = { datasets, schemaVersion: 1, views };
+ return { visualization };
+}
+
export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {
if (!evidence) return [];
const arr = Array.isArray(evidence) ? evidence : [evidence];
diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.ts
index de1aac4e6bd..c113d45460c 100644
--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts
@@ -117,6 +117,29 @@ describe('verifyRouter', () => {
expect(written.verdict).toBeUndefined();
});
+ it('persists structured visualization metadata with the check result', async () => {
+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });
+ const metadata = {
+ visualization: {
+ datasets: [],
+ schemaVersion: 1,
+ views: [],
+ },
+ };
+
+ await createCaller().ingestResult({
+ checkItemId: 'check-1',
+ metadata,
+ verdict: 'passed',
+ verifyRunId: 'run-1',
+ });
+
+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata }),
+ );
+ });
+
it('rejects a result with neither a verdict nor an explicit status', async () => {
await expect(
createCaller().ingestResult({ checkItemId: 'check-1', verifyRunId: 'run-1' } as any),
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index 84a6bff4e05..3ff32b99817 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -5,7 +5,12 @@ import {
verifySurfaces,
verifyVisibilities,
} from '@lobechat/const/verify';
-import type { VerifyCheckItem, VerifyRunContext, VerifyRunScenario } from '@lobechat/types';
+import type {
+ VerifyCheckItem,
+ VerifyCheckResultMetadata,
+ VerifyRunContext,
+ VerifyRunScenario,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { asc, eq } from 'drizzle-orm';
import { z } from 'zod';
@@ -750,6 +755,7 @@ export const verifyRouter = router({
checkItemIndex: z.number().optional(),
checkItemTitle: z.string().optional(),
confidence: z.number().min(0).max(1).optional(),
+ metadata: z.unknown().nullish(),
required: z.boolean().optional(),
status: checkStatusSchema.optional(),
// `.nullish()` (not `.optional()`) so a re-ingest can pass an explicit
@@ -782,6 +788,7 @@ export const verifyRouter = router({
checkItemTitle: input.checkItemTitle,
completedAt: new Date(),
confidence: input.confidence,
+ metadata: input.metadata as VerifyCheckResultMetadata | null | undefined,
required: input.required ?? true,
// Prefer an explicit status; else derive from the verdict (the refine
// guarantees at least one is present).
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 32c4d8b80e8..d3161c20d24 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -395,6 +395,12 @@
"report.verdict.notExecuted": "Not run",
"report.verdict.passed": "Passed",
"report.verdict.uncertain": "Uncertain",
+ "report.visualization.after": "After",
+ "report.visualization.before": "Before",
+ "report.visualization.targetMet": "Target met ยท {{value}}",
+ "report.visualization.targetMissed": "Target missed ยท {{value}}",
+ "report.visualization.title": "Data visualization",
+ "report.visualization.unnamed": "Unnamed metric",
"reports.actions.refresh": "Refresh",
"reports.actions.retry": "Retry",
"reports.dateUnknown": "Date unknown",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 3e309498edb..5089d4747b3 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -395,6 +395,12 @@
"report.verdict.notExecuted": "ๆœชๆ‰ง่กŒ",
"report.verdict.passed": "ๅทฒ้€š่ฟ‡",
"report.verdict.uncertain": "ไธ็กฎๅฎš",
+ "report.visualization.after": "ไผ˜ๅŒ–ๅŽ",
+ "report.visualization.before": "ไผ˜ๅŒ–ๅ‰",
+ "report.visualization.targetMet": "่พพๅˆฐ็›ฎๆ ‡ ยท {{value}}",
+ "report.visualization.targetMissed": "ๆœช่พพๅˆฐ็›ฎๆ ‡ ยท {{value}}",
+ "report.visualization.title": "ๆ•ฐๆฎๅฏ่ง†ๅŒ–",
+ "report.visualization.unnamed": "ๆœชๅ‘ฝๅๆŒ‡ๆ ‡",
"reports.actions.refresh": "ๅˆทๆ–ฐ",
"reports.actions.retry": "้‡่ฏ•",
"reports.dateUnknown": "ๆ—ฅๆœŸๆœช็Ÿฅ",
diff --git a/packages/database/src/schemas/verify.ts b/packages/database/src/schemas/verify.ts
index e67bc267bd0..c50ec398636 100644
--- a/packages/database/src/schemas/verify.ts
+++ b/packages/database/src/schemas/verify.ts
@@ -20,6 +20,7 @@ import type {
ToulminVerdict,
VerifyCheckDecisionDetail,
VerifyCheckItem,
+ VerifyCheckResultMetadata,
VerifyRubricConfig,
VerifyRunContext,
VerifyRunDecisionDetail,
@@ -242,7 +243,7 @@ export const verifyCheckResults = pgTable(
toulmin: jsonb('toulmin').$type<ToulminVerdict>(),
/** Generic result extension bag. Shape is intentionally unknown until verifier payloads stabilize. */
- metadata: jsonb('metadata').$type<unknown>(),
+ metadata: jsonb('metadata').$type<VerifyCheckResultMetadata>(),
/** Forward-looking remediation hint, seeded into auto_repair. */
suggestion: text('suggestion'),
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index c68c31b56de..d8b728ed7ea 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -374,6 +374,12 @@ export default {
'report.filter.passed': 'Passed',
'report.filter.uncertain': 'Uncertain',
'report.filterEmpty': 'No checks match this filter.',
+ 'report.visualization.after': 'After',
+ 'report.visualization.before': 'Before',
+ 'report.visualization.targetMet': 'Target met ยท {{value}}',
+ 'report.visualization.targetMissed': 'Target missed ยท {{value}}',
+ 'report.visualization.title': 'Data visualization',
+ 'report.visualization.unnamed': 'Unnamed metric',
'report.interaction.active': 'Active',
'report.interaction.operator.H': 'H',
'report.interaction.operator.K': 'K',
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 7e0ff356a43..adf0589f750 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -483,6 +483,116 @@ export interface VerifyRunMetadata {
origin?: VerifyRunOrigin;
}
+export type VerifyVisualizationValue = boolean | null | number | string;
+
+export interface VerifyVisualizationField {
+ key: string;
+ label?: string;
+ type: 'boolean' | 'category' | 'number' | 'string' | 'temporal';
+ unit?: string;
+}
+
+/** Small inline dataset used by one or more check-result views. */
+export interface VerifyVisualizationDataset {
+ fields: VerifyVisualizationField[];
+ id: string;
+ rows: Record<string, VerifyVisualizationValue>[];
+}
+
+interface VerifyVisualizationViewBase {
+ context?: string;
+ dataset: string;
+ id: string;
+ title?: string;
+ version: 1;
+}
+
+export interface VerifyMetricComparisonView extends VerifyVisualizationViewBase {
+ encoding: {
+ after: string;
+ afterSamples?: string;
+ before: string;
+ beforeSamples?: string;
+ direction?: string;
+ label: string;
+ statistic?: string;
+ target?: string;
+ unit?: string;
+ };
+ type: 'metric-comparison';
+}
+
+export interface VerifyLineChartView extends VerifyVisualizationViewBase {
+ encoding: {
+ series: {
+ field: string;
+ label?: string;
+ /** Visual role: muted baselines stay gray while primary/accent series carry emphasis. */
+ style?: 'accent' | 'muted' | 'primary';
+ }[];
+ x: string;
+ xLabel?: string;
+ yLabel?: string;
+ };
+ type: 'line-chart';
+}
+
+export interface VerifyScatterPlotView extends VerifyVisualizationViewBase {
+ encoding: {
+ color?: string;
+ label?: string;
+ x: string;
+ xLabel?: string;
+ y: string;
+ yLabel?: string;
+ };
+ type: 'scatter-plot';
+}
+
+export interface VerifyHeatmapView extends VerifyVisualizationViewBase {
+ encoding: { value: string; x: string; y: string };
+ type: 'heatmap';
+}
+
+export interface VerifyBarChartView extends VerifyVisualizationViewBase {
+ encoding: {
+ category: string;
+ series: { field: string; label?: string }[];
+ valueLabel?: string;
+ };
+ type: 'bar-chart';
+}
+
+export interface VerifyTableView extends VerifyVisualizationViewBase {
+ encoding?: {
+ columns?: string[];
+ /** Bold the best numeric value in each configured metric column. */
+ highlights?: { field: string; mode: 'max' | 'min' }[];
+ };
+ type: 'table';
+}
+
+export type VerifyVisualizationView =
+ | VerifyBarChartView
+ | VerifyHeatmapView
+ | VerifyLineChartView
+ | VerifyMetricComparisonView
+ | VerifyScatterPlotView
+ | VerifyTableView;
+
+/** Versioned structured presentation manifest attached to one check result. */
+export interface VerifyVisualizationManifest {
+ datasets: VerifyVisualizationDataset[];
+ schemaVersion: 1;
+ views: VerifyVisualizationView[];
+}
+
+/** Known check-result metadata. Remains open for verifier-specific extensions. */
+export interface VerifyCheckResultMetadata {
+ [key: string]: unknown;
+ visualization?: VerifyVisualizationManifest;
+}
+
/**
* Immutable snapshot of one check item, frozen into `agent_operations.verify_plan`
* when the plan is confirmed. The resolved content (title / verifierConfig) is
diff --git a/src/features/Verify/Acceptance/CheckList.tsx b/src/features/Verify/Acceptance/CheckList.tsx
index 762998ee537..789c32203b9 100644
--- a/src/features/Verify/Acceptance/CheckList.tsx
+++ b/src/features/Verify/Acceptance/CheckList.tsx
@@ -49,6 +49,11 @@ import {
EvidenceFileCard,
markdownTextEvidenceTypes,
} from '../components/MarkdownEvidence';
+import { hasRenderableEvidence, readVisualizationManifest } from '../components/visualization';
+import {
+ VisualizationDeltaBadge,
+ VisualizationRenderer,
+} from '../components/VisualizationRenderer';
import { AnnotatedImage } from './Annotation';
import { AttachmentThumbs } from './attachments';
import { openCheckRejectModal } from './CheckRejectModal';
@@ -767,6 +772,7 @@ const CheckRow = memo<{
const [ignoring, setIgnoring] = useState(false);
const meta = STATE_META[check.state];
const counts = evidenceCounts(check.evidence);
+ const visualization = readVisualizationManifest(check.result?.metadata);
const reviewState = userReviewState(check);
// The decision is stamped on the check's result row โ€” a never-executed
@@ -954,6 +960,7 @@ const CheckRow = memo<{
<Icon color={cssVar.colorTextQuaternary} icon={BadgeCheck} size={14} />
</Tooltip>
)}
+ {visualization && <VisualizationDeltaBadge manifest={visualization} />}
{EVIDENCE_BADGES.map(({ icon, key, labelKey }) =>
counts[key] ? (
<Tooltip key={key} title={t(labelKey, { count: counts[key] })}>
@@ -1037,6 +1044,7 @@ const CheckRow = memo<{
{check.result.toulmin.evidence}
</Text>
)}
+ {visualization && <VisualizationRenderer manifest={visualization} />}
<EvidenceList evidence={check.evidence} />
{check.state === 'not_executed' && (
@@ -1067,21 +1075,23 @@ const CheckRow = memo<{
{/* An executed check with zero artifacts must SAY so โ€” a silent blank
under the verdict reads as a rendering bug, not as a fact. Filled
so it reads as a status, never as more description text. */}
- {check.state !== 'not_executed' && check.result && check.evidence.length === 0 && (
- <Flexbox
- paddingBlock={6}
- paddingInline={10}
- style={{
- background: cssVar.colorFillQuaternary,
- borderRadius: cssVar.borderRadius,
- width: '100%',
- }}
- >
- <Text fontSize={12} type={'secondary'}>
- {t('acceptance.evidence.empty')}
- </Text>
- </Flexbox>
- )}
+ {check.state !== 'not_executed' &&
+ check.result &&
+ !hasRenderableEvidence(check.evidence.length, visualization) && (
+ <Flexbox
+ paddingBlock={6}
+ paddingInline={10}
+ style={{
+ background: cssVar.colorFillQuaternary,
+ borderRadius: cssVar.borderRadius,
+ width: '100%',
+ }}
+ >
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.evidence.empty')}
+ </Text>
+ </Flexbox>
+ )}
{/* The user's standing feedback hangs right under the evidence it
judges. BOTH verdicts keep an undo path โ€” a mis-click is the most
diff --git a/src/features/Verify/ReportViewer.tsx b/src/features/Verify/ReportViewer.tsx
index 2e68e03680e..1369efdb28c 100644
--- a/src/features/Verify/ReportViewer.tsx
+++ b/src/features/Verify/ReportViewer.tsx
@@ -61,6 +61,8 @@ import {
filenameFromUrl,
markdownTextEvidenceTypes,
} from './components/MarkdownEvidence';
+import { readVisualizationManifest } from './components/visualization';
+import { VisualizationRenderer } from './components/VisualizationRenderer';
import { useVerifyReportBundle } from './hooks';
import {
buildCheckRows,
@@ -1373,6 +1375,7 @@ const CheckRow = memo<{ defaultOpen: boolean; row: CheckRowData }>(({ defaultOpe
const meta = VERDICT_META[state];
const evidence = result?.evidence ?? [];
const evidenceCount = evidence.length;
+ const visualization = readVisualizationManifest(result?.metadata);
// An agent-authored plan item records how it meant to check this and what it
// expected to see (prose), plus the evidence media it is required to produce
// (a closed set the executor's coverage gate enforces).
@@ -1391,6 +1394,7 @@ const CheckRow = memo<{ defaultOpen: boolean; row: CheckRowData }>(({ defaultOpe
const hasBody =
Boolean(result?.toulmin?.evidence) ||
Boolean(result?.suggestion) ||
+ Boolean(visualization) ||
Boolean(planConfig.method) ||
Boolean(planConfig.expected) ||
requiredEvidence.length > 0 ||
@@ -1495,6 +1499,7 @@ const CheckRow = memo<{ defaultOpen: boolean; row: CheckRowData }>(({ defaultOpe
<p className={styles.reasoning}>{result.toulmin.evidence}</p>
)}
{result?.suggestion && <p className={styles.suggestion}>{result.suggestion}</p>}
+ {visualization && <VisualizationRenderer manifest={visualization} />}
{evidenceCount > 0 && (
<>
<div className={styles.evidenceList}>
diff --git a/src/features/Verify/components/VisualizationRenderer.tsx b/src/features/Verify/components/VisualizationRenderer.tsx
new file mode 100644
index 00000000000..bbefde3a5a5
--- /dev/null
+++ b/src/features/Verify/components/VisualizationRenderer.tsx
@@ -0,0 +1,762 @@
+'use client';
+
+import type {
+ VerifyBarChartView,
+ VerifyHeatmapView,
+ VerifyLineChartView,
+ VerifyMetricComparisonView,
+ VerifyScatterPlotView,
+ VerifyTableView,
+ VerifyVisualizationDataset,
+ VerifyVisualizationManifest,
+} from '@lobechat/types';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ArrowDownRight, ArrowUpRight, ChartNoAxesCombined } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { Fragment, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ datasetForView,
+ fieldLabel,
+ fieldUnit,
+ metricComparisonDelta,
+ numberCell,
+ stringCell,
+ tableHighlightRows,
+} from './visualization';
+
+const styles = createStaticStyles(({ css }) => ({
+ axisLabel: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ badge: css`
+ display: inline-flex;
+ gap: 3px;
+ align-items: center;
+
+ padding-block: 1px;
+ padding-inline: 5px;
+ border-radius: 999px;
+
+ font-size: 11px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorSuccess};
+
+ background: ${cssVar.colorSuccessBg};
+ `,
+ badgeWorse: css`
+ color: ${cssVar.colorError};
+ background: ${cssVar.colorErrorBg};
+ `,
+ bar: css`
+ overflow: hidden;
+ height: 6px;
+ border-radius: 999px;
+ background: ${cssVar.colorFillSecondary};
+ `,
+ barChartLabel: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ barAfter: css`
+ height: 100%;
+ border-radius: inherit;
+ background: ${cssVar.colorInfo};
+ `,
+ barBefore: css`
+ height: 100%;
+ border-radius: inherit;
+ background: ${cssVar.colorTextQuaternary};
+ `,
+ body: css`
+ min-width: 0;
+ padding: 14px;
+ `,
+ card: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorBgContainer};
+ `,
+ chart: css`
+ display: block;
+ width: 100%;
+ min-height: 180px;
+ `,
+ context: css`
+ padding-block: 8px 10px;
+ padding-inline: 14px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ delta: css`
+ display: inline-flex;
+ gap: 3px;
+ align-items: center;
+
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorSuccess};
+ `,
+ deltaWorse: css`
+ color: ${cssVar.colorError};
+ `,
+ header: css`
+ padding-block: 10px;
+ padding-inline: 14px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ heatmap: css`
+ display: grid;
+ gap: 3px;
+ align-items: center;
+ `,
+ heatmapCell: css`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ min-height: 34px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ font-size: 11px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ `,
+ metric: css`
+ display: grid;
+ grid-template-columns: minmax(120px, 1fr) minmax(240px, 2.4fr) auto;
+ gap: 16px;
+ align-items: center;
+
+ padding-block: 12px;
+ padding-inline: 14px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+
+ @media (width <= 640px) {
+ grid-template-columns: 1fr auto;
+ }
+ `,
+ metricName: css`
+ min-width: 0;
+ font-weight: 500;
+ `,
+ sample: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ table: css`
+ border-collapse: collapse;
+ width: 100%;
+
+ th,
+ td {
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ text-align: start;
+ white-space: nowrap;
+ }
+
+ th {
+ font-size: 11px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ td {
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ }
+ `,
+ tableBest: css`
+ font-weight: 700;
+ color: ${cssVar.colorInfo};
+ background: ${cssVar.colorInfoBg};
+ `,
+ tableBestBadge: css`
+ margin-inline-start: 5px;
+ padding-block: 1px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 9px;
+ font-weight: 700;
+ color: ${cssVar.colorInfo};
+
+ background: ${cssVar.colorInfoBgHover};
+ `,
+ tableScroll: css`
+ overflow-x: auto;
+ `,
+ target: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ values: css`
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+
+ @media (width <= 640px) {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ }
+ `,
+ valueText: css`
+ display: flex;
+ justify-content: space-between;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ `,
+}));
+
+const SERIES_COLORS = [
+ cssVar.colorInfo,
+ cssVar.colorWarning,
+ cssVar.colorSuccess,
+ cssVar.colorInfo,
+ cssVar.colorError,
+];
+
+const lineSeriesColor = (style: VerifyLineChartView['encoding']['series'][number]['style']) => {
+ if (style === 'muted') return cssVar.colorTextQuaternary;
+ if (style === 'accent') return cssVar.colorWarning;
+ return cssVar.colorInfo;
+};
+
+const formatValue = (value: number, unit?: string) => {
+ const absolute = Math.abs(value);
+ const maximumFractionDigits = absolute >= 100 ? 0 : absolute >= 10 ? 1 : 2;
+ return `${new Intl.NumberFormat(undefined, { maximumFractionDigits }).format(value)}${unit ? ` ${unit}` : ''}`;
+};
+
+const extent = (values: number[]) => {
+ const minimum = Math.min(...values);
+ const maximum = Math.max(...values);
+ return minimum === maximum ? [minimum - 1, maximum + 1] : [minimum, maximum];
+};
+
+const scale = (value: number, domain: number[], range: number[]) =>
+ range[0] + ((value - domain[0]) / (domain[1] - domain[0])) * (range[1] - range[0]);
+
+const ViewCard = memo<{
+ children: ReactNode;
+ context?: string;
+ title?: string;
+}>(({ children, context, title }) => {
+ const { t } = useTranslation('verify');
+ return (
+ <div className={styles.card}>
+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>
+ <Icon icon={ChartNoAxesCombined} size={15} />
+ <Text strong>{title ?? t('report.visualization.title')}</Text>
+ </Flexbox>
+ {children}
+ {context && <div className={styles.context}>{context}</div>}
+ </div>
+ );
+});
+
+ViewCard.displayName = 'ViewCard';
+
+const MetricComparisonRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyMetricComparisonView;
+}>(({ dataset, view }) => {
+ const { t } = useTranslation('verify');
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ {dataset.rows.map((row, index) => {
+ const before = numberCell(row, view.encoding.before);
+ const after = numberCell(row, view.encoding.after);
+ if (before === null || after === null) return null;
+ const maximum = Math.max(Math.abs(before), Math.abs(after), 0.000_001);
+ const direction = view.encoding.direction
+ ? stringCell(row, view.encoding.direction)
+ : 'lower';
+ const improved = direction === 'higher' ? after >= before : after <= before;
+ const delta = before === 0 ? null : ((after - before) / Math.abs(before)) * 100;
+ const improvement = delta === null ? null : direction === 'higher' ? delta : -delta;
+ const target = view.encoding.target ? numberCell(row, view.encoding.target) : null;
+ const targetMet =
+ target === null ? null : direction === 'higher' ? after >= target : after <= target;
+ const unit = view.encoding.unit
+ ? (stringCell(row, view.encoding.unit) ?? undefined)
+ : fieldUnit(dataset, view.encoding.after);
+ const DeltaIcon = after <= before ? ArrowDownRight : ArrowUpRight;
+
+ return (
+ <div className={styles.metric} key={`${stringCell(row, view.encoding.label)}-${index}`}>
+ <Flexbox gap={2}>
+ <span className={styles.metricName}>
+ {stringCell(row, view.encoding.label) ?? t('report.visualization.unnamed')}
+ </span>
+ <Flexbox horizontal gap={8}>
+ {view.encoding.statistic && (
+ <span className={styles.sample}>{stringCell(row, view.encoding.statistic)}</span>
+ )}
+ {(view.encoding.beforeSamples || view.encoding.afterSamples) && (
+ <span className={styles.sample}>
+ n=
+ {view.encoding.beforeSamples
+ ? (numberCell(row, view.encoding.beforeSamples) ?? 'โ€“')
+ : 'โ€“'}{' '}
+ โ†’{' '}
+ {view.encoding.afterSamples
+ ? (numberCell(row, view.encoding.afterSamples) ?? 'โ€“')
+ : 'โ€“'}
+ </span>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <div className={styles.values}>
+ {(
+ [
+ ['before', before, styles.barBefore],
+ ['after', after, styles.barAfter],
+ ] as const
+ ).map(([role, value, barClass]) => (
+ <Flexbox gap={5} key={role}>
+ <span className={styles.valueText}>
+ <span>{t(`report.visualization.${role}`)}</span>
+ <strong>{formatValue(value, unit)}</strong>
+ </span>
+ <div className={styles.bar}>
+ <div
+ className={barClass}
+ style={{ width: `${Math.max(3, (Math.abs(value) / maximum) * 100)}%` }}
+ />
+ </div>
+ </Flexbox>
+ ))}
+ </div>
+ <Flexbox align={'flex-end'} gap={2}>
+ {improvement !== null && (
+ <span className={cx(styles.delta, !improved && styles.deltaWorse)}>
+ <Icon icon={DeltaIcon} size={13} />
+ {Math.abs(improvement).toFixed(1)}%
+ </span>
+ )}
+ {target !== null && (
+ <span className={styles.target}>
+ {t(
+ targetMet
+ ? 'report.visualization.targetMet'
+ : 'report.visualization.targetMissed',
+ { value: formatValue(target, unit) },
+ )}
+ </span>
+ )}
+ </Flexbox>
+ </div>
+ );
+ })}
+ </ViewCard>
+ );
+});
+
+MetricComparisonRenderer.displayName = 'MetricComparisonRenderer';
+
+const LineChartRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyLineChartView;
+}>(({ dataset, view }) => {
+ const points = dataset.rows
+ .map((row) => ({ row, x: numberCell(row, view.encoding.x) }))
+ .filter(
+ (point): point is { row: (typeof dataset.rows)[number]; x: number } => point.x !== null,
+ );
+ const yValues = points.flatMap(({ row }) =>
+ view.encoding.series
+ .map((series) => numberCell(row, series.field))
+ .filter((value): value is number => value !== null && Number.isFinite(value)),
+ );
+ if (points.length === 0 || yValues.length === 0) return null;
+ const xDomain = extent(points.map((point) => point.x));
+ const yDomain = extent(yValues);
+
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ <div className={styles.body}>
+ <svg
+ aria-label={view.title ?? 'Line chart'}
+ className={styles.chart}
+ role={'img'}
+ viewBox={'0 0 640 230'}
+ >
+ <line stroke={cssVar.colorBorderSecondary} x1={48} x2={620} y1={198} y2={198} />
+ <line stroke={cssVar.colorBorderSecondary} x1={48} x2={48} y1={12} y2={198} />
+ {view.encoding.series.map((series, seriesIndex) => {
+ const semanticStyle =
+ series.style ??
+ (view.encoding.series.length > 1 && seriesIndex === 0
+ ? 'muted'
+ : seriesIndex > 1
+ ? 'accent'
+ : 'primary');
+ const color = lineSeriesColor(semanticStyle);
+ const coordinates = points
+ .map(({ row, x }) => {
+ const y = numberCell(row, series.field);
+ return y === null
+ ? null
+ : `${scale(x, xDomain, [48, 620])},${scale(y, yDomain, [198, 12])}`;
+ })
+ .filter(Boolean)
+ .join(' ');
+ return (
+ <g key={series.field}>
+ <polyline
+ fill={'none'}
+ points={coordinates}
+ stroke={color}
+ strokeDasharray={semanticStyle === 'muted' ? '5 4' : undefined}
+ strokeLinejoin={'round'}
+ strokeWidth={semanticStyle === 'muted' ? 1.5 : 2.5}
+ />
+ <text fill={color} fontSize={11} x={54 + seriesIndex * 130} y={18}>
+ {series.label ?? fieldLabel(dataset, series.field)}
+ </text>
+ </g>
+ );
+ })}
+ <text fill={cssVar.colorTextTertiary} fontSize={10} textAnchor={'middle'} x={334} y={222}>
+ {view.encoding.xLabel ?? fieldLabel(dataset, view.encoding.x)}
+ </text>
+ <text fill={cssVar.colorTextTertiary} fontSize={10} x={4} y={108}>
+ {view.encoding.yLabel ?? ''}
+ </text>
+ </svg>
+ </div>
+ </ViewCard>
+ );
+});
+
+LineChartRenderer.displayName = 'LineChartRenderer';
+
+const ScatterPlotRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyScatterPlotView;
+}>(({ dataset, view }) => {
+ const points = dataset.rows
+ .map((row) => ({
+ category: view.encoding.color ? stringCell(row, view.encoding.color) : null,
+ label: view.encoding.label ? stringCell(row, view.encoding.label) : null,
+ x: numberCell(row, view.encoding.x),
+ y: numberCell(row, view.encoding.y),
+ }))
+ .filter(
+ (point): point is typeof point & { x: number; y: number } =>
+ point.x !== null && point.y !== null,
+ );
+ if (points.length === 0) return null;
+ const xDomain = extent(points.map((point) => point.x));
+ const yDomain = extent(points.map((point) => point.y));
+ const categories = [...new Set(points.map((point) => point.category).filter(Boolean))];
+
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ <div className={styles.body}>
+ <svg
+ aria-label={view.title ?? 'Scatter plot'}
+ className={styles.chart}
+ role={'img'}
+ viewBox={'0 0 640 230'}
+ >
+ <line stroke={cssVar.colorBorderSecondary} x1={48} x2={620} y1={198} y2={198} />
+ <line stroke={cssVar.colorBorderSecondary} x1={48} x2={48} y1={12} y2={198} />
+ {points.map((point, index) => {
+ const colorIndex = point.category ? categories.indexOf(point.category) : 0;
+ return (
+ <circle
+ cx={scale(point.x, xDomain, [48, 620])}
+ cy={scale(point.y, yDomain, [198, 12])}
+ fill={SERIES_COLORS[Math.max(0, colorIndex) % SERIES_COLORS.length]}
+ key={`${point.label}-${index}`}
+ opacity={0.75}
+ r={4}
+ >
+ <title>{`${point.label ?? index}: ${point.x}, ${point.y}${point.category ? ` ยท ${point.category}` : ''}`}</title>
+ </circle>
+ );
+ })}
+ <text fill={cssVar.colorTextTertiary} fontSize={10} textAnchor={'middle'} x={334} y={222}>
+ {view.encoding.xLabel ?? fieldLabel(dataset, view.encoding.x)}
+ </text>
+ <text fill={cssVar.colorTextTertiary} fontSize={10} x={4} y={108}>
+ {view.encoding.yLabel ?? fieldLabel(dataset, view.encoding.y)}
+ </text>
+ </svg>
+ </div>
+ </ViewCard>
+ );
+});
+
+ScatterPlotRenderer.displayName = 'ScatterPlotRenderer';
+
+const HeatmapRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyHeatmapView;
+}>(({ dataset, view }) => {
+ const xValues = [...new Set(dataset.rows.map((row) => stringCell(row, view.encoding.x)))].filter(
+ Boolean,
+ ) as string[];
+ const yValues = [...new Set(dataset.rows.map((row) => stringCell(row, view.encoding.y)))].filter(
+ Boolean,
+ ) as string[];
+ const values = dataset.rows
+ .map((row) => numberCell(row, view.encoding.value))
+ .filter((value): value is number => value !== null && Number.isFinite(value));
+ if (xValues.length === 0 || yValues.length === 0 || values.length === 0) return null;
+ const minimum = Math.min(...values);
+ const maximum = Math.max(...values);
+ const span = Math.max(maximum - minimum, 0.000_001);
+ const byCoordinate = new Map(
+ dataset.rows.map((row) => [
+ `${stringCell(row, view.encoding.x)}\0${stringCell(row, view.encoding.y)}`,
+ numberCell(row, view.encoding.value),
+ ]),
+ );
+
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ <div className={styles.body}>
+ <div
+ className={styles.heatmap}
+ style={{ gridTemplateColumns: `minmax(64px, auto) repeat(${xValues.length}, 1fr)` }}
+ >
+ <span />
+ {xValues.map((value) => (
+ <span className={styles.axisLabel} key={value} style={{ textAlign: 'center' }}>
+ {value}
+ </span>
+ ))}
+ {yValues.map((y) => (
+ <Fragment key={y}>
+ <span className={styles.axisLabel}>{y}</span>
+ {xValues.map((x) => {
+ const value = byCoordinate.get(`${x}\0${y}`);
+ const intensity =
+ typeof value === 'number' ? 0.14 + ((value - minimum) / span) * 0.76 : 0;
+ return (
+ <span
+ className={styles.heatmapCell}
+ key={`${x}-${y}`}
+ style={{
+ background: `color-mix(in srgb, ${cssVar.colorInfo} ${intensity * 100}%, ${cssVar.colorBgContainer})`,
+ color: intensity > 0.58 ? cssVar.colorTextLightSolid : cssVar.colorText,
+ }}
+ >
+ {typeof value === 'number' ? formatValue(value) : 'โ€“'}
+ </span>
+ );
+ })}
+ </Fragment>
+ ))}
+ </div>
+ </div>
+ </ViewCard>
+ );
+});
+
+HeatmapRenderer.displayName = 'HeatmapRenderer';
+
+const BarChartRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyBarChartView;
+}>(({ dataset, view }) => {
+ const categories = dataset.rows
+ .map((row) => stringCell(row, view.encoding.category))
+ .filter((value): value is string => value !== null);
+ const values = dataset.rows.flatMap((row) =>
+ view.encoding.series
+ .map((series) => numberCell(row, series.field))
+ .filter((value): value is number => value !== null),
+ );
+ if (categories.length === 0 || values.length === 0) return null;
+ const maximum = Math.max(...values, 0.000_001);
+ const plotWidth = 552;
+ const groupWidth = plotWidth / dataset.rows.length;
+ const barWidth = Math.min(30, (groupWidth - 12) / view.encoding.series.length);
+
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ <div className={styles.body}>
+ <svg
+ aria-label={view.title ?? 'Bar chart'}
+ className={styles.chart}
+ role={'img'}
+ viewBox={'0 0 640 250'}
+ >
+ <line stroke={cssVar.colorBorderSecondary} x1={56} x2={608} y1={205} y2={205} />
+ {dataset.rows.map((row, rowIndex) => {
+ const groupStart = 56 + rowIndex * groupWidth;
+ return (
+ <g key={`${categories[rowIndex]}-${rowIndex}`}>
+ {view.encoding.series.map((series, seriesIndex) => {
+ const value = numberCell(row, series.field);
+ if (value === null) return null;
+ const height = (value / maximum) * 172;
+ return (
+ <rect
+ fill={SERIES_COLORS[seriesIndex % SERIES_COLORS.length]}
+ height={height}
+ key={series.field}
+ rx={3}
+ width={barWidth}
+ x={groupStart + 6 + seriesIndex * barWidth}
+ y={205 - height}
+ >
+ <title>{`${categories[rowIndex]} ยท ${series.label ?? fieldLabel(dataset, series.field)}: ${formatValue(value, fieldUnit(dataset, series.field))}`}</title>
+ </rect>
+ );
+ })}
+ <text
+ className={styles.barChartLabel}
+ fill={cssVar.colorTextSecondary}
+ textAnchor={'middle'}
+ x={groupStart + groupWidth / 2}
+ y={224}
+ >
+ {categories[rowIndex]}
+ </text>
+ </g>
+ );
+ })}
+ {view.encoding.series.map((series, index) => (
+ <text
+ fill={SERIES_COLORS[index % SERIES_COLORS.length]}
+ fontSize={11}
+ key={series.field}
+ x={58 + index * 140}
+ y={16}
+ >
+ {series.label ?? fieldLabel(dataset, series.field)}
+ </text>
+ ))}
+ {view.encoding.valueLabel && (
+ <text fill={cssVar.colorTextTertiary} fontSize={10} x={4} y={112}>
+ {view.encoding.valueLabel}
+ </text>
+ )}
+ </svg>
+ </div>
+ </ViewCard>
+ );
+});
+
+BarChartRenderer.displayName = 'BarChartRenderer';
+
+const TableRenderer = memo<{
+ dataset: VerifyVisualizationDataset;
+ view: VerifyTableView;
+}>(({ dataset, view }) => {
+ const requested = view.encoding?.columns;
+ const fields = requested
+ ? requested.flatMap((key) => dataset.fields.filter((field) => field.key === key))
+ : dataset.fields;
+ const highlightedRows = new Map(
+ view.encoding?.highlights?.map((highlight) => [
+ highlight.field,
+ tableHighlightRows(dataset, highlight.field, highlight.mode),
+ ]),
+ );
+ return (
+ <ViewCard context={view.context} title={view.title}>
+ <div className={styles.tableScroll}>
+ <table className={styles.table}>
+ <thead>
+ <tr>
+ {fields.map((field) => (
+ <th key={field.key}>{field.label ?? field.key}</th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {dataset.rows.map((row, index) => (
+ <tr key={index}>
+ {fields.map((field) => {
+ const isBest = highlightedRows.get(field.key)?.has(index) ?? false;
+ return (
+ <td className={isBest ? styles.tableBest : undefined} key={field.key}>
+ {String(row[field.key] ?? 'โ€“')}
+ {isBest && <span className={styles.tableBestBadge}>SOTA</span>}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </ViewCard>
+ );
+});
+
+TableRenderer.displayName = 'TableRenderer';
+
+export const VisualizationDeltaBadge = memo<{
+ manifest: VerifyVisualizationManifest;
+}>(({ manifest }) => {
+ const view = manifest.views.find((item) => item.type === 'metric-comparison');
+ if (!view || view.type !== 'metric-comparison') return null;
+ const dataset = datasetForView(manifest, view);
+ if (!dataset) return null;
+ const delta = metricComparisonDelta(dataset, view);
+ if (!delta) return null;
+ const improved = delta.improvement >= 0;
+ const DeltaIcon = delta.after <= delta.before ? ArrowDownRight : ArrowUpRight;
+ return (
+ <span className={cx(styles.badge, !improved && styles.badgeWorse)}>
+ <Icon icon={DeltaIcon} size={11} />
+ {Math.abs(delta.improvement).toFixed(1)}%
+ </span>
+ );
+});
+
+VisualizationDeltaBadge.displayName = 'VisualizationDeltaBadge';
+
+export const VisualizationRenderer = memo<{
+ manifest: VerifyVisualizationManifest;
+}>(({ manifest }) => (
+ <Flexbox gap={12}>
+ {manifest.views.map((view) => {
+ const dataset = datasetForView(manifest, view);
+ if (!dataset) return null;
+ switch (view.type) {
+ case 'bar-chart': {
+ return <BarChartRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ case 'heatmap': {
+ return <HeatmapRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ case 'line-chart': {
+ return <LineChartRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ case 'metric-comparison': {
+ return <MetricComparisonRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ case 'scatter-plot': {
+ return <ScatterPlotRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ case 'table': {
+ return <TableRenderer dataset={dataset} key={view.id} view={view} />;
+ }
+ }
+ })}
+ </Flexbox>
+));
+
+VisualizationRenderer.displayName = 'VisualizationRenderer';
diff --git a/src/features/Verify/components/visualization.test.ts b/src/features/Verify/components/visualization.test.ts
new file mode 100644
index 00000000000..755a1d9ec5d
--- /dev/null
+++ b/src/features/Verify/components/visualization.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ hasRenderableEvidence,
+ metricComparisonDelta,
+ readVisualizationManifest,
+ tableHighlightRows,
+} from './visualization';
+
+const metadata = {
+ visualization: {
+ datasets: [
+ {
+ fields: [
+ { key: 'name', type: 'string' },
+ { key: 'before', type: 'number' },
+ { key: 'after', type: 'number' },
+ ],
+ id: 'metrics',
+ rows: [{ after: 25, before: 250, name: 'GC time' }],
+ },
+ ],
+ schemaVersion: 1,
+ views: [
+ {
+ dataset: 'metrics',
+ encoding: { after: 'after', before: 'before', label: 'name' },
+ id: 'comparison',
+ type: 'metric-comparison',
+ version: 1,
+ },
+ ],
+ },
+};
+
+describe('readVisualizationManifest', () => {
+ it('reads a supported, versioned manifest', () => {
+ const manifest = readVisualizationManifest(metadata);
+
+ expect(manifest?.datasets).toHaveLength(1);
+ expect(manifest?.views[0]?.type).toBe('metric-comparison');
+ });
+
+ it('ignores malformed or unsupported metadata', () => {
+ expect(readVisualizationManifest(null)).toBe(null);
+ expect(
+ readVisualizationManifest({
+ visualization: { ...metadata.visualization, schemaVersion: 2 },
+ }),
+ ).toBe(null);
+ });
+
+ it.each([
+ ['bar-chart', {}],
+ ['line-chart', { series: [], x: 'name' }],
+ ['scatter-plot', { x: 'before', y: 'missing' }],
+ ['table', { columns: ['missing'] }],
+ ])('rejects a persisted %s view with a malformed encoding', (type, encoding) => {
+ expect(
+ readVisualizationManifest({
+ visualization: {
+ ...metadata.visualization,
+ views: [{ dataset: 'metrics', encoding, id: 'invalid', type, version: 1 }],
+ },
+ }),
+ ).toBe(null);
+ });
+
+ it('rejects malformed persisted datasets instead of partially rendering them', () => {
+ expect(
+ readVisualizationManifest({
+ visualization: {
+ ...metadata.visualization,
+ datasets: [
+ ...metadata.visualization.datasets,
+ {
+ fields: [{ key: 'score', type: 'number' }],
+ id: 'broken',
+ rows: [{ unknown: 1 }],
+ },
+ ],
+ },
+ }),
+ ).toBe(null);
+ });
+
+ it('computes the first metric improvement for the collapsed check row', () => {
+ const manifest = readVisualizationManifest(metadata)!;
+ const view = manifest.views[0];
+ if (view.type !== 'metric-comparison') throw new Error('unexpected fixture view');
+
+ expect(metricComparisonDelta(manifest.datasets[0], view)).toEqual({
+ after: 25,
+ before: 250,
+ improvement: 90,
+ });
+ });
+
+ it('selects every tied SOTA row for max and min table metrics', () => {
+ const dataset = {
+ fields: [{ key: 'score', type: 'number' as const }],
+ id: 'models',
+ rows: [{ score: 92 }, { score: 88 }, { score: 92 }],
+ };
+
+ expect([...tableHighlightRows(dataset, 'score', 'max')]).toEqual([0, 2]);
+ expect([...tableHighlightRows(dataset, 'score', 'min')]).toEqual([1]);
+ });
+
+ it('treats a structured visualization as review evidence without uploaded files', () => {
+ const manifest = readVisualizationManifest(metadata);
+
+ expect(hasRenderableEvidence(0, manifest)).toBe(true);
+ expect(hasRenderableEvidence(0, null)).toBe(false);
+ expect(hasRenderableEvidence(1, null)).toBe(true);
+ });
+});
diff --git a/src/features/Verify/components/visualization.ts b/src/features/Verify/components/visualization.ts
new file mode 100644
index 00000000000..2a3a88c4dac
--- /dev/null
+++ b/src/features/Verify/components/visualization.ts
@@ -0,0 +1,259 @@
+import type {
+ VerifyCheckResultMetadata,
+ VerifyVisualizationDataset,
+ VerifyVisualizationManifest,
+ VerifyVisualizationView,
+} from '@lobechat/types';
+import { isPlainRecord } from '@lobechat/utils/object';
+
+const VIEW_TYPES = new Set([
+ 'bar-chart',
+ 'heatmap',
+ 'line-chart',
+ 'metric-comparison',
+ 'scatter-plot',
+ 'table',
+]);
+const FIELD_TYPES = new Set(['boolean', 'category', 'number', 'string', 'temporal']);
+
+const isOptionalString = (value: unknown) =>
+ value === undefined || (typeof value === 'string' && value.length > 0);
+const isCell = (value: unknown) =>
+ value === null || ['boolean', 'number', 'string'].includes(typeof value);
+
+const hasFieldReference = (
+ encoding: Record<string, unknown>,
+ key: string,
+ fieldKeys: Set<string>,
+ optional = false,
+) =>
+ optional && encoding[key] === undefined
+ ? true
+ : typeof encoding[key] === 'string' && fieldKeys.has(encoding[key]);
+
+const hasValidSeries = (
+ encoding: Record<string, unknown>,
+ fieldKeys: Set<string>,
+ styles = false,
+) =>
+ Array.isArray(encoding.series) &&
+ encoding.series.length > 0 &&
+ encoding.series.every(
+ (item) =>
+ isPlainRecord(item) &&
+ hasFieldReference(item, 'field', fieldKeys) &&
+ isOptionalString(item.label) &&
+ (!styles ||
+ item.style === undefined ||
+ item.style === 'accent' ||
+ item.style === 'muted' ||
+ item.style === 'primary'),
+ );
+
+const hasValidEncoding = (view: Record<string, unknown>, fieldKeys: Set<string>) => {
+ if (view.type === 'table' && view.encoding === undefined) return true;
+ if (!isPlainRecord(view.encoding)) return false;
+ const encoding = view.encoding;
+
+ switch (view.type) {
+ case 'bar-chart': {
+ return (
+ hasFieldReference(encoding, 'category', fieldKeys) &&
+ hasValidSeries(encoding, fieldKeys) &&
+ isOptionalString(encoding.valueLabel)
+ );
+ }
+ case 'heatmap': {
+ return (
+ hasFieldReference(encoding, 'x', fieldKeys) &&
+ hasFieldReference(encoding, 'y', fieldKeys) &&
+ hasFieldReference(encoding, 'value', fieldKeys)
+ );
+ }
+ case 'line-chart': {
+ return (
+ hasFieldReference(encoding, 'x', fieldKeys) &&
+ hasValidSeries(encoding, fieldKeys, true) &&
+ isOptionalString(encoding.xLabel) &&
+ isOptionalString(encoding.yLabel)
+ );
+ }
+ case 'metric-comparison': {
+ return (
+ hasFieldReference(encoding, 'label', fieldKeys) &&
+ hasFieldReference(encoding, 'before', fieldKeys) &&
+ hasFieldReference(encoding, 'after', fieldKeys) &&
+ ['afterSamples', 'beforeSamples', 'direction', 'statistic', 'target', 'unit'].every((key) =>
+ hasFieldReference(encoding, key, fieldKeys, true),
+ )
+ );
+ }
+ case 'scatter-plot': {
+ return (
+ hasFieldReference(encoding, 'x', fieldKeys) &&
+ hasFieldReference(encoding, 'y', fieldKeys) &&
+ hasFieldReference(encoding, 'color', fieldKeys, true) &&
+ hasFieldReference(encoding, 'label', fieldKeys, true) &&
+ isOptionalString(encoding.xLabel) &&
+ isOptionalString(encoding.yLabel)
+ );
+ }
+ case 'table': {
+ const columnsValid =
+ encoding.columns === undefined ||
+ (Array.isArray(encoding.columns) &&
+ encoding.columns.length > 0 &&
+ encoding.columns.every((field) => typeof field === 'string' && fieldKeys.has(field)));
+ const highlightsValid =
+ encoding.highlights === undefined ||
+ (Array.isArray(encoding.highlights) &&
+ encoding.highlights.every(
+ (item) =>
+ isPlainRecord(item) &&
+ hasFieldReference(item, 'field', fieldKeys) &&
+ (item.mode === 'max' || item.mode === 'min'),
+ ));
+ return columnsValid && highlightsValid;
+ }
+ default: {
+ return false;
+ }
+ }
+};
+
+/** Defensive parser: open historical metadata must never crash a report page. */
+export const readVisualizationManifest = (
+ metadata: VerifyCheckResultMetadata | unknown,
+): VerifyVisualizationManifest | null => {
+ if (!isPlainRecord(metadata) || !isPlainRecord(metadata.visualization)) return null;
+ const manifest = metadata.visualization;
+ if (
+ manifest.schemaVersion !== 1 ||
+ !Array.isArray(manifest.datasets) ||
+ !Array.isArray(manifest.views)
+ )
+ return null;
+
+ const datasets = manifest.datasets.filter((dataset): dataset is VerifyVisualizationDataset => {
+ if (
+ !isPlainRecord(dataset) ||
+ typeof dataset.id !== 'string' ||
+ !Array.isArray(dataset.fields) ||
+ !Array.isArray(dataset.rows)
+ )
+ return false;
+ const fieldsValid = dataset.fields.every(
+ (field) =>
+ isPlainRecord(field) &&
+ typeof field.key === 'string' &&
+ typeof field.type === 'string' &&
+ FIELD_TYPES.has(field.type) &&
+ isOptionalString(field.label) &&
+ isOptionalString(field.unit),
+ );
+ const fieldKeys = new Set(
+ dataset.fields.flatMap((field) =>
+ isPlainRecord(field) && typeof field.key === 'string' ? [field.key] : [],
+ ),
+ );
+ return (
+ fieldsValid &&
+ fieldKeys.size === dataset.fields.length &&
+ dataset.rows.every(
+ (row) =>
+ isPlainRecord(row) &&
+ Object.entries(row).every(([key, value]) => fieldKeys.has(key) && isCell(value)),
+ )
+ );
+ });
+ if (datasets.length !== manifest.datasets.length) return null;
+ const datasetIds = new Set(datasets.map((dataset) => dataset.id));
+ if (datasetIds.size !== datasets.length) return null;
+ const views = manifest.views.filter(
+ (view): view is VerifyVisualizationView =>
+ isPlainRecord(view) &&
+ typeof view.id === 'string' &&
+ typeof view.type === 'string' &&
+ VIEW_TYPES.has(view.type) &&
+ view.version === 1 &&
+ typeof view.dataset === 'string' &&
+ datasetIds.has(view.dataset) &&
+ isOptionalString(view.context) &&
+ isOptionalString(view.title) &&
+ hasValidEncoding(
+ view,
+ new Set(
+ datasets.find((dataset) => dataset.id === view.dataset)!.fields.map((field) => field.key),
+ ),
+ ),
+ );
+ if (
+ datasets.length === 0 ||
+ views.length === 0 ||
+ views.length !== manifest.views.length ||
+ new Set(views.map((view) => view.id)).size !== views.length
+ )
+ return null;
+
+ return { datasets, schemaVersion: 1, views };
+};
+
+export const datasetForView = (
+ manifest: VerifyVisualizationManifest,
+ view: VerifyVisualizationView,
+) => manifest.datasets.find((dataset) => dataset.id === view.dataset);
+
+/** Structured views are first-class review evidence, even without uploaded files. */
+export const hasRenderableEvidence = (
+ fileEvidenceCount: number,
+ visualization: VerifyVisualizationManifest | null,
+) => fileEvidenceCount > 0 || visualization !== null;
+
+export const fieldLabel = (dataset: VerifyVisualizationDataset, key: string) => {
+ const field = dataset.fields.find((item) => item.key === key);
+ return field?.label ?? key;
+};
+
+export const fieldUnit = (dataset: VerifyVisualizationDataset, key: string) =>
+ dataset.fields.find((item) => item.key === key)?.unit;
+
+export const numberCell = (row: Record<string, unknown>, key: string): number | null => {
+ const value = row[key];
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+};
+
+export const stringCell = (row: Record<string, unknown>, key: string): string | null => {
+ const value = row[key];
+ return typeof value === 'string' || typeof value === 'number' ? String(value) : null;
+};
+
+export const metricComparisonDelta = (
+ dataset: VerifyVisualizationDataset,
+ view: Extract<VerifyVisualizationView, { type: 'metric-comparison' }>,
+) => {
+ const row = dataset.rows[0];
+ if (!row) return null;
+ const before = numberCell(row, view.encoding.before);
+ const after = numberCell(row, view.encoding.after);
+ if (before === null || after === null || before === 0) return null;
+ const direction = view.encoding.direction ? stringCell(row, view.encoding.direction) : 'lower';
+ const raw = ((after - before) / Math.abs(before)) * 100;
+ const improvement = direction === 'higher' ? raw : -raw;
+ return { after, before, improvement };
+};
+
+export const tableHighlightRows = (
+ dataset: VerifyVisualizationDataset,
+ field: string,
+ mode: 'max' | 'min',
+) => {
+ const values = dataset.rows
+ .map((row, index) => ({ index, value: numberCell(row, field) }))
+ .filter((item): item is { index: number; value: number } => item.value !== null);
+ if (values.length === 0) return new Set<number>();
+ const best =
+ mode === 'max'
+ ? Math.max(...values.map(({ value }) => value))
+ : Math.min(...values.map(({ value }) => value));
+ return new Set(values.filter(({ value }) => value === best).map(({ index }) => index));
+};