Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Smart Results: chart, metrics, facts, cards, findings, verification and files renderers (#228)

Oleksandr Ivanchenkoac30aabb16b5
diff --git a/frontend/src/components/results/Cards.tsx b/frontend/src/components/results/Cards.tsx
new file mode 100644
index 00000000..4ff0dde8
--- /dev/null
+++ b/frontend/src/components/results/Cards.tsx
@@ -0,0 +1,62 @@
+import React from 'react';
+import { ExternalLink } from 'lucide-react';
+import { CardItem, CardsBlock, inRange, isHttpUrl, isText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+/** 3-12 link cards; a url must be http(s) or absent (plan §A.3). */
+export function validCards(raw: unknown): CardsBlock | null {
+ const b = parseCommon(raw, 'cards');
+ if (!b || !inRange(b.items, 3, 12) || !uniqueIds(b.items)) return null;
+ const items: CardItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ if (!isText(it.title) || !isText(it.description, 300, true)) return null;
+ const url = it.url === null || it.url === undefined ? null : isHttpUrl(it.url) ? it.url : undefined;
+ if (url === undefined) return null;
+ if (!Array.isArray(it.meta) || !it.meta.every((m) => isText(m, 40))) return null;
+ items.push({ id: it.id as string, title: it.title, url, description: it.description, meta: it.meta as string[] });
+ }
+ return { id: b.id, type: 'cards', title: b.title, source: b.source, provenance: b.provenance, items };
+}
+
+/** A link's domain, without a leading "www.", or the raw string if it doesn't parse. */
+function urlDomain(url: string): string {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return url;
+ }
+}
+
+/** Compact cards: title, description, and the link's domain. Links open in a new tab, http(s) only. */
+export const Cards: React.FC<RendererProps<CardsBlock>> = ({ block }) => (
+ <div data-smart-result="cards" data-block-id={block.id}>
+ <ul role="list" className="my-3.5 grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ {block.items.map((item) => {
+ const Wrapper = item.url ? 'a' : 'div';
+ const wrapperProps = item.url ? { href: item.url, target: '_blank', rel: 'noopener noreferrer' } : {};
+ return (
+ <li key={item.id} className="min-w-0">
+ <Wrapper
+ {...wrapperProps}
+ className="block h-full rounded-xl border border-zinc-800 bg-zinc-950/70 p-3 shadow-sm transition-colors motion-reduce:transition-none hover:border-zinc-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <h4 className="text-[13px] font-semibold leading-snug text-zinc-100 [overflow-wrap:anywhere]">{item.title}</h4>
+ {item.url && <ExternalLink size={12} className="mt-0.5 shrink-0 text-zinc-600" aria-hidden="true" />}
+ </div>
+ <p className="mt-1 text-xs leading-relaxed text-zinc-400 [overflow-wrap:anywhere]">{item.description}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-zinc-500">
+ {item.url && <span className="truncate">{urlDomain(item.url)}</span>}
+ {item.meta.map((m, i) => (
+ <span key={i} className="rounded border border-zinc-800 px-1.5 py-0.5">
+ {m}
+ </span>
+ ))}
+ </div>
+ </Wrapper>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+);
diff --git a/frontend/src/components/results/Chart.tsx b/frontend/src/components/results/Chart.tsx
new file mode 100644
index 00000000..fbadd2e1
--- /dev/null
+++ b/frontend/src/components/results/Chart.tsx
@@ -0,0 +1,379 @@
+import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
+import { ChartBlock, ChartPoint, ChartSeries, inRange, isNum, isObj, isText, optText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+const MAX_VALUE = 1e15;
+
+/** 1-4 series (unique by key) and 3-60 points, each with one cell/value per series (plan §A.3). */
+export function validChart(raw: unknown): ChartBlock | null {
+ const b = parseCommon(raw, 'chart');
+ if (!b) return null;
+ if (b.chart_kind !== 'line' && b.chart_kind !== 'bar') return null;
+ const x = b.x;
+ if (!isObj(x) || !isText(x.label) || (x.kind !== 'time' && x.kind !== 'category')) return null;
+ if (!inRange(b.series, 1, 4)) return null;
+ const series: ChartSeries[] = [];
+ const keys = new Set<string>();
+ for (const s of b.series as Record<string, unknown>[]) {
+ if (!isObj(s) || !isText(s.key, 60) || keys.has(s.key) || !isText(s.label)) return null;
+ const unit = optText(s.unit, 40);
+ if (unit === undefined) return null;
+ keys.add(s.key);
+ series.push({ key: s.key, label: s.label, unit });
+ }
+ // One shared Y axis means one unit: a chart whose series differ (EUR next to "rating (1-5)") would flatten
+ // the smaller one, so it abstains and the reply's own table shows instead (plan §A.3).
+ if (series.some((s) => s.unit !== series[0].unit)) return null;
+ if (!inRange(b.points, 3, 60) || !uniqueIds(b.points)) return null;
+ // A bar chart needs 5 or more rows (plan §A.3); a smaller table stays a comparison.
+ if (b.chart_kind === 'bar' && (b.points as unknown[]).length < 5) return null;
+ const points: ChartPoint[] = [];
+ for (const p of b.points as Record<string, unknown>[]) {
+ if (!isText(p.x)) return null;
+ if (!Array.isArray(p.cells) || p.cells.length !== series.length || !p.cells.every((c) => isText(c, 300, true))) return null;
+ // Finite and within what an SVG coordinate can carry: 1e308 turns every scaled y into NaN.
+ if (!Array.isArray(p.values) || p.values.length !== series.length || !p.values.every((v) => v === null || (isNum(v) && Math.abs(v) <= MAX_VALUE))) return null;
+ points.push({ id: p.id as string, x: p.x, cells: p.cells as string[], values: p.values as (number | null)[] });
+ }
+ const summary = optText(b.summary);
+ if (summary === undefined) return null;
+ return {
+ id: b.id,
+ type: 'chart',
+ title: b.title,
+ source: b.source,
+ provenance: b.provenance,
+ chart_kind: b.chart_kind,
+ x: { label: x.label, kind: x.kind },
+ series,
+ points,
+ summary,
+ };
+}
+
+const HEIGHT = 260;
+const PAD = { top: 16, right: 16, bottom: 36, left: 44 };
+const PLOT_H = HEIGHT - PAD.top - PAD.bottom;
+
+// Up to 4 series: told apart by shape/pattern as well as colour, never colour alone.
+const MARKERS: React.FC<{ cx: number; cy: number; size: number }>[] = [
+ ({ cx, cy, size }) => <circle cx={cx} cy={cy} r={size} />,
+ ({ cx, cy, size }) => <rect x={cx - size} y={cy - size} width={size * 2} height={size * 2} />,
+ ({ cx, cy, size }) => (
+ <polygon points={`${cx},${cy - size * 1.2} ${cx + size * 1.1},${cy + size} ${cx - size * 1.1},${cy + size}`} />
+ ),
+ ({ cx, cy, size }) => (
+ <polygon points={`${cx},${cy - size * 1.2} ${cx + size * 1.2},${cy} ${cx},${cy + size * 1.2} ${cx - size * 1.2},${cy}`} />
+ ),
+];
+const DASHES = [undefined, '6 3', '2 3', '8 2 2 2'];
+const SERIES_COLORS = ['#8270f5', '#38bdf8', '#34d399', '#fb923c'];
+
+function niceTicks(min: number, max: number, count: number): number[] {
+ if (min === max) {
+ min -= 1;
+ max += 1;
+ }
+ const span = max - min;
+ const step0 = span / count;
+ const mag = 10 ** Math.floor(Math.log10(step0));
+ const residual = step0 / mag;
+ const step = (residual > 5 ? 10 : residual > 2 ? 5 : residual > 1 ? 2 : 1) * mag;
+ const start = Math.floor(min / step) * step;
+ const ticks: number[] = [];
+ for (let v = start; v <= max + step / 2; v += step) ticks.push(Math.round(v * 1e6) / 1e6);
+ return ticks;
+}
+
+function fmtTick(n: number): string {
+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(n);
+}
+
+const BarPattern: React.FC<{ id: string; variant: number; color: string }> = ({ id, variant, color }) => {
+ if (variant === 0) return <pattern id={id} />; // solid fill, no pattern needed
+ if (variant === 1)
+ return (
+ <pattern id={id} width="6" height="6" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">
+ <rect width="6" height="6" fill={color} fillOpacity={0.35} />
+ <line x1="0" y1="0" x2="0" y2="6" stroke={color} strokeWidth="3" />
+ </pattern>
+ );
+ if (variant === 2)
+ return (
+ <pattern id={id} width="5" height="5" patternUnits="userSpaceOnUse">
+ <rect width="5" height="5" fill={color} fillOpacity={0.35} />
+ <circle cx="2.5" cy="2.5" r="1.1" fill={color} />
+ </pattern>
+ );
+ return (
+ <pattern id={id} width="6" height="6" patternUnits="userSpaceOnUse">
+ <rect width="6" height="6" fill={color} fillOpacity={0.35} />
+ <path d="M0 0L6 6M6 0L0 6" stroke={color} strokeWidth="1.2" />
+ </pattern>
+ );
+};
+
+/**
+ * A reply's table rendered as a hand-rolled SVG chart: line for a time axis, grouped bars for
+ * categories. Up to 4 series, told apart by marker shape or fill pattern, never colour alone. Every
+ * value comes verbatim from the block; axis gridlines are scale, not claims. A null value is a gap.
+ */
+export const Chart: React.FC<RendererProps<ChartBlock>> = ({ block }) => {
+ const uid = useId();
+ const [view, setView] = useState<'chart' | 'table'>('chart');
+ const [active, setActive] = useState<{ seriesIdx: number; pointIdx: number } | null>(null);
+ // Drawn at the card's real width (1 SVG unit = 1 px) so axis text stays readable on a 390 px phone.
+ const svgBox = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(640);
+ useEffect(() => {
+ const el = svgBox.current;
+ if (!el || typeof ResizeObserver === 'undefined') return;
+ const measure = () => setWidth(Math.max(240, Math.round(el.clientWidth)) || 640);
+ measure();
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [view]);
+ const WIDTH = width;
+ const narrow = width < 480;
+ const PLOT_W = WIDTH - PAD.left - PAD.right;
+
+ const allValues = block.points.flatMap((p) => p.values).filter((v): v is number => v !== null);
+ const dataMin = allValues.length ? Math.min(0, ...allValues) : 0;
+ const dataMax = allValues.length ? Math.max(0, ...allValues) : 1;
+ const ticks = useMemo(() => niceTicks(dataMin, dataMax, 4), [dataMin, dataMax]);
+ const yMin = Math.min(dataMin, ticks[0] ?? dataMin);
+ const yMax = Math.max(dataMax, ticks[ticks.length - 1] ?? dataMax);
+ const yScale = (v: number) => PAD.top + PLOT_H - ((v - yMin) / (yMax - yMin || 1)) * PLOT_H;
+
+ const n = block.points.length;
+ // Bars sit in equal bands so none touches the axis; lines run edge to edge.
+ const isBar = block.chart_kind === 'bar';
+ const xStep = isBar ? PLOT_W / n : n > 1 ? PLOT_W / (n - 1) : 0;
+ const xPos = (i: number) => (isBar ? PAD.left + (i + 0.5) * xStep : PAD.left + (n > 1 ? i * xStep : PLOT_W / 2));
+
+ // Bars: every category is named when its band fits a shortened label (5 bars at 390 px do); lines thin out.
+ const MIN_BAND_LABEL = 46;
+ const labelEvery = isBar ? Math.max(1, Math.ceil(MIN_BAND_LABEL / xStep)) : Math.max(1, Math.ceil(n / (narrow ? 4 : 10)));
+ const labelChars = isBar ? Math.max(4, Math.floor((xStep * labelEvery - 6) / 6)) : 10;
+
+ const activePoint = active ? block.points[active.pointIdx] : null;
+ const activeSeries = active ? block.series[active.seriesIdx] : null;
+ const activeValue = active ? activePoint?.values[active.seriesIdx] : null;
+ const activeCell = active ? activePoint?.cells[active.seriesIdx] : null;
+
+ const headers = [block.x.label, ...block.series.map((s) => (s.unit ? `${s.label} (${s.unit})` : s.label))];
+
+ const groupWidth = isBar ? Math.min(xStep * 0.7, 56) : 0;
+ const barWidth = isBar ? groupWidth / block.series.length : 0;
+
+ return (
+ <div data-smart-result="chart" data-block-id={block.id} className="my-3.5 rounded-xl border border-zinc-800 bg-zinc-950/70 p-3.5 shadow-sm">
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <div className="flex flex-wrap items-center gap-3 text-[11px]">
+ {block.series.map((s, i) => (
+ <span key={s.key} className="flex items-center gap-1.5 text-zinc-400">
+ <svg width="14" height="14" viewBox="-7 -7 14 14" aria-hidden="true" className="shrink-0">
+ <g fill={SERIES_COLORS[i % SERIES_COLORS.length]} stroke={block.chart_kind === 'line' ? SERIES_COLORS[i % SERIES_COLORS.length] : 'none'}>
+ {React.createElement(MARKERS[i % MARKERS.length], { cx: 0, cy: 0, size: 4 })}
+ </g>
+ </svg>
+ {s.label}
+ {s.unit ? ` (${s.unit})` : ''}
+ </span>
+ ))}
+ </div>
+ <div role="group" aria-label="Chart view" className="flex shrink-0 rounded-lg border border-zinc-800 text-[11px]">
+ {(['chart', 'table'] as const).map((v, i) => (
+ <button
+ key={v}
+ type="button"
+ aria-pressed={view === v}
+ onClick={() => setView(v)}
+ className={`px-2.5 py-1 capitalize cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70 ${
+ i === 0 ? 'rounded-l-lg' : 'rounded-r-lg'
+ } ${view === v ? 'bg-sky-500/15 text-sky-300' : 'text-zinc-400 hover:text-zinc-200'}`}
+ >
+ {v}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {view === 'chart' ? (
+ <>
+ <div ref={svgBox}>
+ <svg
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ role="img"
+ aria-labelledby={`${uid}-title`}
+ aria-describedby={`${uid}-desc`}
+ className="w-full"
+ style={{ maxHeight: 280 }}
+ >
+ <title id={`${uid}-title`}>{block.title ?? `${block.chart_kind === 'line' ? 'Line' : 'Bar'} chart`}</title>
+ <desc id={`${uid}-desc`}>{block.summary ?? headers.join(', ')}</desc>
+ <defs>
+ {block.series.map((s, i) => (
+ <BarPattern key={s.key} id={`${uid}-pat-${i}`} variant={i} color={SERIES_COLORS[i % SERIES_COLORS.length]} />
+ ))}
+ </defs>
+
+ {/* Gridlines: scale, not data claims. */}
+ {ticks.map((t) => (
+ <g key={t}>
+ <line x1={PAD.left} x2={WIDTH - PAD.right} y1={yScale(t)} y2={yScale(t)} stroke="#27272a" strokeWidth={1} />
+ <text x={PAD.left - 8} y={yScale(t)} textAnchor="end" dominantBaseline="middle" fontSize={11} fill="#71717a">
+ {fmtTick(t)}
+ </text>
+ </g>
+ ))}
+ <line x1={PAD.left} x2={PAD.left} y1={PAD.top} y2={HEIGHT - PAD.bottom} stroke="#3f3f46" strokeWidth={1} />
+ <line x1={PAD.left} x2={WIDTH - PAD.right} y1={HEIGHT - PAD.bottom} y2={HEIGHT - PAD.bottom} stroke="#3f3f46" strokeWidth={1} />
+
+ {/* X labels, thinned out so 390 px never clips. */}
+ {block.points.map((p, i) => {
+ const gap = (n - 1) % labelEvery;
+ if (i % labelEvery !== 0 && !(i === n - 1 && gap * 2 >= labelEvery)) return null;
+ return (
+ <text
+ key={p.id}
+ x={xPos(i)}
+ y={HEIGHT - PAD.bottom + 16}
+ textAnchor={!isBar && i === n - 1 && n > 1 ? 'end' : 'middle'}
+ fontSize={11}
+ fill="#a1a1aa"
+ >
+ {p.x.length > labelChars ? `${p.x.slice(0, labelChars - 1)}…` : p.x}
+ </text>
+ );
+ })}
+
+ {block.chart_kind === 'line'
+ ? block.series.map((s, si) => {
+ const segments: { x: number; y: number; i: number }[][] = [];
+ let cur: { x: number; y: number; i: number }[] = [];
+ block.points.forEach((p, i) => {
+ const v = p.values[si];
+ if (v === null) {
+ if (cur.length) segments.push(cur);
+ cur = [];
+ return;
+ }
+ cur.push({ x: xPos(i), y: yScale(v), i });
+ });
+ if (cur.length) segments.push(cur);
+ const color = SERIES_COLORS[si % SERIES_COLORS.length];
+ const Marker = MARKERS[si % MARKERS.length];
+ return (
+ <g key={s.key}>
+ {segments.map((seg, k) => (
+ <path
+ key={k}
+ d={seg.map((pt, idx) => `${idx === 0 ? 'M' : 'L'}${pt.x},${pt.y}`).join(' ')}
+ fill="none"
+ stroke={color}
+ strokeWidth={2}
+ strokeDasharray={DASHES[si % DASHES.length]}
+ />
+ ))}
+ {block.points.map((p, i) => {
+ const v = p.values[si];
+ if (v === null) return null;
+ const isActive = active?.seriesIdx === si && active.pointIdx === i;
+ return (
+ <g
+ key={p.id}
+ tabIndex={0}
+ role="button"
+ aria-label={`${s.label} at ${p.x}: ${p.cells[si] || fmtTick(v)}${s.unit ? ` ${s.unit}` : ''}`}
+ className="cursor-pointer outline-none focus-visible:[&>*]:stroke-zinc-50"
+ fill={color}
+ stroke={color}
+ onFocus={() => setActive({ seriesIdx: si, pointIdx: i })}
+ onBlur={() => setActive(null)}
+ onMouseEnter={() => setActive({ seriesIdx: si, pointIdx: i })}
+ onMouseLeave={() => setActive(null)}
+ >
+ <circle cx={xPos(i)} cy={yScale(v)} r={10} fill="transparent" stroke="none" />
+ <Marker cx={xPos(i)} cy={yScale(v)} size={isActive ? 4.5 : 3.2} />
+ </g>
+ );
+ })}
+ </g>
+ );
+ })
+ : block.points.map((p, i) => (
+ <g key={p.id}>
+ {block.series.map((s, si) => {
+ const v = p.values[si];
+ if (v === null) return null;
+ const x = xPos(i) - groupWidth / 2 + si * barWidth;
+ const y = yScale(Math.max(0, v));
+ const h = Math.abs(yScale(v) - yScale(0));
+ const isActive = active?.seriesIdx === si && active.pointIdx === i;
+ return (
+ <rect
+ key={s.key}
+ tabIndex={0}
+ role="button"
+ aria-label={`${s.label} at ${p.x}: ${p.cells[si] || fmtTick(v)}${s.unit ? ` ${s.unit}` : ''}`}
+ x={x}
+ y={y}
+ width={Math.max(2, barWidth - 2)}
+ height={Math.max(0, h)}
+ fill={si === 0 ? SERIES_COLORS[0] : `url(#${uid}-pat-${si})`}
+ stroke={SERIES_COLORS[si % SERIES_COLORS.length]}
+ strokeWidth={isActive ? 1.5 : 0}
+ className="cursor-pointer outline-none"
+ onFocus={() => setActive({ seriesIdx: si, pointIdx: i })}
+ onBlur={() => setActive(null)}
+ onMouseEnter={() => setActive({ seriesIdx: si, pointIdx: i })}
+ onMouseLeave={() => setActive(null)}
+ />
+ );
+ })}
+ </g>
+ ))}
+ </svg>
+ </div>
+ <div aria-live="polite" className="mt-1 h-4 text-[11px] text-zinc-400">
+ {active && activeSeries
+ ? `${activeSeries.label} at ${activePoint?.x}: ${activeCell || (activeValue !== null && activeValue !== undefined ? fmtTick(activeValue) : '—')}${
+ activeSeries.unit ? ` ${activeSeries.unit}` : ''
+ }`
+ : 'Tab through the chart for each value.'}
+ </div>
+ </>
+ ) : (
+ <div className="overflow-x-auto">
+ <table className="w-full border-collapse text-left text-xs">
+ <thead className="border-b border-zinc-800 text-zinc-200">
+ <tr>
+ {headers.map((h) => (
+ <th key={h} scope="col" className="px-2.5 py-2 font-semibold whitespace-nowrap">
+ {h}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-zinc-800/60 text-zinc-300">
+ {block.points.map((p) => (
+ <tr key={p.id}>
+ <td className="px-2.5 py-2 whitespace-nowrap">{p.x}</td>
+ {p.cells.map((c, j) => (
+ <td key={j} className="px-2.5 py-2">
+ {c !== '' ? c : '—'}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {block.summary && <p className="mt-2 text-xs leading-relaxed text-zinc-400">{block.summary}</p>}
+ </div>
+ );
+};
diff --git a/frontend/src/components/results/Facts.tsx b/frontend/src/components/results/Facts.tsx
new file mode 100644
index 00000000..e8c667f1
--- /dev/null
+++ b/frontend/src/components/results/Facts.tsx
@@ -0,0 +1,29 @@
+import React from 'react';
+import { FactItem, FactsBlock, inRange, isText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+/** 3-12 label/value facts, built from parseCommon plus isText/inRange/uniqueIds (plan §A.3). */
+export function validFacts(raw: unknown): FactsBlock | null {
+ const b = parseCommon(raw, 'facts');
+ if (!b || !inRange(b.items, 3, 12) || !uniqueIds(b.items)) return null;
+ const items: FactItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ if (!isText(it.label) || !isText(it.value, 300, true)) return null;
+ items.push({ id: it.id as string, label: it.label, value: it.value });
+ }
+ return { id: b.id, type: 'facts', title: b.title, source: b.source, provenance: b.provenance, items };
+}
+
+/** A definition-list card for 3-12 label/value facts, mostly non-numeric. */
+export const Facts: React.FC<RendererProps<FactsBlock>> = ({ block }) => (
+ <div data-smart-result="facts" data-block-id={block.id}>
+ <dl className="my-3.5 divide-y divide-zinc-800/60 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3.5 shadow-sm">
+ {block.items.map((item) => (
+ <div key={item.id} className="grid grid-cols-[minmax(0,2fr)_minmax(0,3fr)] gap-x-3 gap-y-0.5 py-2.5 text-xs">
+ <dt className="text-zinc-500 [overflow-wrap:anywhere]">{item.label}</dt>
+ <dd className="text-zinc-200 leading-relaxed [overflow-wrap:anywhere]">{item.value || '—'}</dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+);
diff --git a/frontend/src/components/results/Files.tsx b/frontend/src/components/results/Files.tsx
new file mode 100644
index 00000000..4e75708c
--- /dev/null
+++ b/frontend/src/components/results/Files.tsx
@@ -0,0 +1,159 @@
+import React from 'react';
+import { File as FileIcon, Image as ImageIcon } from 'lucide-react';
+import { FileItem, FilePreview, FilesBlock, PreviewCut, inRange, isIndex, isObj, isText, parseCommon, previewNote, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+/** The optional cut fields: each a non-negative integer (`truncated` only ever `true`); anything else is invalid. */
+function validCut(v: Record<string, unknown>, keys: ('total_rows' | 'total_cols' | 'total_lines')[]): PreviewCut | undefined {
+ const cut: PreviewCut = {};
+ for (const k of keys) {
+ if (v[k] === undefined || v[k] === null) continue;
+ if (!isIndex(v[k])) return undefined;
+ cut[k] = v[k] as number;
+ }
+ if (v.truncated !== undefined && v.truncated !== null) {
+ if (v.truncated !== true) return undefined;
+ cut.truncated = true;
+ }
+ return cut;
+}
+
+function validPreview(v: unknown): FilePreview | undefined {
+ if (v === null || v === undefined) return null;
+ if (!isObj(v)) return undefined;
+ if (v.kind === 'table') {
+ if (!Array.isArray(v.columns) || !v.columns.every((c) => isText(c, 80))) return undefined;
+ const columns = v.columns as string[];
+ if (!Array.isArray(v.rows) || !v.rows.every((r) => Array.isArray(r) && r.length === columns.length && r.every((c) => isText(c, 300, true))))
+ return undefined;
+ const cut = validCut(v, ['total_rows', 'total_cols']);
+ if (!cut) return undefined;
+ return { kind: 'table', columns, rows: v.rows as string[][], ...cut };
+ }
+ if (v.kind === 'text') {
+ if (!isText(v.excerpt, 2000, true)) return undefined;
+ const cut = validCut(v, ['total_lines']);
+ if (!cut) return undefined;
+ return { kind: 'text', excerpt: v.excerpt, ...cut };
+ }
+ if (v.kind === 'image') return { kind: 'image' };
+ return undefined;
+}
+
+/** 1-10 attached files, each with a name, type, size, and an optional preview (plan §A.3). */
+export function validFiles(raw: unknown): FilesBlock | null {
+ const b = parseCommon(raw, 'files');
+ if (!b || b.source.kind !== 'slot' || !inRange(b.items, 1, 10) || !uniqueIds(b.items)) return null;
+ const items: FileItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ if (!isText(it.attachment_id, 200) || !isText(it.name) || !isText(it.mime, 100)) return null;
+ if (!isIndex(it.size_bytes)) return null;
+ const preview = validPreview(it.preview);
+ if (preview === undefined) return null;
+ items.push({ id: it.id as string, attachment_id: it.attachment_id, name: it.name, mime: it.mime, size_bytes: it.size_bytes, preview });
+ }
+ return { id: b.id, type: 'files', title: b.title, source: b.source, provenance: b.provenance, items };
+}
+
+function humanSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ const units = ['KB', 'MB', 'GB', 'TB'];
+ let v = bytes / 1024;
+ let i = 0;
+ while (v >= 1024 && i < units.length - 1) {
+ v /= 1024;
+ i += 1;
+ }
+ return `${v >= 10 ? Math.round(v) : Math.round(v * 10) / 10} ${units[i]}`;
+}
+
+const TablePreview: React.FC<{ columns: string[]; rows: string[][] }> = ({ columns, rows }) => (
+ <div className="mt-2 overflow-x-auto rounded-lg border border-zinc-800">
+ <table className="w-full min-w-max border-collapse text-left text-[11px]">
+ <thead>
+ <tr className="border-b border-zinc-800 bg-zinc-900/60">
+ {columns.map((c, i) => (
+ <th key={i} className="whitespace-nowrap px-2 py-1.5 font-medium text-zinc-400">
+ {c}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r, ri) => (
+ <tr key={ri} className="border-b border-zinc-900 last:border-0">
+ {r.map((c, ci) => (
+ <td key={ci} className="whitespace-nowrap px-2 py-1.5 text-zinc-300">
+ {c}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+);
+
+/** The muted line that says a preview was cut; nothing for a complete one. */
+const CutNote: React.FC<{ preview: FilePreview }> = ({ preview }) => {
+ const note = previewNote(preview);
+ return note ? (
+ <p className="mt-1 text-[11px] text-zinc-500" data-preview-note>
+ {note}
+ </p>
+ ) : null;
+};
+
+const FilePreviewView: React.FC<{ item: FileItem }> = ({ item }) => {
+ const preview = item.preview;
+ if (!preview) return null;
+ if (preview.kind === 'table')
+ return (
+ <>
+ <TablePreview columns={preview.columns} rows={preview.rows} />
+ <CutNote preview={preview} />
+ </>
+ );
+ if (preview.kind === 'text') {
+ return (
+ <>
+ <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded-lg border border-zinc-800 bg-zinc-900/60 p-2 font-mono text-[11px] leading-relaxed text-zinc-300">
+ {preview.excerpt}
+ </pre>
+ <CutNote preview={preview} />
+ </>
+ );
+ }
+ // image previews have no renderable source in this contract yet; show a labelled placeholder
+ // rather than guessing at a URL (the attachment route isn't built — see the PR notes).
+ return (
+ <div className="mt-2 flex items-center gap-2 rounded-lg border border-dashed border-zinc-800 bg-zinc-900/40 px-3 py-4 text-[11px] text-zinc-500">
+ <ImageIcon size={14} aria-hidden="true" />
+ Image preview not available yet
+ </div>
+ );
+};
+
+/** Attached files: name, type, size, and a preview of the data itself when one is available. */
+export const Files: React.FC<RendererProps<FilesBlock>> = ({ block }) => (
+ <div data-smart-result="files" data-block-id={block.id}>
+ <ul role="list" className="my-3.5 space-y-2">
+ {block.items.map((item) => (
+ <li key={item.id} className="rounded-xl border border-zinc-800 bg-zinc-950/70 p-3 shadow-sm">
+ <div className="flex items-start gap-2">
+ <FileIcon size={14} className="mt-0.5 shrink-0 text-zinc-500" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-xs font-medium text-zinc-200" title={item.name}>
+ {item.name}
+ </div>
+ <div className="mt-0.5 text-[11px] text-zinc-500">
+ {item.mime} · {humanSize(item.size_bytes)}
+ </div>
+ <FilePreviewView item={item} />
+ </div>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+);
diff --git a/frontend/src/components/results/Findings.tsx b/frontend/src/components/results/Findings.tsx
new file mode 100644
index 00000000..594b3db9
--- /dev/null
+++ b/frontend/src/components/results/Findings.tsx
@@ -0,0 +1,80 @@
+import React from 'react';
+import { FindingItem, FindingRef, FindingsBlock, Severity, inRange, isIndex, isObj, isText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+const SEVERITIES: Severity[] = ['critical', 'high', 'medium', 'low', 'info'];
+const ORDER: Severity[] = ['critical', 'high', 'medium', 'low', 'info'];
+
+/** 2-30 findings; severity is one of the fixed enum values, refs name a path and an optional line. */
+export function validFindings(raw: unknown): FindingsBlock | null {
+ const b = parseCommon(raw, 'findings');
+ if (!b || !inRange(b.items, 2, 30) || !uniqueIds(b.items)) return null;
+ const items: FindingItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ if (!SEVERITIES.includes(it.severity as Severity) || !isText(it.severity_text, 40)) return null;
+ if (!isText(it.title) || !isText(it.detail, 2000)) return null;
+ if (!Array.isArray(it.refs)) return null;
+ const refs: FindingRef[] = [];
+ for (const r of it.refs) {
+ if (!isObj(r) || !isText(r.path, 400)) return null;
+ if (r.line !== null && r.line !== undefined && !isIndex(r.line)) return null;
+ refs.push({ path: r.path, line: r.line === undefined ? null : (r.line as number | null) });
+ }
+ items.push({ id: it.id as string, severity: it.severity as Severity, severity_text: it.severity_text, title: it.title, detail: it.detail, refs });
+ }
+ return { id: b.id, type: 'findings', title: b.title, source: b.source, provenance: b.provenance, items };
+}
+
+// Severity is always paired with its word, never colour alone; the dot is decorative.
+const DOT: Record<Severity, string> = {
+ critical: 'bg-rose-500',
+ high: 'bg-orange-500',
+ medium: 'bg-amber-500',
+ low: 'bg-sky-500',
+ info: 'bg-zinc-500',
+};
+
+const refLabel = (r: FindingItem['refs'][number]) => `${r.path}${r.line !== null ? `:${r.line}` : ''}`;
+
+/** Findings grouped by severity, with counts; severity is text, refs are code. */
+export const Findings: React.FC<RendererProps<FindingsBlock>> = ({ block }) => {
+ const groups = ORDER.map((sev) => ({ sev, items: block.items.filter((i) => i.severity === sev) })).filter((g) => g.items.length > 0);
+
+ return (
+ <div data-smart-result="findings" data-block-id={block.id} className="my-3.5 space-y-3">
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-zinc-500">
+ {groups.map((g) => (
+ <span key={g.sev} className="flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 rounded-full ${DOT[g.sev]}`} aria-hidden="true" />
+ {block.items.find((i) => i.severity === g.sev)?.severity_text ?? g.sev}: {g.items.length}
+ </span>
+ ))}
+ </div>
+ {groups.map((g) => (
+ <div key={g.sev}>
+ <h4 className="mb-1.5 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-500">
+ <span className={`h-1.5 w-1.5 rounded-full ${DOT[g.sev]}`} aria-hidden="true" />
+ {g.items[0].severity_text} ({g.items.length})
+ </h4>
+ <ul role="list" className="space-y-1.5">
+ {g.items.map((item) => (
+ <li key={item.id} className="rounded-xl border border-zinc-800 bg-zinc-950/70 p-3 text-xs shadow-sm">
+ <div className="font-semibold leading-snug text-zinc-100 [overflow-wrap:anywhere]">{item.title}</div>
+ <p className="mt-1 leading-relaxed text-zinc-400 [overflow-wrap:anywhere]">{item.detail}</p>
+ {item.refs.length > 0 && (
+ <div className="mt-1.5 flex flex-wrap gap-1.5">
+ {item.refs.map((r, i) => (
+ <code key={i} className="rounded bg-zinc-900 px-1.5 py-0.5 font-mono text-[11px] text-sky-300">
+ {refLabel(r)}
+ </code>
+ ))}
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ );
+};
diff --git a/frontend/src/components/results/Metrics.tsx b/frontend/src/components/results/Metrics.tsx
new file mode 100644
index 00000000..5849c1b8
--- /dev/null
+++ b/frontend/src/components/results/Metrics.tsx
@@ -0,0 +1,38 @@
+import React from 'react';
+import { MetricItem, MetricsBlock, inRange, isNum, isText, optText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+/** 2-6 key numbers, verbatim from the reply (plan §A.3). */
+export function validMetrics(raw: unknown): MetricsBlock | null {
+ const b = parseCommon(raw, 'metrics');
+ if (!b || !inRange(b.items, 2, 6) || !uniqueIds(b.items)) return null;
+ const items: MetricItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ if (!isText(it.label) || !isText(it.value_text) || !isNum(it.value)) return null;
+ const unit = optText(it.unit, 40);
+ const note = optText(it.note);
+ if (unit === undefined || note === undefined) return null;
+ items.push({ id: it.id as string, label: it.label, value_text: it.value_text, value: it.value, unit, note });
+ }
+ return { id: b.id, type: 'metrics', title: b.title, source: b.source, provenance: b.provenance, items };
+}
+
+/** Tiles for 2-6 key numbers, verbatim from the reply. Two per row on a phone. */
+export const Metrics: React.FC<RendererProps<MetricsBlock>> = ({ block }) => (
+ <div data-smart-result="metrics" data-block-id={block.id}>
+ <ul role="list" className="my-3.5 grid grid-cols-2 gap-2.5 sm:grid-cols-3">
+ {block.items.map((item) => (
+ <li key={item.id} className="rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2.5 shadow-sm min-w-0">
+ <div className="truncate text-[11px] text-zinc-500" title={item.label}>
+ {item.label}
+ </div>
+ <div className="mt-0.5 flex items-baseline gap-1 text-lg font-semibold text-zinc-100 [overflow-wrap:anywhere]">
+ <span>{item.value_text}</span>
+ {item.unit && !item.value_text.includes(item.unit) && <span className="text-xs font-normal text-zinc-500">{item.unit}</span>}
+ </div>
+ {item.note && <div className="mt-0.5 text-[11px] leading-snug text-zinc-500 [overflow-wrap:anywhere]">{item.note}</div>}
+ </li>
+ ))}
+ </ul>
+ </div>
+);
diff --git a/frontend/src/components/results/Verification.tsx b/frontend/src/components/results/Verification.tsx
new file mode 100644
index 00000000..4724ee7d
--- /dev/null
+++ b/frontend/src/components/results/Verification.tsx
@@ -0,0 +1,98 @@
+import React from 'react';
+import { AlertTriangle, CircleDashed, Clock, XCircle, CheckCircle2 } from 'lucide-react';
+import { CheckStatus, VerificationBlock, VerificationCheck, inRange, isObj, isText, optText, parseCommon, uniqueIds } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+const STATUSES: CheckStatus[] = ['passed', 'failed', 'error', 'pending'];
+
+/** 1-20 checks against one task, each with a fixed-enum status (plan §A.3). */
+export function validVerification(raw: unknown): VerificationBlock | null {
+ const b = parseCommon(raw, 'verification');
+ if (!b || b.source.kind !== 'slot') return null;
+ const target = b.target;
+ if (!isObj(target) || target.kind !== 'task' || !isText(target.id, 120) || !isText(target.title)) return null;
+ if (!inRange(b.checks, 1, 20) || !uniqueIds(b.checks)) return null;
+ if (!isText(b.summary)) return null;
+ const checks: VerificationCheck[] = [];
+ for (const c of b.checks as Record<string, unknown>[]) {
+ if (!isText(c.label) || !isText(c.kind, 40) || !STATUSES.includes(c.status as CheckStatus)) return null;
+ const excerpt = optText(c.excerpt, 300);
+ if (excerpt === undefined) return null;
+ const checkedAt = c.checked_at === null || c.checked_at === undefined ? null : isText(c.checked_at, 60) ? c.checked_at : undefined;
+ if (checkedAt === undefined) return null;
+ checks.push({ id: c.id as string, label: c.label, kind: c.kind, status: c.status as CheckStatus, excerpt, checked_at: checkedAt });
+ }
+ return {
+ id: b.id,
+ type: 'verification',
+ title: b.title,
+ source: b.source,
+ provenance: b.provenance,
+ target: { kind: 'task', id: target.id, title: target.title },
+ checks,
+ summary: b.summary,
+ };
+}
+
+const STATUS_TEXT: Record<CheckStatus, string> = { passed: 'Passed', failed: 'Failed', error: 'Error', pending: 'Pending' };
+const STATUS_ICON: Record<CheckStatus, React.ElementType> = { passed: CheckCircle2, failed: XCircle, error: AlertTriangle, pending: CircleDashed };
+const STATUS_COLOR: Record<CheckStatus, string> = {
+ passed: 'text-emerald-400',
+ failed: 'text-rose-400',
+ error: 'text-amber-400',
+ pending: 'text-zinc-500',
+};
+
+function formatWhen(s: string | null): string | null {
+ if (!s) return null;
+ const d = new Date(s);
+ return Number.isNaN(d.getTime()) ? s : d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
+}
+
+/** A task's outcome checks: the summary line, then each check with status, an expandable excerpt, and time. */
+export const Verification: React.FC<RendererProps<VerificationBlock>> = ({ block }) => (
+ <div data-smart-result="verification" data-block-id={block.id} className="my-3.5 rounded-xl border border-zinc-800 bg-zinc-950/70 shadow-sm">
+ <div className="border-b border-zinc-800 px-3.5 py-2.5">
+ <p className="text-xs font-medium text-zinc-200">{block.summary}</p>
+ <p className="mt-0.5 truncate text-[11px] text-zinc-500" title={block.target.title}>
+ {block.target.title}
+ </p>
+ </div>
+ <ul role="list" className="divide-y divide-zinc-800/60">
+ {block.checks.map((check) => {
+ const Icon = STATUS_ICON[check.status];
+ const when = formatWhen(check.checked_at);
+ return (
+ <li key={check.id} className="px-3.5 py-2.5">
+ <div className="flex items-start gap-2">
+ <Icon size={14} className={`mt-0.5 shrink-0 ${STATUS_COLOR[check.status]}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ <span className="text-xs font-medium text-zinc-200 [overflow-wrap:anywhere]">{check.label}</span>
+ <span className={`text-[11px] font-medium ${STATUS_COLOR[check.status]}`}>{STATUS_TEXT[check.status]}</span>
+ <span className="text-[11px] text-zinc-600">{check.kind}</span>
+ </div>
+ {when && (
+ <div className="mt-0.5 flex items-center gap-1 text-[11px] text-zinc-500">
+ <Clock size={10} aria-hidden="true" />
+ {when}
+ </div>
+ )}
+ {check.excerpt && (
+ <details className="mt-1">
+ <summary className="cursor-pointer rounded text-[11px] text-sky-400 hover:text-sky-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70">
+ Details
+ </summary>
+ <pre className="mt-1 whitespace-pre-wrap rounded-lg bg-zinc-900 p-2 font-mono text-[11px] leading-relaxed text-zinc-300">
+ {check.excerpt}
+ </pre>
+ </details>
+ )}
+ </div>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+);
diff --git a/frontend/src/components/results/exporters.ts b/frontend/src/components/results/exporters.ts
index fbe3020a..30bcabfb 100644
--- a/frontend/src/components/results/exporters.ts
+++ b/frontend/src/components/results/exporters.ts
@@ -3,7 +3,7 @@
// override this with `markdown` / `csv` in its registry entry.
import type { SmartBlock } from '../../smartResults';
-import { comparisonCsv, csvCell, plainText, stepsMarkdown } from '../../smartResults';
+import { comparisonCsv, csvCell, plainText, previewNote, stepsMarkdown } from '../../smartResults';
type Row = Record<string, unknown>;
@@ -29,7 +29,11 @@ export function blockRows(block: SmartBlock): Row[] {
case 'cards':
return block.items.map(({ title, url, description, meta }) => ({ title, url, description, meta: meta.join(' · ') }));
case 'files':
- return block.items.map(({ name, mime, size_bytes }) => ({ name, type: mime, bytes: size_bytes }));
+ // A cut preview says so in its own row, so pasted data never passes a partial preview off as the file.
+ return block.items.map(({ name, mime, size_bytes, preview }) => {
+ const note = previewNote(preview);
+ return { name, type: mime, bytes: size_bytes, ...(note ? { preview: `${note}; Copy data copies the preview only` } : {}) };
+ });
case 'steps':
return block.items.map(({ text, done, when, owner }) => ({ ...(when != null ? { when } : {}), step: text, ...(owner != null ? { owner } : {}), ...(done != null ? { done } : {}) }));
default:
diff --git a/frontend/src/components/results/fixtures.ts b/frontend/src/components/results/fixtures.ts
index fccd778e..d184d15d 100644
--- a/frontend/src/components/results/fixtures.ts
+++ b/frontend/src/components/results/fixtures.ts
@@ -75,6 +75,7 @@ const barRows = [
['Newsletter', '1,980'],
['Social', '1,310'],
['Referral', '640'],
+ ['Direct', '520'],
];
const chartBar: Fixture = {
reply: `Where October's visits came from:\n\n${table(['Channel', 'Visits'], barRows)}`,
@@ -268,6 +269,16 @@ const files: Fixture = {
preview: { kind: 'table', columns: ['from', 'to'], rows: [['/guide', '/docs/guide'], ['/faq', '/docs/faq']] },
},
{ id: 'a1', attachment_id: 'att-notes', name: 'move-notes.md', mime: 'text/markdown', size_bytes: 840, preview: { kind: 'text', excerpt: '# Move notes\nFreeze content on Monday.' } },
+ {
+ id: 'a3',
+ attachment_id: 'att-big',
+ name: 'urls-all.csv',
+ mime: 'text/csv',
+ size_bytes: 91200,
+ preview: { kind: 'table', columns: ['url', 'status'], rows: [['/a', '200'], ['/b', '301']], total_rows: 143, total_cols: 2 },
+ },
+ { id: 'a4', attachment_id: 'att-log', name: 'crawl.log', mime: 'text/plain', size_bytes: 40960, preview: { kind: 'text', excerpt: 'start\nfetch /a\nfetch /b', total_lines: 512 } },
+ { id: 'a5', attachment_id: 'att-dump', name: 'dump.txt', mime: 'text/plain', size_bytes: 3145728, preview: { kind: 'text', excerpt: 'header', truncated: true } },
{ id: 'a2', attachment_id: 'att-shot', name: 'dns.png', mime: 'image/png', size_bytes: 48200, preview: { kind: 'image' } },
],
}),
diff --git a/frontend/src/components/results/registry.ts b/frontend/src/components/results/registry.ts
index 4b857202..3414e7ed 100644
--- a/frontend/src/components/results/registry.ts
+++ b/frontend/src/components/results/registry.ts
@@ -14,6 +14,13 @@ import type { BlockOf, BlockType, SmartBlock } from '../../smartResults';
import { matchKey, validComparison, validSteps } from '../../smartResults';
import { Comparison } from './Comparison';
import { Steps } from './Steps';
+import { Chart, validChart } from './Chart';
+import { Metrics, validMetrics } from './Metrics';
+import { Facts, validFacts } from './Facts';
+import { Cards, validCards } from './Cards';
+import { Findings, validFindings } from './Findings';
+import { Verification, validVerification } from './Verification';
+import { Files, validFiles } from './Files';
/** One cell or list item of the reply as react-markdown drew it, plus its plain text for matching. */
export interface ReplyPart {
@@ -65,7 +72,13 @@ const stepsMatches = (block: BlockOf<'steps'>, reply: ReplySource) => {
export const REGISTRY: { [T in BlockType]?: Renderer<BlockOf<T>> } = {
comparison: { validate: validComparison, matches: comparisonMatches, Component: Comparison },
steps: { validate: validSteps, matches: stepsMatches, Component: Steps },
- // Iris (smart-results-renderers): chart, metrics, facts, cards, findings, verification, files.
+ chart: { validate: validChart, Component: Chart },
+ metrics: { validate: validMetrics, Component: Metrics },
+ facts: { validate: validFacts, Component: Facts },
+ cards: { validate: validCards, Component: Cards },
+ findings: { validate: validFindings, Component: Findings },
+ verification: { validate: validVerification, Component: Verification },
+ files: { validate: validFiles, Component: Files },
};
const count = (block: SmartBlock): number | null => {
diff --git a/frontend/src/smartResults.ts b/frontend/src/smartResults.ts
index 5100d6c6..7ff4e4a8 100644
--- a/frontend/src/smartResults.ts
+++ b/frontend/src/smartResults.ts
@@ -168,9 +168,19 @@ export interface VerificationBlock extends BlockCommon<'verification'> {
summary: string;
}
+/**
+ * Set only when the server cut the preview: totals of the whole file (rows and columns for a table,
+ * lines for text), or `truncated: true` when it knows the preview is partial but not the totals.
+ */
+export interface PreviewCut {
+ total_rows?: number;
+ total_cols?: number;
+ total_lines?: number;
+ truncated?: true;
+}
export type FilePreview =
- | { kind: 'table'; columns: string[]; rows: string[][] }
- | { kind: 'text'; excerpt: string }
+ | ({ kind: 'table'; columns: string[]; rows: string[][] } & PreviewCut)
+ | ({ kind: 'text'; excerpt: string } & PreviewCut)
| { kind: 'image' }
| null;
export interface FileItem {
@@ -181,6 +191,25 @@ export interface FileItem {
size_bytes: number;
preview: FilePreview;
}
+/**
+ * The muted line under a cut preview: "Showing 20 of 143 rows", "Showing 20 of 512 lines", or
+ * "Preview, file is longer" when only `truncated` is known. Null for a complete preview. The shown
+ * counts are the rows and lines actually drawn; the totals are the server's.
+ */
+export function previewNote(preview: FilePreview): string | null {
+ if (!preview || preview.kind === 'image') return null;
+ const parts: string[] = [];
+ if (preview.kind === 'table') {
+ if (preview.total_rows !== undefined && preview.total_rows > preview.rows.length) parts.push(`${preview.rows.length} of ${preview.total_rows} rows`);
+ if (preview.total_cols !== undefined && preview.total_cols > preview.columns.length) parts.push(`${preview.columns.length} of ${preview.total_cols} columns`);
+ } else if (preview.total_lines !== undefined) {
+ const shown = preview.excerpt.replace(/\n$/, '').split('\n').length;
+ if (preview.total_lines > shown) parts.push(`${shown} of ${preview.total_lines} lines`);
+ }
+ if (parts.length) return `Showing ${parts.join(', ')}`;
+ return preview.truncated || preview.total_rows !== undefined || preview.total_cols !== undefined || preview.total_lines !== undefined ? 'Preview, file is longer' : null;
+}
+
/** 1–10 files; source is always slot. */
export interface FilesBlock extends BlockCommon<'files'> {
items: FileItem[];
diff --git a/frontend/tests/resultsChart.test.mjs b/frontend/tests/resultsChart.test.mjs
new file mode 100644
index 00000000..685f11c6
--- /dev/null
+++ b/frontend/tests/resultsChart.test.mjs
@@ -0,0 +1,170 @@
+// Chart: a hand-rolled SVG, line for a time axis or bars for categories, up to 4 series told apart by
+// shape/pattern as well as colour. The Chart/Table toggle must show the same data either way, every point
+// is keyboard-reachable with a value tooltip, and a null value renders as a gap, never a zero.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { FIXTURES } from './src/components/results/fixtures';
+ export { Chart, validChart } from './src/components/results/Chart';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+const noop = () => {};
+
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mounted = new Set();
+afterEach(() => {
+ for (const v of mounted) v.done();
+ mounted.clear();
+});
+async function mount(block) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ mounted.add({ done: () => { root.unmount(); host.remove(); } });
+ root.render(h(m.Chart, { block, messageId: 'm1', reply: null, ask: noop }));
+ await settle();
+ return host;
+}
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const focus = async (el) => {
+ el.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
+ await settle();
+};
+const blur = async (el) => {
+ el.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
+ await settle();
+};
+
+const lineBlock = () => m.FIXTURES.chartLine.results.blocks[0];
+const barBlock = () => m.FIXTURES.chartBar.results.blocks[0];
+
+test('role=img with a title and description built from the block, never a computed claim', async () => {
+ const host = await mount(lineBlock());
+ const svg = host.querySelector('svg[role="img"]');
+ assert.ok(svg);
+ assert.equal(svg.querySelector('title').textContent, 'Signups by month');
+ assert.equal(svg.querySelector('desc').textContent, 'October had 2,260 signups and 455 paid.');
+ assert.match(host.textContent, /October had 2,260 signups and 455 paid\./, 'the summary is also printed under the chart');
+});
+
+test('a chart with no title or summary still describes itself, never a computed claim', async () => {
+ const host = await mount(barBlock());
+ const svg = host.querySelector('svg[role="img"]');
+ assert.equal(svg.querySelector('title').textContent, 'Bar chart');
+ assert.equal(svg.querySelector('desc').textContent, 'Channel, Visits');
+});
+
+test('Chart/Table toggle shows the same data either way', async () => {
+ const host = await mount(lineBlock());
+ const [chartBtn, tableBtn] = [...host.querySelectorAll('button')];
+ assert.equal(chartBtn.getAttribute('aria-pressed'), 'true');
+ await click(tableBtn);
+ assert.equal(tableBtn.getAttribute('aria-pressed'), 'true');
+ const table = host.querySelector('table');
+ assert.ok(table, 'table view renders a real table, the source data');
+ const rows = [...table.querySelectorAll('tbody tr')].map((tr) => [...tr.querySelectorAll('td')].map((td) => td.textContent));
+ assert.deepEqual(rows[0], ['Jul 2026', '1,240', '310'], 'table cells are the reply’s own cells, not recomputed');
+ assert.equal(host.querySelector('svg[role="img"]'), null, 'table view replaces the chart, not alongside it');
+ await click(chartBtn);
+ assert.ok(host.querySelector('svg[role="img"]'));
+});
+
+test('every point is keyboard-reachable and announces its value on focus, via aria-live', async () => {
+ const host = await mount(lineBlock());
+ const live = host.querySelector('[aria-live="polite"]');
+ assert.match(live.textContent, /Tab through the chart/);
+ const points = [...host.querySelectorAll('g[role="button"][tabindex="0"]')];
+ assert.ok(points.length > 0, 'line points are focusable');
+ await focus(points[0]);
+ assert.match(live.textContent, /Signups at Jul 2026: 1,240/);
+ await blur(points[0]);
+ assert.match(live.textContent, /Tab through the chart/, 'the tooltip clears on blur');
+});
+
+test('bar points are also keyboard-reachable with a value label', async () => {
+ const host = await mount(barBlock());
+ const bars = [...host.querySelectorAll('rect[role="button"][tabindex="0"]')];
+ assert.equal(bars.length, 5);
+ assert.equal(bars[0].getAttribute('aria-label'), 'Visits at Search: 4,120');
+});
+
+test('a null value is a gap: no marker is drawn for it, and the line splits around it', async () => {
+ const b = lineBlock();
+ const withGap = m.validChart({ ...b, points: b.points.map((p, i) => (i === 1 ? { ...p, cells: ['', p.cells[1]], values: [null, p.values[1]] } : p)) });
+ const host = await mount(withGap);
+ const labels = [...host.querySelectorAll('g[role="button"][tabindex="0"]')].map((g) => g.getAttribute('aria-label'));
+ assert.ok(!labels.some((l) => l.startsWith('Signups at Aug 2026')), 'no focusable point for the gapped value');
+ const paths = host.querySelectorAll('path[fill="none"]');
+ assert.ok(paths.length >= 2, 'the signups series line breaks into separate segments around the gap');
+});
+
+test('up to 4 series are told apart by marker shape as well as colour', async () => {
+ const host = await mount(lineBlock());
+ const legend = host.querySelectorAll('svg[aria-hidden="true"]');
+ assert.equal(legend.length, 2, 'one legend swatch per series');
+ assert.notEqual(legend[0].innerHTML, legend[1].innerHTML, 'each series gets a distinct marker shape, not colour alone');
+});
+
+test('a bar chart needs 5 rows; a smaller one falls back to markdown', () => {
+ const b = barBlock();
+ assert.ok(m.validChart(b));
+ assert.equal(m.validChart({ ...b, points: b.points.slice(0, 4) }), null);
+});
+
+test('series in different units abstain: one shared Y axis would flatten the smaller one (SR-R-13)', () => {
+ const b = lineBlock();
+ assert.equal(b.series.length, 2);
+ assert.ok(m.validChart(b), 'the fixture (both unitless) still draws');
+ const withUnits = (u0, u1) => ({ ...b, series: [{ ...b.series[0], unit: u0 }, { ...b.series[1], unit: u1 }] });
+ assert.equal(m.validChart(withUnits('EUR', 'rating (1-5)')), null, 'EUR next to a rating');
+ assert.equal(m.validChart(withUnits('EUR', null)), null, 'a unit next to none');
+ assert.ok(m.validChart(withUnits('EUR', 'EUR')), 'the same unit on every series draws');
+ const one = { ...b, series: [{ ...b.series[0], unit: 'EUR' }], points: b.points.map((p) => ({ ...p, cells: [p.cells[0]], values: [p.values[0]] })) };
+ assert.ok(m.validChart(one), 'a single series has nothing to differ from');
+});
+
+test('a value too large to scale abstains instead of drawing NaN coordinates (SR-R-24)', async () => {
+ const b = lineBlock();
+ const put = (v) => ({ ...b, points: b.points.map((p, i) => (i === 0 ? { ...p, values: [v, p.values[1]] } : p)) });
+ assert.equal(m.validChart(put(1e308)), null);
+ assert.equal(m.validChart(put(-1e308)), null);
+ assert.equal(m.validChart(put(Infinity)), null);
+ assert.equal(m.validChart(put(NaN)), null);
+ assert.ok(m.validChart(put(1e12)), 'large but sane values still draw');
+ const bar = barBlock();
+ assert.equal(m.validChart({ ...bar, points: bar.points.map((p, i) => (i === 0 ? { ...p, values: p.values.map(() => 1e308) } : p)) }), null);
+});
+
+test('every bar category is named at a 390 px card width, shortened to fit its band', async () => {
+ const real = Object.getOwnPropertyDescriptor(dom.window.HTMLElement.prototype, 'clientWidth');
+ Object.defineProperty(dom.window.HTMLElement.prototype, 'clientWidth', { configurable: true, get: () => 300 });
+ // The chart measures its box through a ResizeObserver; jsdom has none, so a no-op one lets the first measure run.
+ globalThis.ResizeObserver = class { observe() {} disconnect() {} };
+ try {
+ const host = await mount(barBlock());
+ const labels = [...host.querySelectorAll('svg[role="img"] text')].filter((t) => t.getAttribute('y') === '240');
+ assert.equal(labels.length, barBlock().points.length, 'all 5 categories are labelled, not 3');
+ assert.ok(labels.every((t) => t.textContent.length <= 7), 'shortened to fit its band: ' + labels.map((t) => t.textContent).join('|'));
+ } finally {
+ delete globalThis.ResizeObserver;
+ if (real) Object.defineProperty(dom.window.HTMLElement.prototype, 'clientWidth', real);
+ else delete dom.window.HTMLElement.prototype.clientWidth;
+ }
+});
diff --git a/frontend/tests/resultsIrisStatic.test.mjs b/frontend/tests/resultsIrisStatic.test.mjs
new file mode 100644
index 00000000..e31daaf4
--- /dev/null
+++ b/frontend/tests/resultsIrisStatic.test.mjs
@@ -0,0 +1,100 @@
+// Static rendering for the 6 non-chart renderers (Chart has its own interactive test file): each is a
+// bare block wrapped only in a data-smart-result div (the title/footer/copy-data frame is SmartResult.tsx's
+// job, not the renderer's), accessible text stands in for colour, and links are safe by construction.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { FIXTURES } from './src/components/results/fixtures';
+ import { Metrics } from './src/components/results/Metrics';
+ import { Facts } from './src/components/results/Facts';
+ import { Cards } from './src/components/results/Cards';
+ import { Findings } from './src/components/results/Findings';
+ import { Verification } from './src/components/results/Verification';
+ import { Files } from './src/components/results/Files';
+ const noop = () => {};
+ const props = (name) => ({ block: FIXTURES[name].results.blocks[0], messageId: 'm1', reply: null, ask: noop });
+ export const html = {
+ metrics: renderToStaticMarkup(React.createElement(Metrics, props('metrics'))),
+ facts: renderToStaticMarkup(React.createElement(Facts, props('facts'))),
+ cards: renderToStaticMarkup(React.createElement(Cards, props('cards'))),
+ findings: renderToStaticMarkup(React.createElement(Findings, props('findings'))),
+ verification: renderToStaticMarkup(React.createElement(Verification, props('verification'))),
+ files: renderToStaticMarkup(React.createElement(Files, props('files'))),
+ };
+`);
+
+test('every renderer is a bare block tagged with its own type and block id, nothing more', () => {
+ for (const [type, id] of [
+ ['metrics', 'b-metrics'],
+ ['facts', 'b-facts'],
+ ['cards', 'b-cards'],
+ ['findings', 'b-find'],
+ ['verification', 'b-verify'],
+ ['files', 'b-files'],
+ ]) {
+ assert.match(m.html[type], new RegExp(`data-smart-result="${type}"[^>]*data-block-id="${id}"|data-block-id="${id}"[^>]*data-smart-result="${type}"`));
+ }
+});
+
+test('metrics: two tiles per row on a phone, unit and note shown verbatim', () => {
+ assert.match(m.html.metrics, /grid-cols-2/);
+ assert.match(m.html.metrics, /EUR 18,400/);
+ assert.doesNotMatch(m.html.metrics, />EUR</, 'a unit the value text already carries is not repeated');
+ assert.match(m.html.metrics, /up 8% vs September/);
+});
+
+test('facts: a definition list, label then value, blank values show an em dash', () => {
+ assert.match(m.html.facts, /<dl/);
+ assert.match(m.html.facts, /<dt[^>]*>Registrar<\/dt>/);
+ assert.match(m.html.facts, /<dd[^>]*>Porkfish<\/dd>/);
+});
+
+test('cards: a link opens safely in a new tab, and domain is shown instead of the raw url', () => {
+ assert.match(m.html.cards, /rel="noopener noreferrer"/);
+ assert.match(m.html.cards, /target="_blank"/);
+ assert.match(m.html.cards, /northdeck\.example/);
+ assert.doesNotMatch(m.html.cards, /https:\/\/northdeck\.example\/docs</, 'the raw url is not printed as text');
+});
+
+test('findings: severity is spelled out in text, grouped with a count, refs are code', () => {
+ assert.match(m.html.findings, />High \(1\)</, 'severity word and count, not colour alone');
+ assert.match(m.html.findings, /<code[^>]*>scripts\/deploy\.sh:42<\/code>/);
+ assert.match(m.html.findings, />Nit \(1\)</, 'the reply’s own severity word is kept, not the raw enum key');
+});
+
+test('verification: summary line, each check’s status as text, and an expandable excerpt', () => {
+ assert.match(m.html.verification, />2 of 4 checks passed</);
+ assert.match(m.html.verification, />Passed</);
+ assert.match(m.html.verification, />Failed</);
+ assert.match(m.html.verification, /<details/);
+ assert.match(m.html.verification, /HTTP 200 in 182 ms/);
+});
+
+test('files: name, type and size are shown; a table and a text preview render, an image never guesses a url', () => {
+ assert.match(m.html.files, /redirects\.csv/);
+ assert.match(m.html.files, /text\/csv/);
+ assert.match(m.html.files, /2\.3 KB/);
+ assert.match(m.html.files, /<table/);
+ assert.match(m.html.files, /Freeze content on Monday/);
+ assert.match(m.html.files, /Image preview not available yet/);
+ assert.doesNotMatch(m.html.files, /<img/, 'never renders an <img> from unverified attachment data');
+});
+
+test('files: a cut preview gets a muted note, a complete one gets none', () => {
+ assert.match(m.html.files, /Showing 2 of 143 rows/);
+ assert.match(m.html.files, /Showing 3 of 512 lines/);
+ assert.match(m.html.files, /Preview, file is longer/);
+ // 3 cut previews in the fixture; the complete csv, the markdown notes and the image carry no note.
+ assert.equal((m.html.files.match(/data-preview-note/g) ?? []).length, 3);
+});
diff --git a/frontend/tests/resultsRegistry.test.mjs b/frontend/tests/resultsRegistry.test.mjs
new file mode 100644
index 00000000..6fe77812
--- /dev/null
+++ b/frontend/tests/resultsRegistry.test.mjs
@@ -0,0 +1,70 @@
+// Registration: each of Iris's 7 types is wired into REGISTRY with its own validator and component, and
+// resolveBlock's generic rules apply to them correctly — a table/list type needs a same-shaped reply, a
+// slot type (verification, files) only ever resolves without one. Pixel's own smartResults.test.mjs
+// already covers resolveBlock/REGISTRY end to end for every fixture; this file checks the wiring itself.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export { FIXTURES } from './src/components/results/fixtures';
+ export { REGISTRY, resolveBlock, defaultMatches } from './src/components/results/registry';
+ export { Chart, validChart } from './src/components/results/Chart';
+ export { Metrics, validMetrics } from './src/components/results/Metrics';
+ export { Facts, validFacts } from './src/components/results/Facts';
+ export { Cards, validCards } from './src/components/results/Cards';
+ export { Findings, validFindings } from './src/components/results/Findings';
+ export { Verification, validVerification } from './src/components/results/Verification';
+ export { Files, validFiles } from './src/components/results/Files';
+`);
+
+const block = (name) => m.FIXTURES[name].results.blocks[0];
+const parts = (n) => Array.from({ length: n }, (_, i) => ({ node: String(i), text: `item ${i}` }));
+const tableReply = (rows) => ({ kind: 'table', head: parts(1), body: Array.from({ length: rows }, () => parts(1)) });
+const listReply = (items) => ({ kind: 'list', items: parts(items), start: 1, ordered: false, task: false });
+
+test('every type Iris owns is registered with its own validator and component, nothing swapped', () => {
+ const owned = [
+ ['chart', m.validChart, m.Chart],
+ ['metrics', m.validMetrics, m.Metrics],
+ ['facts', m.validFacts, m.Facts],
+ ['cards', m.validCards, m.Cards],
+ ['findings', m.validFindings, m.Findings],
+ ['verification', m.validVerification, m.Verification],
+ ['files', m.validFiles, m.Files],
+ ];
+ for (const [type, validate, Component] of owned) {
+ const entry = m.REGISTRY[type];
+ assert.ok(entry, `${type} is registered`);
+ assert.equal(entry.validate, validate, `${type} uses its own validator, not a copy or another type's`);
+ assert.equal(entry.Component, Component, `${type} renders its own component`);
+ }
+});
+
+test('resolveBlock resolves a table-sourced type only against a reply table of the same row count', () => {
+ const b = block('chartLine');
+ assert.ok(m.resolveBlock(b, tableReply(b.points.length)), 'same row count resolves');
+ assert.equal(m.resolveBlock(b, tableReply(b.points.length - 1)), null, 'a short reply table is rejected, never padded or guessed');
+ assert.equal(m.resolveBlock(b, listReply(b.points.length)), null, 'a table-sourced block never matches a list reply');
+});
+
+test('resolveBlock resolves a list-sourced type only against a reply list of the same item count', () => {
+ const b = block('cards');
+ assert.ok(m.resolveBlock(b, listReply(b.items.length)), 'same item count resolves');
+ assert.equal(m.resolveBlock(b, listReply(b.items.length + 1)), null, 'an extra reply item is rejected');
+});
+
+test('a slot-only type (verification, files) resolves with no reply, and never against one, even a same-shaped one', () => {
+ const verification = block('verification');
+ const files = block('files');
+ assert.ok(m.resolveBlock(verification, null), 'verification stands alone, after the reply');
+ assert.ok(m.resolveBlock(files, null), 'files stands alone, after the reply');
+ assert.equal(m.resolveBlock(verification, listReply(verification.checks.length)), null, 'a slot block is never placed into the reply body');
+ assert.equal(m.resolveBlock(files, listReply(files.items.length)), null, 'a slot block is never placed into the reply body');
+});
+
+test('an unknown type, or a block its own validator rejects, resolves to null so the reply falls back to markdown', () => {
+ const b = block('metrics');
+ assert.equal(m.resolveBlock({ ...b, type: 'nonsense' }, null), null);
+ assert.equal(m.resolveBlock({ ...b, items: b.items.slice(0, 1) }, listReply(1)), null, 'below the 2-item minimum, validMetrics itself rejects it');
+});
diff --git a/frontend/tests/smartResults.test.mjs b/frontend/tests/smartResults.test.mjs
index 41180295..46ec80f1 100644
--- a/frontend/tests/smartResults.test.mjs
+++ b/frontend/tests/smartResults.test.mjs
@@ -469,7 +469,7 @@ test('fixtures: one per block type, every block well formed; Pixel’s types ren
assert.ok(v.host.querySelector('[data-smart-frame]'), `${name} renders`);
}
}
- assert.deepEqual(Object.keys(m.REGISTRY).sort(), ['comparison', 'steps']);
+ assert.deepEqual(Object.keys(m.REGISTRY).sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'steps', 'verification']);
});
test('a slot block renders after the reply with its title; Show as text gives its data as markdown', async () => {
diff --git a/frontend/tests/smartResultsIris.test.mjs b/frontend/tests/smartResultsIris.test.mjs
new file mode 100644
index 00000000..854c3623
--- /dev/null
+++ b/frontend/tests/smartResultsIris.test.mjs
@@ -0,0 +1,154 @@
+// Iris's 7 validators (chart, metrics, facts, cards, findings, verification, files): a good fixture
+// always passes, and a block that breaks the plan §A.3 contract always comes back null (the client falls
+// back to markdown rather than trust it). Each validator is built from the shared helpers in smartResults.ts.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export { FIXTURES } from './src/components/results/fixtures';
+ export { validChart } from './src/components/results/Chart';
+ export { validMetrics } from './src/components/results/Metrics';
+ export { validFacts } from './src/components/results/Facts';
+ export { validCards } from './src/components/results/Cards';
+ export { validFindings } from './src/components/results/Findings';
+ export { validVerification } from './src/components/results/Verification';
+ export { validFiles } from './src/components/results/Files';
+ export { blockRows, blockCsv } from './src/components/results/exporters';
+ export { previewNote } from './src/smartResults';
+`);
+
+const block = (name) => m.FIXTURES[name].results.blocks[0];
+
+test('every fixture of a type this file owns passes its own validator', () => {
+ assert.ok(m.validChart(block('chartLine')), 'line chart');
+ assert.ok(m.validChart(block('chartBar')), 'bar chart');
+ assert.ok(m.validMetrics(block('metrics')));
+ assert.ok(m.validFacts(block('facts')));
+ assert.ok(m.validCards(block('cards')));
+ assert.ok(m.validFindings(block('findings')));
+ assert.ok(m.validVerification(block('verification')));
+ assert.ok(m.validFiles(block('files')));
+});
+
+test('chart: series count, point/series alignment, enum and null values are checked', () => {
+ const b = block('chartLine');
+ assert.equal(m.validChart({ ...b, chart_kind: 'pie' }), null, 'chart_kind is a fixed enum');
+ assert.equal(m.validChart({ ...b, series: [] }), null, 'at least one series');
+ assert.equal(m.validChart({ ...b, series: Array(5).fill(b.series[0]).map((s, i) => ({ ...s, key: `s${i}` })) }), null, 'at most 4 series');
+ assert.equal(m.validChart({ ...b, series: [b.series[0], { ...b.series[0] }] }), null, 'series keys must be unique');
+ assert.equal(
+ m.validChart({ ...b, points: b.points.map((p) => ({ ...p, cells: [p.cells[0]] })) }),
+ null,
+ 'a point needs one cell per series',
+ );
+ assert.equal(
+ m.validChart({ ...b, points: b.points.map((p) => ({ ...p, values: [p.values[0]] })) }),
+ null,
+ 'a point needs one value per series',
+ );
+ const withGap = m.validChart({ ...b, points: b.points.map((p, i) => (i === 1 ? { ...p, values: [null, null] } : p)) });
+ assert.ok(withGap, 'a null value is a gap, not a rejection');
+ assert.equal(withGap.points[1].values[0], null);
+ assert.equal(m.validChart({ ...b, points: b.points.slice(0, 2) }), null, 'at least 3 points');
+});
+
+test('metrics: 2-6 items, a real number, and HTML in any text is rejected', () => {
+ const b = block('metrics');
+ assert.equal(m.validMetrics({ ...b, items: b.items.slice(0, 1) }), null, 'at least 2 items');
+ assert.equal(m.validMetrics({ ...b, items: [...b.items, ...b.items, ...b.items] }), null, 'at most 6 items');
+ assert.equal(m.validMetrics({ ...b, items: [{ ...b.items[0], value: 'eighteen' }, b.items[1]] }), null, 'value must be a number');
+ assert.equal(m.validMetrics({ ...b, items: [{ ...b.items[0], label: '<b>Revenue</b>' }, b.items[1]] }), null, 'no HTML in label');
+});
+
+test('facts: 3-12 items, and a value may be blank but never HTML', () => {
+ const b = block('facts');
+ assert.equal(m.validFacts({ ...b, items: b.items.slice(0, 2) }), null, 'at least 3 items');
+ const blank = m.validFacts({ ...b, items: b.items.map((i) => ({ ...i, value: '' })) });
+ assert.ok(blank, 'a blank value is allowed');
+ assert.equal(m.validFacts({ ...b, items: b.items.map((i) => ({ ...i, value: '<script>1</script>' })) }), null);
+});
+
+test('cards: url is http(s) or absent, never javascript: or a relative path', () => {
+ const b = block('cards');
+ assert.equal(m.validCards({ ...b, items: b.items.slice(0, 1) }), null, 'at least 3 items');
+ assert.equal(m.validCards({ ...b, items: [{ ...b.items[0], url: 'javascript:alert(1)' }, b.items[1], b.items[2]] }), null);
+ assert.equal(m.validCards({ ...b, items: [{ ...b.items[0], url: '/relative' }, b.items[1], b.items[2]] }), null);
+ const noLink = m.validCards({ ...b, items: [{ ...b.items[0], url: null }, b.items[1], b.items[2]] });
+ assert.ok(noLink, 'a card may have no link');
+ assert.equal(noLink.items[0].url, null);
+});
+
+test('findings: severity is one of the fixed enum values, refs name a path', () => {
+ const b = block('findings');
+ assert.equal(m.validFindings({ ...b, items: b.items.slice(0, 1) }), null, 'at least 2 items');
+ assert.equal(m.validFindings({ ...b, items: [{ ...b.items[0], severity: 'urgent' }, b.items[1]] }), null, 'severity is a fixed enum');
+ assert.equal(
+ m.validFindings({ ...b, items: [{ ...b.items[0], refs: [{ path: 'a.sh', line: -1 }] }, b.items[1]] }),
+ null,
+ 'a ref line is a non-negative integer or null',
+ );
+ const nullLine = m.validFindings({ ...b, items: [{ ...b.items[0], refs: [{ path: 'a.sh', line: null }] }, b.items[1]] });
+ assert.ok(nullLine, 'a ref may have no line');
+});
+
+test('verification: status is a fixed enum, target is a task, source is always slot', () => {
+ const b = block('verification');
+ assert.equal(m.validVerification({ ...b, source: { kind: 'markdown_table', index: 0 } }), null, 'source is always slot');
+ assert.equal(m.validVerification({ ...b, target: { kind: 'file', id: 'x', title: 'x' } }), null, 'target is always a task');
+ assert.equal(m.validVerification({ ...b, checks: [{ ...b.checks[0], status: 'skipped' }] }), null, 'status is a fixed enum');
+ assert.equal(m.validVerification({ ...b, checks: [] }), null, 'at least 1 check');
+});
+
+test('files: size is a non-negative integer, preview kinds are checked, source is always slot', () => {
+ const b = block('files');
+ assert.equal(m.validFiles({ ...b, source: { kind: 'markdown_list', index: 0 } }), null, 'source is always slot');
+ assert.equal(m.validFiles({ ...b, items: [] }), null, 'at least 1 file');
+ assert.equal(m.validFiles({ ...b, items: [{ ...b.items[0], size_bytes: -1 }] }), null, 'size is non-negative');
+ assert.equal(m.validFiles({ ...b, items: [{ ...b.items[0], size_bytes: 1.5 }] }), null, 'size is an integer');
+ assert.equal(
+ m.validFiles({ ...b, items: [{ ...b.items[0], preview: { kind: 'table', columns: ['a', 'b'], rows: [['x']] } }] }),
+ null,
+ 'a table preview row must match the column count',
+ );
+ const noPreview = m.validFiles({ ...b, items: [{ ...b.items[0], preview: null }] });
+ assert.ok(noPreview, 'a file may have no preview');
+});
+
+test('files: cut-preview fields are optional, non-negative integers, and truncated is only ever true', () => {
+ const b = block('files');
+ const table = (extra) => ({ ...b, items: [{ ...b.items[0], preview: { kind: 'table', columns: ['a'], rows: [['x']], ...extra } }] });
+ const text = (extra) => ({ ...b, items: [{ ...b.items[0], preview: { kind: 'text', excerpt: 'x', ...extra } }] });
+ assert.ok(m.validFiles(table({})), 'a complete preview needs none of them');
+ assert.equal(m.validFiles(table({ total_rows: 143, total_cols: 9 })).items[0].preview.total_rows, 143);
+ assert.equal(m.validFiles(text({ total_lines: 512 })).items[0].preview.total_lines, 512);
+ assert.equal(m.validFiles(text({ truncated: true })).items[0].preview.truncated, true);
+ assert.equal(m.validFiles(table({ total_rows: -1 })), null, 'negative total');
+ assert.equal(m.validFiles(table({ total_rows: 1.5 })), null, 'fractional total');
+ assert.equal(m.validFiles(table({ total_cols: '9' })), null, 'string total');
+ assert.equal(m.validFiles(text({ total_lines: NaN })), null, 'NaN total');
+ assert.equal(m.validFiles(text({ truncated: false })), null, 'truncated is only ever true');
+ assert.equal(m.validFiles(text({ truncated: 'yes' })), null, 'truncated is a boolean');
+});
+
+test('files: Copy data on a cut preview says it copies the preview only; complete previews are unchanged', () => {
+ const rows = m.blockRows(block('files'));
+ const by = (n) => rows.find((r) => r.name === n);
+ assert.deepEqual(Object.keys(by('redirects.csv')), ['name', 'type', 'bytes'], 'complete preview: no extra column');
+ assert.deepEqual(Object.keys(by('dns.png')), ['name', 'type', 'bytes']);
+ assert.match(by('urls-all.csv').preview, /^Showing 2 of 143 rows; Copy data copies the preview only$/);
+ assert.match(by('crawl.log').preview, /Showing 3 of 512 lines/);
+ assert.match(by('dump.txt').preview, /Preview, file is longer/);
+ assert.match(m.blockCsv(block('files')), /copies the preview only/);
+});
+
+test('previewNote: counts the rows and lines drawn, and says nothing when the totals do not exceed them', () => {
+ const t = (extra) => ({ kind: 'table', columns: ['a', 'b', 'c'], rows: [['1', '2', '3']], ...extra });
+ assert.equal(m.previewNote(t({ total_rows: 20, total_cols: 12 })), 'Showing 1 of 20 rows, 3 of 12 columns');
+ assert.equal(m.previewNote(t({ total_cols: 12 })), 'Showing 3 of 12 columns');
+ assert.equal(m.previewNote(t({ total_rows: 1 })), 'Preview, file is longer', 'a total that is not larger than the rows drawn still marks a cut');
+ assert.equal(m.previewNote(t({})), null);
+ assert.equal(m.previewNote({ kind: 'text', excerpt: 'a\nb\n', total_lines: 9 }), 'Showing 2 of 9 lines', 'a trailing newline is not a line');
+ assert.equal(m.previewNote({ kind: 'image' }), null);
+ assert.equal(m.previewNote(null), null);
+});