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.

Insights: Performance section on the Mission board (Phase D1 UI)

pixel-bot7c213483babd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7111ed17..8d2bd4af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
which model, how long it took, its tokens and cost, whether it ended verified, and how often you had
to step in. Earlier finished tasks are filled in once on upgrade. `GET /api/performance` groups this
by task class and bot (and model) with a 95% confidence range on the verified rate and flags groups
- with fewer than 5 tasks. It doesn't change who gets work: Laya still routes. No screen for it yet.
+ with fewer than 5 tasks. It doesn't change who gets work: Laya still routes.
+- **Performance on the Mission board.** Under the board (All work), a Performance section shows, per
+ kind of work and bot (or model), how many tasks finished, the verified rate with its likely range
+ ("56% (27–81%)"), median time and tokens, cost per task and how often you stepped in. Filter by kind
+ of work, bot and period (30 days, 90 days, all time); groups with fewer than 5 tasks say "few tasks".
+ It's report-only and only you can see it.
### Fixed
- **"Answer in chat" works when that chat is already open.** On the Mission board, "Answer in chat" and
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 8fa27b6b..9c8a42c7 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -28,6 +28,7 @@ import {
} from 'lucide-react';
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { ModernAvatar } from './ModernAvatar';
+import { PerformancePanel } from './PerformancePanel';
import { playSfx } from '../audio/chiptune';
import {
ACTION_DONE,
@@ -2021,6 +2022,10 @@ export interface MissionBoardViewProps {
scanning?: boolean;
onScan?: () => void;
onRetryGraph?: () => void;
+ /** Insights → Performance under the board on "All work" (it loads its own numbers). */
+ showPerformance?: boolean;
+ /** Bumps with each board refresh so Performance reloads too. */
+ refreshCount?: number;
}
export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
@@ -2054,6 +2059,8 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
scanning = false,
onScan,
onRetryGraph,
+ showPerformance = false,
+ refreshCount = 0,
}) => {
const selectId = useId();
const visibleMissions = missions.filter((m) => m.status !== 'cancelled');
@@ -2215,6 +2222,8 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
busy={busyCard}
/>
)}
+
+ {showPerformance && !mission && !needsToken && <PerformancePanel names={names} refreshKey={refreshCount} />}
</>
)}
</div>
@@ -2235,6 +2244,7 @@ export const MissionBoardPage: React.FC<{
const [tasks, setTasks] = useState<Task[] | null>(null);
const [missions, setMissions] = useState<Mission[]>([]);
const [insights, setInsights] = useState<Insights | null>(null);
+ const [refreshCount, setRefreshCount] = useState(0);
const [missionId, setMissionId] = useState<string | null>(null);
const [column, setColumn] = useState<Column>('ready');
const [loading, setLoading] = useState(true);
@@ -2713,6 +2723,7 @@ export const MissionBoardPage: React.FC<{
busyCard={busyCard}
onRefresh={() => {
load();
+ setRefreshCount((n) => n + 1);
if (view === 'graph' && missionId) loadGraph(missionId);
}}
onBack={onBack}
@@ -2724,6 +2735,8 @@ export const MissionBoardPage: React.FC<{
scanning={scanning}
onScan={scan}
onRetryGraph={() => missionId && loadGraph(missionId)}
+ showPerformance
+ refreshCount={refreshCount}
/>
{openId && (
<TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>
diff --git a/frontend/src/components/PerformancePanel.tsx b/frontend/src/components/PerformancePanel.tsx
new file mode 100644
index 00000000..d3510ff9
--- /dev/null
+++ b/frontend/src/components/PerformancePanel.tsx
@@ -0,0 +1,312 @@
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, Gauge, Loader2 } from 'lucide-react';
+import {
+ FEW_TASKS,
+ PerfBy,
+ PerfError,
+ PerfGroup,
+ PerfQuery,
+ PerfReport,
+ PerfSince,
+ SINCE_OPTIONS,
+ botName,
+ classText,
+ costText,
+ latencyText,
+ loadPerformance,
+ mergeOptions,
+ modelText,
+ perTaskText,
+ perfView,
+ rateLabel,
+ rateText,
+ tokensText,
+} from '../performance';
+
+const card = 'rounded-xl border border-zinc-800 bg-zinc-900/40';
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const select =
+ 'min-h-[40px] sm:min-h-[32px] max-w-full bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none';
+
+export const EMPTY_TEXT = 'No finished tasks yet. Numbers appear as tasks finish.';
+export const FILTERED_EMPTY_TEXT = 'No finished tasks match these filters.';
+export const REPORT_ONLY_TEXT = 'Report only: these numbers don’t change which bot gets work.';
+
+const FewTasks: React.FC<{ n: number; min: number }> = ({ n, min }) => (
+ <span
+ title={`Fewer than ${min} finished tasks, so this could change a lot`}
+ data-few-tasks
+ className="inline-flex shrink-0 px-1.5 py-px rounded border border-amber-500/30 bg-amber-500/10 text-[10px] font-medium text-amber-200"
+ >
+ {FEW_TASKS}
+ <span className="sr-only">: only {n}, fewer than {min} finished</span>
+ </span>
+);
+
+const Verified: React.FC<{ g: PerfGroup }> = ({ g }) => (
+ <span aria-label={rateLabel(g.verified_rate, g.verified_ci95)} className="tabular-nums">
+ {rateText(g.verified_rate, g.verified_ci95)}
+ </span>
+);
+
+/** The table body for wide screens. */
+export const PerformanceTable: React.FC<{ groups: PerfGroup[]; by: PerfBy; minN: number; names?: Record<string, string> }> = ({ groups, by, minN, names }) => {
+ const th = 'px-2 py-1.5 font-medium text-left whitespace-nowrap';
+ const num = 'px-2 py-1.5 text-right tabular-nums whitespace-nowrap';
+ return (
+ <table className="hidden sm:table w-full text-xs" data-perf-table>
+ <thead className="text-[11px] text-zinc-400 border-b border-zinc-800">
+ <tr>
+ <th scope="col" className={th}>
+ Kind of work
+ </th>
+ <th scope="col" className={th}>
+ Bot
+ </th>
+ {by === 'model' && (
+ <th scope="col" className={th}>
+ Model
+ </th>
+ )}
+ <th scope="col" className={`${th} text-right`}>
+ Tasks
+ </th>
+ <th scope="col" className={`${th} text-right`} title="Share that ended Verified, with the range it likely falls in (95%)">
+ Verified
+ </th>
+ <th scope="col" className={`${th} text-right`} title="Median time a bot held the task">
+ Median time
+ </th>
+ <th scope="col" className={`${th} text-right`} title="Median fresh tokens per task">
+ Median tokens
+ </th>
+ <th scope="col" className={`${th} text-right`}>
+ Cost per task
+ </th>
+ <th scope="col" className={`${th} text-right`} title="Approvals, unblocks, retries and AutoFix runs per task">
+ You stepped in
+ </th>
+ </tr>
+ </thead>
+ <tbody className="text-zinc-200">
+ {groups.map((g) => (
+ <tr key={`${g.task_class}|${g.kwant_id}|${g.model ?? ''}`} className={`border-b border-zinc-800/60 ${g.low_confidence ? 'text-zinc-400' : ''}`} data-perf-row={g.kwant_id}>
+ <td className="px-2 py-1.5 break-words">{classText(g.task_class)}</td>
+ <td className="px-2 py-1.5 break-words">{botName(g, names)}</td>
+ {by === 'model' && <td className="px-2 py-1.5 break-all text-zinc-400">{modelText(g.model)}</td>}
+ <td className={num}>
+ <span className="inline-flex items-center gap-1.5 justify-end">
+ {g.low_confidence && <FewTasks n={g.n} min={minN} />}
+ {g.n}
+ </span>
+ </td>
+ <td className={num}>
+ <Verified g={g} />
+ </td>
+ <td className={num}>{latencyText(g.median_latency_ms)}</td>
+ <td className={num}>{tokensText(g.median_fresh_tokens)}</td>
+ <td className={num}>{costText(g.cost_per_task_usd)}</td>
+ <td className={num}>{perTaskText(g.interventions_per_task)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+};
+
+/** The same rows as cards on a phone: no sideways scroll. */
+export const PerformanceCards: React.FC<{ groups: PerfGroup[]; by: PerfBy; minN: number; names?: Record<string, string> }> = ({ groups, by, minN, names }) => (
+ <ul className="sm:hidden space-y-2" data-perf-cards>
+ {groups.map((g) => (
+ <li key={`${g.task_class}|${g.kwant_id}|${g.model ?? ''}`} className="rounded-lg border border-zinc-800 px-3 py-2">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-sm font-medium text-zinc-100 break-words min-w-0">{botName(g, names)}</span>
+ <span className="text-[11px] text-zinc-400 break-words min-w-0">{classText(g.task_class)}</span>
+ {g.low_confidence && <FewTasks n={g.n} min={minN} />}
+ </div>
+ {by === 'model' && <p className="text-[11px] text-zinc-500 break-all">{modelText(g.model)}</p>}
+ <dl className="mt-1.5 grid grid-cols-2 gap-x-3 gap-y-1 text-xs">
+ {(
+ [
+ ['Tasks', String(g.n)],
+ ['Verified', <Verified key="v" g={g} />],
+ ['Median time', latencyText(g.median_latency_ms)],
+ ['Median tokens', tokensText(g.median_fresh_tokens)],
+ ['Cost per task', costText(g.cost_per_task_usd)],
+ ['You stepped in', `${perTaskText(g.interventions_per_task)} per task`],
+ ] as Array<[string, React.ReactNode]>
+ ).map(([k, v]) => (
+ <div key={k} className="min-w-0">
+ <dt className="text-[10px] text-zinc-500">{k}</dt>
+ <dd className="text-zinc-200 tabular-nums">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ </li>
+ ))}
+ </ul>
+);
+
+/** What one load produced; exported so tests can render each state without a server. */
+export interface PerformanceBodyProps {
+ report: PerfReport | null;
+ error: PerfError | null;
+ loading: boolean;
+ by: PerfBy;
+ filtered: boolean;
+ names?: Record<string, string>;
+ onRetry: () => void;
+}
+
+export const PerformanceBody: React.FC<PerformanceBodyProps> = ({ report, error, loading, by, filtered, names, onRetry }) => {
+ const view = perfView({ report, error, loading });
+ if (view === 'hidden') return null;
+ if (view === 'loading')
+ return (
+ <p className="flex items-center gap-2 text-xs text-zinc-400" data-perf-loading>
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading performance…
+ </p>
+ );
+ if (view === 'error' && error)
+ return (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300" data-perf-error>
+ <AlertTriangle size={14} className="shrink-0" aria-hidden="true" />
+ <span className="flex-1 min-w-0 break-words">
+ {error.status === 401 ? 'Only you can see these numbers. Confirm it’s you, then try again.' : `Couldn’t load performance. ${error.message}`}
+ </span>
+ <button type="button" onClick={onRetry} className={`shrink-0 px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 min-h-[32px] ${focusRing}`}>
+ Retry
+ </button>
+ </div>
+ );
+ if (view === 'empty')
+ return (
+ <p className="py-4 text-center text-xs text-zinc-400" data-perf-empty>
+ {filtered ? FILTERED_EMPTY_TEXT : EMPTY_TEXT}
+ </p>
+ );
+ const r = report as PerfReport;
+ return (
+ <div className={loading ? 'opacity-60' : ''} aria-busy={loading}>
+ <PerformanceTable groups={r.groups} by={by} minN={r.min_n} names={names} />
+ <PerformanceCards groups={r.groups} by={by} minN={r.min_n} names={names} />
+ {r.groups.some((g) => g.low_confidence) && (
+ <p className="mt-2 text-[11px] text-zinc-500">“{FEW_TASKS}”: fewer than {r.min_n} finished tasks, so the range is wide and the numbers can still change a lot.</p>
+ )}
+ </div>
+ );
+};
+
+/** Insights → Performance. Loads on its own; hides itself if the server says it isn't for this viewer (403). */
+export const PerformancePanel: React.FC<{
+ names?: Record<string, string>;
+ /** Changes when the board refreshes, so the numbers reload with it. */
+ refreshKey?: number;
+ load?: (q: PerfQuery) => Promise<PerfReport>;
+}> = ({ names, refreshKey = 0, load = loadPerformance }) => {
+ const ids = { title: useId(), cls: useId(), bot: useId(), since: useId() };
+ const [by, setBy] = useState<PerfBy>('bot');
+ const [since, setSince] = useState<PerfSince>('30d');
+ const [cls, setCls] = useState('');
+ const [bot, setBot] = useState('');
+ const [report, setReport] = useState<PerfReport | null>(null);
+ const [error, setError] = useState<PerfError | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [classes, setClasses] = useState<Record<string, string>>({});
+ const [bots, setBots] = useState<Record<string, string>>({});
+ const seq = useRef(0);
+
+ const fetchNow = useCallback(() => {
+ const mine = ++seq.current;
+ setLoading(true);
+ load({ by, since, class: cls || undefined, bot: bot || undefined }).then(
+ (r) => {
+ if (mine !== seq.current) return;
+ setReport(r);
+ setError(null);
+ setLoading(false);
+ setClasses((p) => mergeOptions(p, r.groups, (g) => [g.task_class, classText(g.task_class)]));
+ setBots((p) => mergeOptions(p, r.groups, (g) => [g.kwant_id, botName(g, names)]));
+ },
+ (e) => {
+ if (mine !== seq.current) return;
+ setError(e instanceof PerfError ? e : new PerfError(e instanceof Error ? e.message : 'Something went wrong.', 0));
+ setLoading(false);
+ },
+ );
+ }, [load, by, since, cls, bot, names]);
+
+ useEffect(() => {
+ fetchNow();
+ }, [fetchNow, refreshKey]);
+
+ if (perfView({ report, error, loading }) === 'hidden') return null;
+ const filtered = !!cls || !!bot;
+ const options = (m: Record<string, string>) => Object.entries(m).sort((a, b) => a[1].localeCompare(b[1]));
+ return (
+ <section aria-labelledby={ids.title} className={`${card} p-3 sm:p-4 space-y-3`} data-performance>
+ <div className="flex flex-wrap items-start gap-2">
+ <Gauge size={16} className="mt-0.5 shrink-0 text-sky-400" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <h3 id={ids.title} className="text-sm font-semibold text-zinc-100">
+ Performance
+ </h3>
+ <p className="mt-0.5 text-xs text-zinc-400">How often each bot’s finished work ends Verified, and what it takes.</p>
+ <p className="mt-0.5 text-[11px] text-zinc-500" data-report-only>
+ {REPORT_ONLY_TEXT}
+ </p>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <div role="group" aria-label="Group by" className="inline-flex rounded-lg border border-zinc-800 p-0.5">
+ {(['bot', 'model'] as const).map((v) => (
+ <button
+ key={v}
+ type="button"
+ aria-pressed={by === v}
+ onClick={() => setBy(v)}
+ className={`min-h-[40px] sm:min-h-[28px] px-3 rounded-md text-xs font-medium ${focusRing} ${by === v ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200'}`}
+ >
+ {v === 'bot' ? 'By bot' : 'By model'}
+ </button>
+ ))}
+ </div>
+ <label htmlFor={ids.cls} className="sr-only">
+ Kind of work
+ </label>
+ <select id={ids.cls} value={cls} onChange={(e) => setCls(e.target.value)} className={select}>
+ <option value="">All kinds of work</option>
+ {options(classes).map(([k, v]) => (
+ <option key={k} value={k}>
+ {v}
+ </option>
+ ))}
+ </select>
+ <label htmlFor={ids.bot} className="sr-only">
+ Bot
+ </label>
+ <select id={ids.bot} value={bot} onChange={(e) => setBot(e.target.value)} className={select}>
+ <option value="">All bots</option>
+ {options(bots).map(([k, v]) => (
+ <option key={k} value={k}>
+ {v}
+ </option>
+ ))}
+ </select>
+ <label htmlFor={ids.since} className="sr-only">
+ Period
+ </label>
+ <select id={ids.since} value={since} onChange={(e) => setSince(e.target.value as PerfSince)} className={select}>
+ {SINCE_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <PerformanceBody report={report} error={error} loading={loading} by={by} filtered={filtered} names={names} onRetry={fetchNow} />
+ </section>
+ );
+};
diff --git a/frontend/src/performance.ts b/frontend/src/performance.ts
new file mode 100644
index 00000000..cb6bdeb1
--- /dev/null
+++ b/frontend/src/performance.ts
@@ -0,0 +1,163 @@
+// Performance Market (Phase D1, docs/mission-control.md §17): how each bot does per kind of work.
+// Report only: nothing here (or on the server) changes who gets work. Person-only on the server.
+import { personFetch, PersonCancelledError } from './auth';
+import { classLabel } from './flightSchool';
+import { formatTokens } from './missions';
+
+export type PerfBy = 'bot' | 'model';
+export type PerfSince = '30d' | '90d' | 'all';
+
+export interface PerfGroup {
+ task_class: string;
+ kwant_id: string;
+ kwant_name: string | null;
+ engine: string | null;
+ /** Only when grouped by model. */
+ model?: string;
+ n: number;
+ verified: number;
+ failed: number;
+ unverified: number;
+ verified_rate: number;
+ verified_ci95: [number, number];
+ median_latency_ms: number | null;
+ median_fresh_tokens: number | null;
+ cost_usd: number | null;
+ cost_per_task_usd: number | null;
+ interventions_per_task: number;
+ low_confidence: boolean;
+}
+
+export interface PerfReport {
+ since: string;
+ report_only: boolean;
+ min_n: number;
+ observations?: number;
+ groups: PerfGroup[];
+}
+
+export interface PerfQuery {
+ by: PerfBy;
+ since: PerfSince;
+ class?: string;
+ bot?: string;
+}
+
+export const SINCE_OPTIONS: Array<{ value: PerfSince; label: string }> = [
+ { value: '30d', label: 'Last 30 days' },
+ { value: '90d', label: 'Last 90 days' },
+ { value: 'all', label: 'All time' },
+];
+
+/** "All time" is a date before any kwant data; the server caps `Nd` at 365. */
+const ALL_SINCE = '2000-01-01';
+
+export function perfUrl(q: PerfQuery): string {
+ const p = new URLSearchParams({ by: q.by, since: q.since === 'all' ? ALL_SINCE : q.since });
+ if (q.class) p.set('class', q.class);
+ if (q.bot) p.set('bot', q.bot);
+ return `/api/performance?${p}`;
+}
+
+export class PerfError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ ) {
+ super(message);
+ }
+}
+
+export async function loadPerformance(q: PerfQuery): Promise<PerfReport> {
+ let res: Response;
+ try {
+ res = await personFetch(perfUrl(q), { cache: 'no-store' });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new PerfError(e.message, 401);
+ throw new PerfError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const body = await res.json().catch(() => null);
+ if (res.ok && body && Array.isArray(body.groups)) return body as PerfReport;
+ if (res.ok) throw new PerfError('The server sent a report this app can’t read.', res.status);
+ if (res.status === 404) throw new PerfError('This server doesn’t have performance numbers yet. Update the app.', 404);
+ const err = body && typeof body.error === 'string' && body.error.trim() ? body.error.trim() : `Something went wrong (HTTP ${res.status}).`;
+ throw new PerfError(err, res.status);
+}
+
+/** What the section shows. 403: the server says this isn't the person, so there's no section at all. */
+export type PerfView = 'hidden' | 'loading' | 'error' | 'empty' | 'rows';
+export function perfView(state: { report: PerfReport | null; error: PerfError | null; loading: boolean }): PerfView {
+ if (state.error?.status === 403) return 'hidden';
+ if (state.error) return 'error';
+ if (!state.report) return 'loading';
+ return state.report.groups.length ? 'rows' : 'empty';
+}
+
+const pct = (x: number) => Math.round(Math.max(0, Math.min(1, x)) * 100);
+
+/** "56% (27–81%)": the verified rate with its 95% interval. */
+export function rateText(rate: number, ci: [number, number] | null | undefined): string {
+ const r = `${pct(rate)}%`;
+ if (!ci || ci.length !== 2) return r;
+ return `${r} (${pct(ci[0])}–${pct(ci[1])}%)`;
+}
+
+/** Screen-reader form: "56% verified, likely between 27% and 81%". */
+export function rateLabel(rate: number, ci: [number, number] | null | undefined): string {
+ const r = `${pct(rate)}% verified`;
+ if (!ci || ci.length !== 2) return r;
+ return `${r}, likely between ${pct(ci[0])}% and ${pct(ci[1])}%`;
+}
+
+/** "45 s", "3.5 min", "1.2 h"; "—" when unknown. */
+export function latencyText(ms: number | null | undefined): string {
+ if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return '—';
+ const s = ms / 1000;
+ if (s < 60) return `${Math.max(1, Math.round(s))} s`;
+ const m = s / 60;
+ if (m < 60) return `${m < 10 ? m.toFixed(1).replace(/\.0$/, '') : Math.round(m)} min`;
+ const h = m / 60;
+ return `${h < 10 ? h.toFixed(1).replace(/\.0$/, '') : Math.round(h)} h`;
+}
+
+export function tokensText(n: number | null | undefined): string {
+ return n === null || n === undefined || !Number.isFinite(n) ? '—' : formatTokens(n);
+}
+
+/** "$0.15", "<$0.01", "—" when no run reported a cost. */
+export function costText(usd: number | null | undefined): string {
+ if (usd === null || usd === undefined || !Number.isFinite(usd)) return '—';
+ if (usd === 0) return '$0';
+ if (usd < 0.01) return '<$0.01';
+ return `$${usd < 10 ? usd.toFixed(2) : Math.round(usd)}`;
+}
+
+/** Interventions per task: "0", "0.4", "2". */
+export function perTaskText(x: number | null | undefined): string {
+ if (x === null || x === undefined || !Number.isFinite(x)) return '—';
+ return x === 0 ? '0' : x < 10 ? x.toFixed(1).replace(/\.0$/, '') : String(Math.round(x));
+}
+
+export const FEW_TASKS = 'few tasks';
+
+export function botName(g: Pick<PerfGroup, 'kwant_name' | 'kwant_id'>, names: Record<string, string> = {}): string {
+ return g.kwant_name || names[g.kwant_id] || 'Removed bot';
+}
+
+/** "Claude Opus" style labels aren't known here; show the model id, or say no usage matched. */
+export function modelText(m: string | undefined): string {
+ if (!m || m === 'unknown' || m === 'auto') return 'Not reported';
+ return m;
+}
+
+export const classText = classLabel;
+
+/** Options seen so far, kept across filter changes so a filter never hides its own choices. */
+export function mergeOptions(prev: Record<string, string>, groups: PerfGroup[], pick: (g: PerfGroup) => [string, string]): Record<string, string> {
+ const next = { ...prev };
+ for (const g of groups) {
+ const [k, v] = pick(g);
+ next[k] = v;
+ }
+ return next;
+}
diff --git a/frontend/tests/performance.test.mjs b/frontend/tests/performance.test.mjs
new file mode 100644
index 00000000..94cd3b33
--- /dev/null
+++ b/frontend/tests/performance.test.mjs
@@ -0,0 +1,169 @@
+// Insights → Performance (Phase D1, docs/mission-control.md §17): a read-only table of how each bot
+// does per kind of work, from GET /api/performance. The verified rate shows its 95% range, groups
+// under min_n say "few tasks", an empty report says numbers appear as tasks finish, it says it
+// doesn't change who gets work, and a 403 hides the whole section.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const p = await loadBundled(`export * from './src/performance';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { PerformanceBody, PerformancePanel, EMPTY_TEXT, FILTERED_EMPTY_TEXT, REPORT_ONLY_TEXT } from './src/components/PerformancePanel';
+ import { PerfError } from './src/performance';
+ export { createRoot } from 'react-dom/client';
+ export { React, PerformancePanel, PerfError, EMPTY_TEXT, FILTERED_EMPTY_TEXT, REPORT_ONLY_TEXT };
+ export const body = (props) => renderToStaticMarkup(React.createElement(PerformanceBody, props));
+`);
+
+const group = (over = {}) => ({
+ task_class: 'general', kwant_id: 'k_shelly', kwant_name: 'Shelly', engine: 'cli',
+ n: 9, verified: 5, failed: 3, unverified: 1, verified_rate: 0.5556, verified_ci95: [0.2666, 0.8112],
+ median_latency_ms: 81_234, median_fresh_tokens: 23_110, cost_usd: 1.38, cost_per_task_usd: 0.153,
+ interventions_per_task: 0.4444, low_confidence: false, ...over,
+});
+const report = (groups) => ({ since: '2026-09-29T00:00:00Z', report_only: true, min_n: 5, observations: groups.reduce((n, x) => n + x.n, 0), groups });
+const noop = () => {};
+
+test('verified rate reads as "56% (27–81%)" and clamps', () => {
+ assert.equal(p.rateText(0.5556, [0.2666, 0.8112]), '56% (27–81%)');
+ assert.equal(p.rateText(1, [0.5655, 1]), '100% (57–100%)');
+ assert.equal(p.rateText(0, null), '0%');
+ assert.equal(p.rateText(1.2, [-0.1, 1.3]), '100% (0–100%)');
+ assert.equal(p.rateLabel(0.75, [0.4677, 0.9111]), '75% verified, likely between 47% and 91%');
+});
+
+test('time, tokens, cost and per-task numbers', () => {
+ assert.equal(p.latencyText(81_234), '1.4 min');
+ assert.equal(p.latencyText(400), '1 s');
+ assert.equal(p.latencyText(45_000), '45 s');
+ assert.equal(p.latencyText(30 * 60_000), '30 min');
+ assert.equal(p.latencyText(90 * 60_000), '1.5 h');
+ assert.equal(p.latencyText(null), '—');
+ assert.equal(p.tokensText(23_110), '23.1k');
+ assert.equal(p.tokensText(null), '—');
+ assert.equal(p.costText(0.153), '$0.15');
+ assert.equal(p.costText(0.004), '<$0.01');
+ assert.equal(p.costText(0), '$0');
+ assert.equal(p.costText(12.6), '$13');
+ assert.equal(p.costText(null), '—');
+ assert.equal(p.perTaskText(0.4444), '0.4');
+ assert.equal(p.perTaskText(0), '0');
+ assert.equal(p.perTaskText(2), '2');
+ assert.equal(p.modelText('auto'), 'Not reported');
+ assert.equal(p.modelText('claude-opus-5-5'), 'claude-opus-5-5');
+ assert.equal(p.botName({ kwant_name: null, kwant_id: 'k_x' }, { k_x: 'Rex' }), 'Rex');
+ assert.equal(p.botName({ kwant_name: null, kwant_id: 'k_gone' }), 'Removed bot');
+});
+
+test('the URL carries by, since and only the filters that are set; All time is a date', () => {
+ assert.equal(p.perfUrl({ by: 'bot', since: '30d' }), '/api/performance?by=bot&since=30d');
+ assert.equal(p.perfUrl({ by: 'model', since: '90d', class: 'research', bot: 'k_1' }), '/api/performance?by=model&since=90d&class=research&bot=k_1');
+ assert.equal(p.perfUrl({ by: 'bot', since: 'all' }), '/api/performance?by=bot&since=2000-01-01');
+});
+
+test('which state shows: 403 hides, other errors show, no groups is empty', () => {
+ const E = (s) => new p.PerfError('x', s);
+ assert.equal(p.perfView({ report: null, error: E(403), loading: false }), 'hidden');
+ assert.equal(p.perfView({ report: null, error: E(500), loading: false }), 'error');
+ assert.equal(p.perfView({ report: null, error: null, loading: true }), 'loading');
+ assert.equal(p.perfView({ report: report([]), error: null, loading: false }), 'empty');
+ assert.equal(p.perfView({ report: report([group()]), error: null, loading: true }), 'rows');
+});
+
+test('rows: the range, the numbers, and "few tasks" only on small groups', () => {
+ const html = ui.body({ report: report([group(), group({ kwant_id: 'k_rex', kwant_name: 'Rex', n: 3, verified: 2, verified_rate: 0.6667, verified_ci95: [0.2077, 0.9385], low_confidence: true })]), error: null, loading: false, by: 'bot', filtered: false, onRetry: noop });
+ assert.match(html, /56% \(27–81%\)/);
+ assert.match(html, /67% \(21–94%\)/);
+ assert.match(html, /1\.4 min/);
+ assert.match(html, /23\.1k/);
+ assert.match(html, /\$0\.15/);
+ assert.equal((html.match(/data-few-tasks/g) ?? []).length, 2, 'table and phone card for Rex only');
+ assert.match(html, /fewer than 5 finished tasks/);
+ assert.doesNotMatch(html, /Model</, 'no model column when grouped by bot');
+ const byModel = ui.body({ report: report([group({ model: 'auto' })]), error: null, loading: false, by: 'model', filtered: false, onRetry: noop });
+ assert.match(byModel, /Model</);
+ assert.match(byModel, /Not reported/);
+ assert.doesNotMatch(byModel, /data-few-tasks/);
+});
+
+test('empty, filtered empty, error and 403 bodies', () => {
+ assert.match(ui.body({ report: report([]), error: null, loading: false, by: 'bot', filtered: false, onRetry: noop }), new RegExp(ui.EMPTY_TEXT));
+ assert.equal(ui.EMPTY_TEXT, 'No finished tasks yet. Numbers appear as tasks finish.');
+ assert.match(ui.body({ report: report([]), error: null, loading: false, by: 'bot', filtered: true, onRetry: noop }), new RegExp(ui.FILTERED_EMPTY_TEXT));
+ const err = ui.body({ report: null, error: new ui.PerfError('Server is busy.', 500), loading: false, by: 'bot', filtered: false, onRetry: noop });
+ assert.match(err, /role="alert"/);
+ assert.match(err, /Couldn’t load performance\. Server is busy\./);
+ assert.match(err, />Retry</);
+ assert.match(ui.body({ report: null, error: new ui.PerfError('x', 401), loading: false, by: 'bot', filtered: false, onRetry: noop }), /Only you can see these numbers/);
+ assert.equal(ui.body({ report: null, error: new ui.PerfError('x', 403), loading: false, by: 'bot', filtered: false, onRetry: noop }), '');
+});
+
+const flush = async () => {
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mount = async (load) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ root.render(ui.React.createElement(ui.PerformancePanel, { load }));
+ await flush();
+ return { host, root };
+};
+
+test('the panel says it is report-only, and a 403 hides the whole section', async () => {
+ const ok = await mount(async () => report([]));
+ assert.ok(ok.host.querySelector('[data-performance]'));
+ assert.match(ok.host.textContent, new RegExp(ui.REPORT_ONLY_TEXT));
+ assert.match(ok.host.textContent, /No finished tasks yet/);
+ ok.root.unmount();
+ const denied = await mount(async () => {
+ throw new ui.PerfError('Only the person can see this.', 403);
+ });
+ assert.equal(denied.host.innerHTML, '');
+ denied.root.unmount();
+});
+
+test('filters reload with by, class, bot and since; choices stay listed after filtering', async () => {
+ const calls = [];
+ const load = async (q) => {
+ calls.push(q);
+ return report(q.class ? [group({ task_class: q.class })] : [group(), group({ task_class: 'research', kwant_id: 'k_rex', kwant_name: 'Rex' })]);
+ };
+ const { host, root } = await mount(load);
+ assert.deepEqual(calls[0], { by: 'bot', since: '30d', class: undefined, bot: undefined });
+ const [cls, , since] = host.querySelectorAll('select');
+ assert.deepEqual([...cls.options].map((o) => o.textContent), ['All kinds of work', 'General', 'research']);
+ const change = async (el, v) => {
+ el.value = v;
+ el.dispatchEvent(new window.Event('change', { bubbles: true }));
+ await flush();
+ };
+ await change(cls, 'research');
+ assert.equal(calls.at(-1).class, 'research');
+ assert.equal(host.querySelectorAll('select')[0].options.length, 3, 'filtering by a class keeps the others listed');
+ await change(since, 'all');
+ assert.equal(calls.at(-1).since, 'all');
+ const byModel = [...host.querySelectorAll('button[aria-pressed]')].find((b) => b.textContent === 'By model');
+ byModel.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await flush();
+ assert.equal(calls.at(-1).by, 'model');
+ assert.equal(byModel.getAttribute('aria-pressed'), 'true');
+ root.unmount();
+});
+
+test('the board shows Performance on All work only, and Refresh reloads it', () => {
+ const src = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');
+ assert.match(src, /showPerformance && !mission && !needsToken && <PerformancePanel names=\{names\} refreshKey=\{refreshCount\} \/>/);
+ assert.match(src, /setRefreshCount\(\(n\) => n \+ 1\)/);
+});