/** * Shared UI helpers for the Evaluation Command Center (megaeval). * Complements components/labeleval/shared.tsx with aggregate-first idioms: * query provenance badges, exact/approx honesty tags, delta coloring, * outcome chips and sketch histogram sparklines. */ import type { ReactNode } from 'react'; import Box from '@mui/material/Box'; import Chip from '@mui/material/Chip'; import Tooltip from '@mui/material/Tooltip'; import Typography from '@mui/material/Typography'; import { CheckCircle2, AlertTriangle, OctagonAlert } from 'lucide-react'; import type { ErrorType, HistogramSketch, QueryMeta, QueryRow } from '../../types/megaeval'; import { fmtCompact } from '../../services/megaeval'; import { fmtPct } from '../labeleval/shared'; import { GLOSSARY, glossaryKeyForStatus } from '../../content/glossary'; import { ExplainTip, GlossaryContent, InfoDot } from '../help/InfoTip'; // ---------------------------------------------------------------- query provenance const SOURCE_COLORS: Record = { cache: { bg: '#1b5e20', fg: '#a5d6a7' }, cube: { bg: '#0d47a1', fg: '#90caf9' }, scan: { bg: '#e65100', fg: '#ffe0b2' }, }; function fmtLatency(ms: number): string { if (ms < 1) return `${ms.toFixed(1)}ms`; if (ms < 100) return `${ms.toFixed(1)}ms`; return `${Math.round(ms)}ms`; } /** "cube · 74ms" / "cache · 0.1ms" provenance badge for POST /api/evaluations/query panels. */ export function QueryBadge({ meta }: { meta: QueryMeta | null | undefined }) { if (!meta) return null; const colors = SOURCE_COLORS[meta.source] ?? SOURCE_COLORS.cube; const label = `${meta.source} · ${fmtLatency(meta.latency_ms)}`; const entry = GLOSSARY.query_source; return ( {`this query: source=${meta.source} · cache_hit=${meta.cache_hit ? 'yes' : 'no'} · cells=${meta.cells_touched}${ meta.exact ? ' · exact' : ` · approx (${meta.approximate_fields.join(', ') || 'sketch'})` }`} } slotProps={{ tooltip: { sx: { bgcolor: '#1d242c', border: '1px solid #2f3944', p: 1.25 } } }} > ); } /** Exact vs sketch-derived honesty tag. Hover explains how the estimate was made. */ export function ExactnessTag({ approx, sx, method, }: { approx: boolean; sx?: object; /** Optional glossary key of the estimator (hll, quantile_sketch, wilson_ci…). */ method?: string; }) { return ( ); } // ---------------------------------------------------------------- query row helpers /** Reads a numeric metric out of a QueryRow (values arrive as string | number | null). */ export function rowNum(row: QueryRow, key: string): number | null { const v = row[key]; if (v === null || v === undefined) return null; const n = typeof v === 'number' ? v : Number(v); return Number.isNaN(n) ? null : n; } export function rowStr(row: QueryRow, key: string): string { const v = row[key]; return v === null || v === undefined ? '—' : String(v); } // ---------------------------------------------------------------- inline percent bar /** Compact percentage cell with an inline bar, for dense aggregate tables. */ export function PctBarCell({ value, color = '#4fc3f7', width = 84, }: { value: number | null | undefined; color?: string; width?: number; }) { if (value === null || value === undefined || Number.isNaN(value)) { return ( — ); } const frac = Math.max(0, Math.min(1, value <= 1 ? value : value / 100)); return ( {fmtPct(value)} ); } // ---------------------------------------------------------------- outcome / error type chips export const OUTCOME_COLORS: Record = { TP: { bg: '#1b5e20', fg: '#a5d6a7' }, FN: { bg: '#b71c1c', fg: '#ffcdd2' }, FP: { bg: '#e65100', fg: '#ffe0b2' }, LOCALIZATION: { bg: '#4a148c', fg: '#ce93d8' }, ANOMALY: { bg: '#880e4f', fg: '#f48fb1' }, LOW_CONF: { bg: '#f9a825', fg: '#212121' }, }; export function OutcomeChip({ outcome }: { outcome: string }) { const colors = OUTCOME_COLORS[outcome] ?? { bg: '#37474f', fg: '#cfd8dc' }; const chip = ( ); const key = glossaryKeyForStatus(outcome); return key ? {chip} : chip; } export const ERROR_TYPE_COLORS: Record = { FN: '#ef5350', FP: '#ffa726', LOCALIZATION: '#ab47bc', ANOMALY: '#ec407a', LOW_CONF: '#ffee58', }; // ---------------------------------------------------------------- run status const RUN_STATUS_COLORS: Record = { created: { bg: '#37474f', fg: '#cfd8dc' }, queued: { bg: '#37474f', fg: '#cfd8dc' }, running: { bg: '#0d47a1', fg: '#90caf9' }, reducing: { bg: '#4a148c', fg: '#ce93d8' }, materializing: { bg: '#004d40', fg: '#80cbc4' }, published: { bg: '#1b5e20', fg: '#a5d6a7' }, failed: { bg: '#b71c1c', fg: '#ffcdd2' }, }; const RUN_STATUS_EXPLANATIONS: Record = { created: 'Run record exists but has not been queued yet.', queued: 'Waiting for evaluation workers to pick it up.', running: 'Workers are scoring population partitions and emitting partial statistics.', reducing: 'Merging per-partition partial statistics into global aggregates.', materializing: 'Writing the metric cube, error index and sketches to storage.', published: 'Artifacts are live: this run is queryable across the Command Center.', failed: 'The run aborted; inspect the run record for the failing stage.', }; export function RunStatusChip({ status }: { status: string }) { const colors = RUN_STATUS_COLORS[status] ?? { bg: '#37474f', fg: '#cfd8dc' }; return ( ); } // ---------------------------------------------------------------- container status const CONTAINER_STATUS_EXPLANATIONS: Record = { ok: 'No elevated error signal: error counts and risk score within normal range for this run.', warn: 'Elevated risk: notable error density or anomaly presence — worth a look.', critical: 'High risk: dense errors and/or safety-critical failures concentrated in this container.', }; export function ContainerStatusIcon({ status }: { status: 'ok' | 'warn' | 'critical' }) { const icon = status === 'critical' ? ( ) : status === 'warn' ? ( ) : ( ); return ( {icon} ); } // ---------------------------------------------------------------- deltas /** Colored delta text. Set higherIsBetter=false for metrics like anomaly_rate / error_rate / fp. */ export function DeltaText({ delta, higherIsBetter = true, asPct = true, }: { delta: number; higherIsBetter?: boolean; asPct?: boolean; }) { const good = higherIsBetter ? delta >= 0 : delta <= 0; const neutral = Math.abs(delta) < 1e-9; const magnitude = asPct ? (Math.abs(delta) * 100).toFixed(1) : Math.abs(delta).toFixed(3); const sign = delta > 0 ? '+' : delta < 0 ? '−' : '±'; const text = `${sign}${magnitude}`; return ( {text} ); } // ---------------------------------------------------------------- dimension chips export function DimChips({ values, sx }: { values: (string | undefined)[]; sx?: object }) { return ( {values .filter((v): v is string => Boolean(v)) .map((v, i) => ( ))} ); } // ---------------------------------------------------------------- histogram sparkline (sketch) /** SVG histogram sparkline with p10 / p50 / p90 markers. Sketch-derived — always labeled approx. */ export function HistogramSparkline({ sketch, color = '#4fc3f7', width = 260, height = 56, }: { sketch: HistogramSketch; color?: string; width?: number; height?: number; }) { const maxCount = Math.max(1, ...sketch.counts); const barW = width / Math.max(1, sketch.counts.length); const span = sketch.hi - sketch.lo || 1; const xFor = (v: number) => ((v - sketch.lo) / span) * width; const markers: Array<{ key: string; v: number }> = ['p10', 'p50', 'p90'] .filter((k) => sketch.percentiles[k] !== undefined) .map((k) => ({ key: k, v: sketch.percentiles[k] })); return ( {sketch.counts.map((c, i) => { const h = (c / maxCount) * height; return ( ); })} {markers.map((m) => ( {m.key} {m.v.toFixed(2)} ))} ); } // ---------------------------------------------------------------- misc export function CompactStat({ label, value, term, info }: { label: string; value: ReactNode; term?: string; info?: string }) { return ( {label} {term || info ? : null} {value} ); } export function compactWithExact(n: number | null | undefined): string { if (n === null || n === undefined) return '—'; return `${fmtCompact(n)} (${Math.round(n).toLocaleString()})`; }