Skip to content

Replay your coding agent sessions as a map and a timeline

feat(insights): Insights view with PR rate, spend, failures, search heatmap, waste and compaction

aiswaryasankartest58e442804ee2
diff --git a/python/src/agentplay/facts.py b/python/src/agentplay/facts.py
index b6c3e28..6242863 100644
--- a/python/src/agentplay/facts.py
+++ b/python/src/agentplay/facts.py
@@ -174,11 +174,12 @@ def compute(doc: dict[str, Any]) -> dict[str, Any]:
last_edit = max((e["seq"] for e in edits), default=None)
users = [e for e in evs if e["kind"] == "user" and e.get("agent") == "main"]
- by_source: dict[str, int] = {}
+ by_source: dict[str, dict[str, int]] = {}
for e in evs:
if e.get("err"):
- src = _error_source(e)
- by_source[src] = by_source.get(src, 0) + 1
+ classes = by_source.setdefault(_error_source(e), {})
+ cls = str(e.get("errClass") or "other")
+ classes[cls] = classes.get(cls, 0) + 1
return {
"outcome": outcome,
@@ -186,7 +187,8 @@ def compute(doc: dict[str, Any]) -> dict[str, Any]:
"prsCreated": int(t.get("prsCreated") or 0),
"prsMerged": int(t.get("prsMerged") or 0),
"costUsd": float(t.get("costUsd") or 0.0),
- "hasCost": any("cost" in e for e in llm),
+ # Cursor writes requests with no usable cost; a zero total means "unknown", not "free".
+ "hasCost": float(t.get("costUsd") or 0.0) > 0,
"tokens": {
"in": sum(int(e.get("in") or 0) for e in llm),
"cw": sum(int(e.get("cw") or 0) for e in llm),
diff --git a/python/tests/test_facts.py b/python/tests/test_facts.py
index 7a41849..f36d0cb 100644
--- a/python/tests/test_facts.py
+++ b/python/tests/test_facts.py
@@ -59,7 +59,7 @@ def test_commands_files_prompt_and_verify():
assert f["files"] == {"acme/api:src/a.ts": {"hits": 3, "reads": 2, "edits": 1}} # untouched files dropped
assert f["firstPromptChars"] == 420 and f["userTurns"] == 2
assert f["edited"] is True and f["verifyAfterLastEdit"] is True
- assert f["errorsBySource"] == {"tool": 1}
+ assert f["errorsBySource"] == {"tool": {"exit_code": 1}}
def test_waste_charges_each_request_once_in_bucket_order():
diff --git a/viewer/public/demo/index.json b/viewer/public/demo/index.json
index eba4325..8cd61b8 100644
--- a/viewer/public/demo/index.json
+++ b/viewer/public/demo/index.json
@@ -106,8 +106,12 @@
"overloaded": 1
},
"errorsBySource": {
- "tool": 1,
- "llm": 1
+ "tool": {
+ "exit_code": 1
+ },
+ "llm": {
+ "overloaded": 1
+ }
},
"files": {
"acme/api:README.md": {
@@ -275,7 +279,9 @@
"exit_code": 2
},
"errorsBySource": {
- "tool": 2
+ "tool": {
+ "exit_code": 2
+ }
},
"files": {
"acme/web:src/lib/formatDate.ts": {
@@ -359,7 +365,7 @@
"prsCreated": 0,
"prsMerged": 0,
"costUsd": 0.0,
- "hasCost": true,
+ "hasCost": false,
"tokens": {
"in": 0,
"cw": 0,
diff --git a/viewer/src/App.tsx b/viewer/src/App.tsx
index 4bf3784..252d8a7 100644
--- a/viewer/src/App.tsx
+++ b/viewer/src/App.tsx
@@ -9,6 +9,8 @@ import {
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { SessionExplorer } from '@/explorer/SessionExplorer';
+import { InsightsView } from '@/insights/InsightsView';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { SessionExplorerSkeleton } from '@/explorer/SessionExplorerStates';
import { WINDOW_KEYS, type WindowKey } from '@/core/windowOptions';
import { SessionMapSourceProvider } from '@/data/SourceContext';
@@ -90,6 +92,11 @@ export function App() {
'win',
parseAsStringEnum<WindowKey>([...WINDOW_KEYS]).withDefault('all')
);
+ // Which page: the session explorer or the cross-session Insights view.
+ const [tab, setTab] = useQueryState(
+ 'tab',
+ parseAsStringEnum(['sessions', 'insights'] as const).withDefault('sessions')
+ );
const inputRef = useRef<HTMLInputElement>(null);
const openFiles = useCallback(
@@ -174,6 +181,8 @@ export function App() {
onBack={openedFiles ? () => setShowFiles(false) : undefined}
baseLabel={baseSource.label}
account={mode === 'server' ? <AccountChip base={base} state={account.data} /> : null}
+ tab={tab}
+ onTab={(t) => void setTab(t === 'sessions' ? null : t)}
/>
{mode !== 'probing' ? <PlatformBanner /> : null}
{mode === 'demo' && source === demo ? (
@@ -186,6 +195,12 @@ export function App() {
{notice ? <OpenNotice result={notice} onClose={() => setNotice(null)} /> : null}
{mode === 'probing' ? (
<SessionExplorerSkeleton />
+ ) : tab === 'insights' ? (
+ <InsightsView
+ key={`insights:${source.id}`}
+ windowKey={windowKey}
+ onWindowChange={(k) => void setWindowKey(k === 'all' ? null : k)}
+ />
) : (
<SessionExplorer
key={`explorer:${source.id}`}
@@ -209,6 +224,8 @@ function AppBar({
onBack,
baseLabel,
account,
+ tab,
+ onTab,
}: {
mode: Mode;
source: SessionMapSource;
@@ -216,12 +233,14 @@ function AppBar({
onBack?: () => void;
baseLabel: string;
account: ReactNode;
+ tab: 'sessions' | 'insights';
+ onTab: (tab: 'sessions' | 'insights') => void;
}) {
const { theme, toggle } = useTheme();
const status = useSessionExplorerStatus();
const count = mode === 'probing' ? null : (status.data?.mapCount ?? null);
return (
- <header className="flex shrink-0 items-center gap-3">
+ <header className="flex shrink-0 flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<img src="entelligence-logo.svg" alt="" className="size-7" />
<span className="ds-text-body-sm-semibold text-ds-text-darker">agentplay</span>
@@ -233,6 +252,19 @@ function AppBar({
{status.data?.scanning ? ' · scanning…' : ''}
</Badge>
) : null}
+ {mode !== 'probing' ? (
+ <ToggleGroup
+ value={[tab]}
+ onValueChange={(v: unknown[]) => {
+ const next = v.find((x): x is 'sessions' | 'insights' => x === 'sessions' || x === 'insights');
+ if (next) onTab(next);
+ }}
+ aria-label="View"
+ >
+ <ToggleGroupItem value="sessions">Sessions</ToggleGroupItem>
+ <ToggleGroupItem value="insights">Insights</ToggleGroupItem>
+ </ToggleGroup>
+ ) : null}
{onBack ? (
<Button variant="ghost" size="sm" className="h-7 px-2 text-ds-text-subtle" onClick={onBack}>
Back to {baseLabel.toLowerCase()}
diff --git a/viewer/src/core/insights.test.ts b/viewer/src/core/insights.test.ts
new file mode 100644
index 0000000..e47f001
--- /dev/null
+++ b/viewer/src/core/insights.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from 'vitest';
+import {
+ compactionSummary,
+ failuresBySource,
+ fileHeat,
+ filterSessions,
+ headline,
+ insightsStatsSchema,
+ outcomesByWeek,
+ prRate,
+ spendByDay,
+ topFailingCommands,
+ wasteSummary,
+ weekStart,
+ type InsightsSession,
+ type SessionFacts,
+} from './insights';
+import { squarify } from './treemap';
+
+const facts = (over: Partial<SessionFacts> = {}): SessionFacts => ({
+ outcome: 'completed',
+ edited: false,
+ prsCreated: 0,
+ prsMerged: 0,
+ costUsd: 1,
+ hasCost: true,
+ costByModel: { 'claude-sonnet-4-5': 1 },
+ calls: 10,
+ errors: 0,
+ retries: 0,
+ cmd: {},
+ errorsBySource: {},
+ files: {},
+ compactions: 0,
+ preTokens: [],
+ rereadsAfterCompaction: 0,
+ verifyAfterLastEdit: false,
+ waste: { retry: 0, abandoned: 0, cacheMiss: 0, reread: 0, deadSubagent: 0 },
+ stallMs: 0,
+ firstPromptChars: 0,
+ userTurns: 1,
+ ...over,
+});
+
+const row = (id: string, over: Partial<SessionFacts> = {}, rest: Partial<InsightsSession> = {}): InsightsSession => ({
+ sessionId: id,
+ sessionDate: '2026-10-14',
+ startedAt: '2026-10-14T10:00:00Z',
+ agentTool: 'claude-code',
+ models: ['claude-sonnet-4-5'],
+ repos: ['acme/api'],
+ facts: facts(over),
+ ...rest,
+});
+
+describe('PR rate', () => {
+ it('counts only sessions that edited code', () => {
+ const rows = [
+ row('a', { edited: true, prsCreated: 1 }),
+ row('b', { edited: true }),
+ row('c'), // answered a question: neither helps nor hurts
+ ];
+ expect(prRate(rows)).toEqual({ edited: 2, opened: 1, rate: 0.5 });
+ expect(prRate([row('x')]).rate).toBeNull();
+ });
+
+ it('keeps sessions with no cost out of spend and cost per PR', () => {
+ const h = headline([
+ row('a', { edited: true, prsCreated: 2, prsMerged: 1, costUsd: 4 }),
+ row('b', { hasCost: false, costUsd: 0, edited: true, prsCreated: 1 }, { agentTool: 'cursor' }),
+ ]);
+ expect(h.spend).toBe(4);
+ expect(h.noCost).toBe(1);
+ expect(h.costPerPr).toBe(2); // $4 over the 2 PRs from priced sessions
+ expect(h.prsOpened).toBe(3);
+ expect(h.prsMerged).toBe(1);
+ });
+});
+
+describe('filters and weeks', () => {
+ it('filters by agent, repo and model', () => {
+ const rows = [row('a'), row('b', {}, { agentTool: 'codex', repos: ['acme/web'] })];
+ expect(filterSessions(rows, { agent: 'codex' }).map((r) => r.sessionId)).toEqual(['b']);
+ expect(filterSessions(rows, { repo: 'acme/api' }).map((r) => r.sessionId)).toEqual(['a']);
+ expect(filterSessions(rows, { model: 'gpt-5' })).toEqual([]);
+ });
+
+ it('buckets weeks from Monday and counts outcomes', () => {
+ expect(weekStart('2026-10-14')).toBe('2026-10-12');
+ expect(weekStart('2026-10-12')).toBe('2026-10-12');
+ expect(weekStart('2026-10-18')).toBe('2026-10-12');
+ const weeks = outcomesByWeek([
+ row('a', { outcome: 'pr_created', edited: true, prsCreated: 1 }),
+ row('b', { outcome: 'weird' }),
+ row('c', {}, { sessionDate: '2026-10-05' }),
+ ]);
+ expect(weeks.map((w) => w.week)).toEqual(['2026-10-05', '2026-10-12']);
+ expect(weeks[1].counts.pr_created).toBe(1);
+ expect(weeks[1].counts.completed).toBe(1); // unknown outcomes fold into completed
+ expect(weeks[1].pr.rate).toBe(1);
+ });
+});
+
+describe('spend', () => {
+ it('splits by agent or model and folds the tail into Other', () => {
+ const rows = [
+ row('a', { costUsd: 3, costByModel: { m1: 2, m2: 1 } }),
+ row('b', { costUsd: 1, costByModel: { m3: 1 } }, { agentTool: 'codex', sessionDate: '2026-10-15' }),
+ ];
+ const byAgent = spendByDay(rows, 'agent');
+ expect(byAgent.series).toEqual([
+ { key: 'claude-code', total: 3 },
+ { key: 'codex', total: 1 },
+ ]);
+ const byModel = spendByDay(rows, 'model', 1);
+ expect(byModel.series.map((s) => s.key)).toEqual(['m1', 'Other']);
+ expect(byModel.days[0].parts).toEqual({ m1: 2, Other: 1 });
+ });
+});
+
+describe('failures', () => {
+ it('ranks commands by failures with their error classes', () => {
+ const rows = [
+ row('a', { cmd: { pytest: { calls: 4, fails: 2, retries: 1, byClass: { exit_code: 2 } } } }),
+ row('b', { cmd: { pytest: { calls: 2, fails: 1, retries: 0, byClass: { timeout: 1 } }, ls: { calls: 9, fails: 0, retries: 0, byClass: {} } } }),
+ ];
+ const [top, ...rest] = topFailingCommands(rows);
+ expect(rest).toEqual([]); // commands that never failed are left out
+ expect(top).toMatchObject({ verb: 'pytest', calls: 6, fails: 3, retries: 1, sessions: 2 });
+ expect(top.failRate).toBeCloseTo(0.5);
+ expect(top.byClass).toEqual({ exit_code: 2, timeout: 1 });
+ });
+
+ it('groups failures by source in a fixed order', () => {
+ const groups = failuresBySource([
+ row('a', { errorsBySource: { llm: { rate_limit: 2 }, tool: { exit_code: 3, timeout: 1 } } }),
+ ]);
+ expect(groups.map((g) => g.source)).toEqual(['tool', 'llm']);
+ expect(groups[0]).toEqual({ source: 'tool', total: 4, classes: [{ cls: 'exit_code', n: 3 }, { cls: 'timeout', n: 1 }] });
+ });
+});
+
+describe('files, waste and compaction', () => {
+ it('sums file touches across sessions', () => {
+ const heat = fileHeat([
+ row('a', { files: { 'acme/api:src/lib/auth.ts': { hits: 3, reads: 2, edits: 1 } } }),
+ row('b', { files: { 'acme/api:src/lib/auth.ts': { hits: 1, reads: 1, edits: 0 }, 'acme/api:README.md': { hits: 0, reads: 1, edits: 0 } } }),
+ ]);
+ expect(heat[0]).toMatchObject({ key: 'acme/api:src/lib/auth.ts', repo: 'acme/api', dir: 'src/lib/', name: 'auth.ts', sessions: 2, hits: 4, reads: 3, edits: 1 });
+ expect(heat[1]).toMatchObject({ dir: '', name: 'README.md' });
+ });
+
+ it('sums waste over priced sessions and reports its share', () => {
+ const w = wasteSummary([
+ row('a', { costUsd: 10, waste: { retry: 1, abandoned: 2, cacheMiss: 0, reread: 0, deadSubagent: 0 }, stallMs: 5000 }),
+ row('b', { hasCost: false, costUsd: 0, waste: { retry: 9, abandoned: 0, cacheMiss: 0, reread: 0, deadSubagent: 0 } }),
+ ]);
+ expect(w.total).toBe(3);
+ expect(w.share).toBeCloseTo(0.3);
+ expect(w.stallMs).toBe(5000);
+ });
+
+ it('compares PR rate with and without compaction', () => {
+ const c = compactionSummary([
+ row('a', { compactions: 2, preTokens: [100, 300], edited: true }),
+ row('b', { edited: true, prsCreated: 1 }),
+ ]);
+ expect(c.perSession).toBe(1);
+ expect(c.share).toBe(0.5);
+ expect(c.medianPreTokens).toBe(200);
+ expect(c.withCompaction.rate).toBe(0);
+ expect(c.without.rate).toBe(1);
+ });
+});
+
+describe('stats schema', () => {
+ it('drops rows it cannot read instead of failing the page', () => {
+ const parsed = insightsStatsSchema.parse({ sessions: [{ sessionId: 'a', facts: {} }, { nope: 1 }] });
+ expect(parsed.sessions.map((s) => s.sessionId)).toEqual(['a']);
+ expect(parsed.sessions[0].facts.waste.retry).toBe(0);
+ });
+});
+
+describe('squarify', () => {
+ it('fills the box with areas proportional to value', () => {
+ const placed = squarify([6, 6, 4, 3, 2, 2, 1], (v) => v, { x: 0, y: 0, w: 6, h: 4 });
+ expect(placed).toHaveLength(7);
+ const area = placed.reduce((s, p) => s + p.w * p.h, 0);
+ expect(area).toBeCloseTo(24);
+ for (const p of placed) expect(p.w * p.h).toBeCloseTo(p.item);
+ });
+
+ it('skips empty items and an empty box', () => {
+ expect(squarify([0, 0], (v) => v, { x: 0, y: 0, w: 1, h: 1 })).toEqual([]);
+ expect(squarify([1], (v) => v, { x: 0, y: 0, w: 0, h: 1 })).toEqual([]);
+ });
+});
diff --git a/viewer/src/core/insights.ts b/viewer/src/core/insights.ts
new file mode 100644
index 0000000..243a640
--- /dev/null
+++ b/viewer/src/core/insights.ts
@@ -0,0 +1,437 @@
+/**
+ * Insights: cross-session aggregates over per-session facts.
+ *
+ * Facts are computed once per session by the CLI (`agentplay/facts.py`) and
+ * served by `GET /api/stats` (or read off the demo index). Everything here is
+ * a pure function of those rows, so the dashboard and its tests share one
+ * definition of every number. No React, no fetchers.
+ */
+import { z } from 'zod';
+import type { SessionOutcome } from './sessionMapModel';
+
+const count = z.number().catch(0);
+
+const cmdSchema = z.object({
+ calls: count,
+ fails: count,
+ retries: count,
+ byClass: z.record(z.string(), z.number()).catch({}),
+});
+
+const fileSchema = z.object({ hits: count, reads: count, edits: count });
+
+export const sessionFactsSchema = z.object({
+ outcome: z.string().catch('completed'),
+ edited: z.boolean().catch(false),
+ prsCreated: count,
+ prsMerged: count,
+ costUsd: count,
+ hasCost: z.boolean().catch(false),
+ costByModel: z.record(z.string(), z.number()).catch({}),
+ calls: count,
+ errors: count,
+ retries: count,
+ cmd: z.record(z.string(), cmdSchema).catch({}),
+ errorsBySource: z.record(z.string(), z.record(z.string(), z.number())).catch({}),
+ files: z.record(z.string(), fileSchema).catch({}),
+ compactions: count,
+ preTokens: z.array(z.number()).catch([]),
+ rereadsAfterCompaction: count,
+ verifyAfterLastEdit: z.boolean().catch(false),
+ waste: z
+ .object({
+ retry: count,
+ abandoned: count,
+ cacheMiss: count,
+ reread: count,
+ deadSubagent: count,
+ })
+ .catch({ retry: 0, abandoned: 0, cacheMiss: 0, reread: 0, deadSubagent: 0 }),
+ stallMs: count,
+ firstPromptChars: count,
+ userTurns: count,
+});
+export type SessionFacts = z.infer<typeof sessionFactsSchema>;
+
+export const insightsSessionSchema = z.object({
+ sessionId: z.string(),
+ sessionDate: z.string().nullable().catch(null),
+ startedAt: z.string().nullable().catch(null),
+ agentTool: z.string().catch('unknown'),
+ models: z.array(z.string()).catch([]),
+ repos: z.array(z.string()).catch([]),
+ facts: sessionFactsSchema,
+});
+export type InsightsSession = z.infer<typeof insightsSessionSchema>;
+
+export const insightsStatsSchema = z.object({
+ sessions: z
+ .array(z.unknown())
+ .transform((rows) =>
+ rows.flatMap((r) => {
+ const parsed = insightsSessionSchema.safeParse(r);
+ return parsed.success ? [parsed.data] : [];
+ })
+ ),
+});
+export type InsightsStats = z.infer<typeof insightsStatsSchema>;
+
+/** Rates over fewer sessions than this are shown greyed, with their counts. */
+export const MIN_SAMPLE = 10;
+
+export interface InsightsFilter {
+ agent?: string | null;
+ repo?: string | null;
+ model?: string | null;
+}
+
+export function filterSessions(rows: InsightsSession[], f: InsightsFilter): InsightsSession[] {
+ return rows.filter(
+ (r) =>
+ (!f.agent || r.agentTool === f.agent) &&
+ (!f.repo || r.repos.includes(f.repo)) &&
+ (!f.model || r.models.includes(f.model))
+ );
+}
+
+/** The values each filter can take, most common first. */
+export function filterOptions(rows: InsightsSession[]): {
+ agents: string[];
+ repos: string[];
+ models: string[];
+} {
+ const rank = (values: string[]) => {
+ const n = new Map<string, number>();
+ for (const v of values) n.set(v, (n.get(v) ?? 0) + 1);
+ return [...n.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([k]) => k);
+ };
+ return {
+ agents: rank(rows.map((r) => r.agentTool)),
+ repos: rank(rows.flatMap((r) => r.repos)),
+ models: rank(rows.flatMap((r) => r.models)),
+ };
+}
+
+// ------------------------------------------------------------------ headline
+
+export interface PrRate {
+ /** sessions with at least one edit */
+ edited: number;
+ /** of those, sessions that opened a PR */
+ opened: number;
+ /** opened / edited, or null with no edited sessions */
+ rate: number | null;
+}
+
+/** PR rate: sessions that opened a PR over sessions that edited code. A
+ * session that only answered a question or explored neither raises nor
+ * lowers it. */
+export function prRate(rows: InsightsSession[]): PrRate {
+ const edited = rows.filter((r) => r.facts.edited);
+ const opened = edited.filter((r) => r.facts.prsCreated > 0).length;
+ return { edited: edited.length, opened, rate: edited.length ? opened / edited.length : null };
+}
+
+export interface Headline {
+ sessions: number;
+ /** USD over sessions that report cost */
+ spend: number;
+ /** sessions with no cost data (Cursor), left out of every spend figure */
+ noCost: number;
+ pr: PrRate;
+ prsOpened: number;
+ prsMerged: number;
+ costPerPr: number | null;
+}
+
+export function headline(rows: InsightsSession[]): Headline {
+ const priced = rows.filter((r) => r.facts.hasCost);
+ const spend = priced.reduce((s, r) => s + r.facts.costUsd, 0);
+ const prsOpened = rows.reduce((s, r) => s + r.facts.prsCreated, 0);
+ const prsMerged = rows.reduce((s, r) => s + r.facts.prsMerged, 0);
+ const pricedPrs = priced.reduce((s, r) => s + r.facts.prsCreated, 0);
+ return {
+ sessions: rows.length,
+ spend,
+ noCost: rows.length - priced.length,
+ pr: prRate(rows),
+ prsOpened,
+ prsMerged,
+ costPerPr: pricedPrs ? spend / pricedPrs : null,
+ };
+}
+
+// ------------------------------------------------------------------ outcomes
+
+export const OUTCOME_ORDER: SessionOutcome[] = [
+ 'pr_created',
+ 'verified',
+ 'completed',
+ 'interrupted',
+ 'blocked',
+ 'unresolved_errors',
+ 'incomplete',
+];
+
+/** Monday (UTC) of the week holding `iso`, as `YYYY-MM-DD`. */
+export function weekStart(iso: string): string {
+ const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);
+ const dow = (d.getUTCDay() + 6) % 7;
+ d.setUTCDate(d.getUTCDate() - dow);
+ return d.toISOString().slice(0, 10);
+}
+
+export interface OutcomeWeek {
+ week: string;
+ total: number;
+ counts: Record<SessionOutcome, number>;
+ pr: PrRate;
+}
+
+export function outcomesByWeek(rows: InsightsSession[]): OutcomeWeek[] {
+ const byWeek = new Map<string, InsightsSession[]>();
+ for (const r of rows) {
+ const day = r.sessionDate ?? r.startedAt;
+ if (!day) continue;
+ const w = weekStart(day);
+ byWeek.set(w, [...(byWeek.get(w) ?? []), r]);
+ }
+ return [...byWeek.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([week, list]) => {
+ const counts = Object.fromEntries(OUTCOME_ORDER.map((o) => [o, 0])) as Record<SessionOutcome, number>;
+ for (const r of list) {
+ const o = (OUTCOME_ORDER as string[]).includes(r.facts.outcome)
+ ? (r.facts.outcome as SessionOutcome)
+ : 'completed';
+ counts[o] += 1;
+ }
+ return { week, total: list.length, counts, pr: prRate(list) };
+ });
+}
+
+// ------------------------------------------------------------------ spend
+
+export interface SpendDay {
+ day: string;
+ parts: Record<string, number>;
+ total: number;
+}
+
+export interface SpendSeries {
+ key: string;
+ total: number;
+}
+
+/** Spend per day split by agent or model. Series past `maxSeries` fold into "Other". */
+export function spendByDay(
+ rows: InsightsSession[],
+ by: 'agent' | 'model',
+ maxSeries = 5
+): { days: SpendDay[]; series: SpendSeries[] } {
+ const raw = new Map<string, Map<string, number>>();
+ const totals = new Map<string, number>();
+ for (const r of rows) {
+ if (!r.facts.hasCost || !r.sessionDate) continue;
+ const parts: [string, number][] =
+ by === 'agent'
+ ? [[r.agentTool, r.facts.costUsd]]
+ : Object.entries(r.facts.costByModel);
+ const day = raw.get(r.sessionDate) ?? new Map<string, number>();
+ for (const [k, v] of parts) {
+ day.set(k, (day.get(k) ?? 0) + v);
+ totals.set(k, (totals.get(k) ?? 0) + v);
+ }
+ raw.set(r.sessionDate, day);
+ }
+ const ranked = [...totals.entries()].sort((a, b) => b[1] - a[1]);
+ const keep = new Set(ranked.slice(0, maxSeries).map(([k]) => k));
+ const fold = (k: string) => (keep.has(k) ? k : 'Other');
+ const series = new Map<string, number>();
+ for (const [k, v] of ranked) series.set(fold(k), (series.get(fold(k)) ?? 0) + v);
+ const days = [...raw.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([day, m]) => {
+ const parts: Record<string, number> = {};
+ for (const [k, v] of m) parts[fold(k)] = (parts[fold(k)] ?? 0) + v;
+ return { day, parts, total: Object.values(parts).reduce((s, v) => s + v, 0) };
+ });
+ return { days, series: [...series.entries()].map(([key, total]) => ({ key, total })) };
+}
+
+/** Every UTC day from `first` through `last`, so a chart shows quiet days as gaps. */
+export function dayRange(first: string, last: string): string[] {
+ const out: string[] = [];
+ const d = new Date(`${first}T00:00:00Z`);
+ const end = new Date(`${last}T00:00:00Z`);
+ while (d <= end && out.length < 400) {
+ out.push(d.toISOString().slice(0, 10));
+ d.setUTCDate(d.getUTCDate() + 1);
+ }
+ return out;
+}
+
+// ------------------------------------------------------------------ failures
+
+export interface CommandStat {
+ verb: string;
+ calls: number;
+ fails: number;
+ retries: number;
+ failRate: number;
+ byClass: Record<string, number>;
+ sessions: number;
+}
+
+export function topFailingCommands(rows: InsightsSession[], n = 8): CommandStat[] {
+ const m = new Map<string, CommandStat>();
+ for (const r of rows) {
+ for (const [verb, c] of Object.entries(r.facts.cmd)) {
+ const s = m.get(verb) ?? { verb, calls: 0, fails: 0, retries: 0, failRate: 0, byClass: {}, sessions: 0 };
+ s.calls += c.calls;
+ s.fails += c.fails;
+ s.retries += c.retries;
+ if (c.fails) s.sessions += 1;
+ for (const [k, v] of Object.entries(c.byClass)) s.byClass[k] = (s.byClass[k] ?? 0) + v;
+ m.set(verb, s);
+ }
+ }
+ return [...m.values()]
+ .filter((s) => s.fails > 0)
+ .map((s) => ({ ...s, failRate: s.calls ? s.fails / s.calls : 0 }))
+ .sort((a, b) => b.fails - a.fails || b.calls - a.calls)
+ .slice(0, n);
+}
+
+export const ERROR_SOURCES = ['tool', 'mcp', 'llm', 'hook', 'orchestration'] as const;
+
+export interface FailureGroup {
+ source: string;
+ total: number;
+ classes: { cls: string; n: number }[];
+}
+
+export function failuresBySource(rows: InsightsSession[]): FailureGroup[] {
+ const m = new Map<string, Map<string, number>>();
+ for (const r of rows) {
+ for (const [src, classes] of Object.entries(r.facts.errorsBySource)) {
+ const g = m.get(src) ?? new Map<string, number>();
+ for (const [cls, n] of Object.entries(classes)) g.set(cls, (g.get(cls) ?? 0) + n);
+ m.set(src, g);
+ }
+ }
+ const order = (s: string) => {
+ const i = (ERROR_SOURCES as readonly string[]).indexOf(s);
+ return i < 0 ? ERROR_SOURCES.length : i;
+ };
+ return [...m.entries()]
+ .map(([source, g]) => ({
+ source,
+ total: [...g.values()].reduce((s, v) => s + v, 0),
+ classes: [...g.entries()].map(([cls, n]) => ({ cls, n })).sort((a, b) => b.n - a.n),
+ }))
+ .filter((g) => g.total > 0)
+ .sort((a, b) => order(a.source) - order(b.source));
+}
+
+// ------------------------------------------------------------------ files
+
+export interface FileHeat {
+ /** `repo:path` */
+ key: string;
+ repo: string;
+ path: string;
+ dir: string;
+ name: string;
+ sessions: number;
+ hits: number;
+ reads: number;
+ edits: number;
+}
+
+export function fileHeat(rows: InsightsSession[]): FileHeat[] {
+ const m = new Map<string, FileHeat>();
+ for (const r of rows) {
+ for (const [key, f] of Object.entries(r.facts.files)) {
+ const cut = key.indexOf(':');
+ const repo = cut >= 0 ? key.slice(0, cut) : '';
+ const path = cut >= 0 ? key.slice(cut + 1) : key;
+ const slash = path.lastIndexOf('/');
+ const h = m.get(key) ?? {
+ key,
+ repo,
+ path,
+ dir: slash >= 0 ? path.slice(0, slash + 1) : '',
+ name: slash >= 0 ? path.slice(slash + 1) : path,
+ sessions: 0,
+ hits: 0,
+ reads: 0,
+ edits: 0,
+ };
+ h.sessions += 1;
+ h.hits += f.hits;
+ h.reads += f.reads;
+ h.edits += f.edits;
+ m.set(key, h);
+ }
+ }
+ return [...m.values()].sort((a, b) => b.hits - a.hits || b.sessions - a.sessions);
+}
+
+// ------------------------------------------------------------------ waste
+
+export const WASTE_BUCKETS = ['abandoned', 'retry', 'cacheMiss', 'reread', 'deadSubagent'] as const;
+export type WasteBucket = (typeof WASTE_BUCKETS)[number];
+
+export interface WasteSummary {
+ buckets: Record<WasteBucket, number>;
+ total: number;
+ /** share of priced spend, or null with no spend */
+ share: number | null;
+ stallMs: number;
+}
+
+export function wasteSummary(rows: InsightsSession[]): WasteSummary {
+ const buckets = Object.fromEntries(WASTE_BUCKETS.map((b) => [b, 0])) as Record<WasteBucket, number>;
+ let spend = 0;
+ let stallMs = 0;
+ for (const r of rows) {
+ stallMs += r.facts.stallMs;
+ if (!r.facts.hasCost) continue;
+ spend += r.facts.costUsd;
+ for (const b of WASTE_BUCKETS) buckets[b] += r.facts.waste[b];
+ }
+ const total = WASTE_BUCKETS.reduce((s, b) => s + buckets[b], 0);
+ return { buckets, total, share: spend ? total / spend : null, stallMs };
+}
+
+// ------------------------------------------------------------------ compaction
+
+export interface CompactionSummary {
+ perSession: number;
+ /** share of sessions with at least one compaction */
+ share: number | null;
+ medianPreTokens: number | null;
+ rereads: number;
+ withCompaction: PrRate;
+ without: PrRate;
+}
+
+const median = (xs: number[]): number | null => {
+ if (!xs.length) return null;
+ const s = [...xs].sort((a, b) => a - b);
+ const mid = Math.floor(s.length / 2);
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
+};
+
+export function compactionSummary(rows: InsightsSession[]): CompactionSummary {
+ const compacted = rows.filter((r) => r.facts.compactions > 0);
+ return {
+ perSession: rows.length ? rows.reduce((s, r) => s + r.facts.compactions, 0) / rows.length : 0,
+ share: rows.length ? compacted.length / rows.length : null,
+ medianPreTokens: median(rows.flatMap((r) => r.facts.preTokens)),
+ rereads: rows.reduce((s, r) => s + r.facts.rereadsAfterCompaction, 0),
+ withCompaction: prRate(compacted),
+ without: prRate(rows.filter((r) => r.facts.compactions === 0)),
+ };
+}
diff --git a/viewer/src/core/treemap.ts b/viewer/src/core/treemap.ts
new file mode 100644
index 0000000..2a1f4d6
--- /dev/null
+++ b/viewer/src/core/treemap.ts
@@ -0,0 +1,83 @@
+/**
+ * Squarified treemap layout (Bruls, Huizing, van Wijk 2000).
+ *
+ * Lays out weighted items in a rectangle so each item's area is proportional
+ * to its value and its aspect ratio stays close to 1. Pure geometry: the
+ * caller decides units (the heatmap uses percentages of its box).
+ */
+
+export interface Rect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+export interface Placed<T> extends Rect {
+ item: T;
+}
+
+export function squarify<T>(items: T[], value: (t: T) => number, box: Rect): Placed<T>[] {
+ const entries = items
+ .map((item) => ({ item, v: Math.max(0, value(item)) }))
+ .filter((e) => e.v > 0)
+ .sort((a, b) => b.v - a.v);
+ const total = entries.reduce((s, e) => s + e.v, 0);
+ if (!total || box.w <= 0 || box.h <= 0) return [];
+ const k = (box.w * box.h) / total;
+ const nodes = entries.map((e) => ({ item: e.item, a: e.v * k }));
+ const out: Placed<T>[] = [];
+ let { x, y, w, h } = box;
+
+ const worst = (row: { a: number }[], side: number) => {
+ const s = row.reduce((t, n) => t + n.a, 0);
+ let max = -Infinity;
+ let min = Infinity;
+ for (const n of row) {
+ max = Math.max(max, n.a);
+ min = Math.min(min, n.a);
+ }
+ return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min));
+ };
+
+ const lay = (row: { item: T; a: number }[]) => {
+ const s = row.reduce((t, n) => t + n.a, 0);
+ if (w >= h) {
+ const cw = s / h;
+ let cy = y;
+ for (const n of row) {
+ const ch = n.a / cw;
+ out.push({ item: n.item, x, y: cy, w: cw, h: ch });
+ cy += ch;
+ }
+ x += cw;
+ w -= cw;
+ } else {
+ const ch = s / w;
+ let cx = x;
+ for (const n of row) {
+ const cw = n.a / ch;
+ out.push({ item: n.item, x: cx, y, w: cw, h: ch });
+ cx += cw;
+ }
+ y += ch;
+ h -= ch;
+ }
+ };
+
+ let row: { item: T; a: number }[] = [];
+ let i = 0;
+ while (i < nodes.length) {
+ const side = Math.min(w, h);
+ const next = nodes[i];
+ if (!row.length || worst([...row, next], side) <= worst(row, side)) {
+ row.push(next);
+ i += 1;
+ } else {
+ lay(row);
+ row = [];
+ }
+ }
+ if (row.length) lay(row);
+ return out;
+}
diff --git a/viewer/src/data/demoSource.ts b/viewer/src/data/demoSource.ts
index cb899a0..dcf8b16 100644
--- a/viewer/src/data/demoSource.ts
+++ b/viewer/src/data/demoSource.ts
@@ -2,6 +2,7 @@ import {
sessionExplorerSessionSchema,
type SessionExplorerSession,
} from '@/core/schema';
+import { insightsStatsSchema } from '@/core/insights';
import { SessionExplorerError } from './errors';
import { listRows } from './memoryListing';
import { parseMapBytes } from './parse';
@@ -17,13 +18,20 @@ type DemoRow = SessionExplorerSession & { file?: string };
*/
export function demoSource(root = 'demo/'): SessionMapSource {
const base = new URL(root, document.baseURI);
+ let raw: Promise<{ sessions?: unknown[] }> | null = null;
let index: Promise<DemoRow[]> | null = null;
- const load = () =>
- (index ??= fetch(new URL('index.json', base))
+ const loadRaw = () =>
+ (raw ??= fetch(new URL('index.json', base))
.then((r) => {
if (!r.ok) throw new SessionExplorerError('demo index missing', 'not_found');
return r.json() as Promise<{ sessions?: unknown[] }>;
})
+ .catch((err) => {
+ raw = null;
+ throw err;
+ }));
+ const load = () =>
+ (index ??= loadRaw()
.then((body) =>
(body.sessions ?? []).map((raw) => {
const row = sessionExplorerSessionSchema.parse(raw) as DemoRow;
@@ -58,6 +66,16 @@ export function demoSource(root = 'demo/'): SessionMapSource {
}),
};
},
+ async stats(range) {
+ // The demo index rows carry the same facts `/api/stats` serves
+ // (`scripts/demo_facts.py`); the row schema above drops them, so read raw.
+ const body = await loadRaw();
+ const rows = (body.sessions ?? []).filter((r) => {
+ const day = (r as { sessionDate?: string | null }).sessionDate ?? '';
+ return (!range.from || day >= range.from) && (!range.to || day <= range.to);
+ });
+ return insightsStatsSchema.parse({ sessions: rows });
+ },
async fetchMap(meta) {
const r = await fetch(meta.url);
if (!r.ok) throw new SessionExplorerError(`demo map ${r.status}`, 'not_found');
diff --git a/viewer/src/data/hooks.ts b/viewer/src/data/hooks.ts
index d436885..d4aa91e 100644
--- a/viewer/src/data/hooks.ts
+++ b/viewer/src/data/hooks.ts
@@ -244,3 +244,23 @@ export function useHookDetail(sessionId: string, uuid: string | undefined) {
staleTime: Infinity,
});
}
+
+/** Per-session facts for the Insights view over a date range. Refetches when
+ * a background scan adds maps, like the session list. Disabled on a source
+ * without `stats` (opened files). */
+export function useInsightsStats(range: { from?: string; to?: string }) {
+ const source = useSessionMapSource();
+ const status = useSessionExplorerStatus();
+ const stamp = status.data ? `${status.data.mapCount}:${status.data.scanning}` : '';
+ return useQuery({
+ queryKey: ['insightsStats', source.id, range.from ?? '', range.to ?? '', stamp] as const,
+ queryFn: () => {
+ if (!source.stats) throw new SessionExplorerError('Insights need the local store', 'unsupported');
+ return source.stats(range);
+ },
+ enabled: !!source.stats,
+ staleTime: 60 * 1000,
+ placeholderData: keepPreviousData,
+ retry: false,
+ });
+}
diff --git a/viewer/src/data/httpSource.ts b/viewer/src/data/httpSource.ts
index cd057a7..df59f58 100644
--- a/viewer/src/data/httpSource.ts
+++ b/viewer/src/data/httpSource.ts
@@ -6,6 +6,7 @@ import {
sessionExplorerStatusSchema,
type SessionMap,
} from '@/core/schema';
+import { insightsStatsSchema } from '@/core/insights';
import { SessionExplorerError } from './errors';
import { parseMapBytes } from './parse';
import { SESSION_MAP_BATCH_MAX, type SessionMapSource } from './source';
@@ -97,6 +98,14 @@ export function httpSource(baseUrl: string): SessionMapSource {
if (!r.ok) throw await failure(r, 'promptImages');
return promptImagesResponseSchema.parse(await json(r, 'promptImages'));
},
+ async stats(range) {
+ const qs = new URLSearchParams();
+ if (range.from) qs.set('from', range.from);
+ if (range.to) qs.set('to', range.to);
+ const r = await get(`/api/stats?${qs.toString()}`);
+ if (!r.ok) throw await failure(r, 'stats');
+ return insightsStatsSchema.parse(await json(r, 'stats'));
+ },
async hookDetail(sessionId, uuid) {
const qs = new URLSearchParams({ id: sessionId, uuid });
const r = await get(`/api/hook-detail?${qs.toString()}`);
diff --git a/viewer/src/data/source.ts b/viewer/src/data/source.ts
index d63e892..1f0a749 100644
--- a/viewer/src/data/source.ts
+++ b/viewer/src/data/source.ts
@@ -7,6 +7,7 @@ import type {
SessionExplorerStatus,
SessionMap,
} from '@/core/schema';
+import type { InsightsStats } from '@/core/insights';
export interface SessionsParams {
/** inclusive UTC `YYYY-MM-DD` */
@@ -50,6 +51,12 @@ export interface SessionMapSource {
* to the recording machine can answer, and it rejects otherwise.
*/
hookDetail?(sessionId: string, uuid: string): Promise<HookDetailResponse>;
+ /**
+ * Optional. Per-session facts for the Insights view, for root sessions in
+ * the range (inclusive UTC `YYYY-MM-DD`; omitted = all time). Absent on a
+ * source with no precomputed facts (opened files).
+ */
+ stats?(range: { from?: string; to?: string }): Promise<InsightsStats>;
}
/** Max ids per `maps()` call. */
diff --git a/viewer/src/insights/InfoButton.tsx b/viewer/src/insights/InfoButton.tsx
new file mode 100644
index 0000000..d008ec0
--- /dev/null
+++ b/viewer/src/insights/InfoButton.tsx
@@ -0,0 +1,59 @@
+import { Info, X } from '@phosphor-icons/react';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+import { GLOSSARY, type TermKey } from './glossary';
+
+/** A small (i) next to a term that opens its plain-language definition. */
+export function InfoButton({ term, className }: { term: TermKey; className?: string }) {
+ const t = GLOSSARY[term];
+ return (
+ <Dialog>
+ <DialogTrigger
+ aria-label={`What is ${t.title.toLowerCase()}?`}
+ className={cn(
+ 'inline-flex size-6 shrink-0 items-center justify-center rounded-full text-ds-text-subtle hover:bg-ds-gray-subtlest hover:text-ds-text-darker focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ds-brand-subtler',
+ className
+ )}
+ >
+ <Info size={15} aria-hidden />
+ </DialogTrigger>
+ <DialogContent className="w-[min(34rem,calc(100vw-2rem))] gap-3 p-5">
+ <div className="flex items-start gap-3">
+ <DialogTitle className="flex-1 ds-text-title-sm-semibold text-ds-text-darker">{t.title}</DialogTitle>
+ <DialogClose
+ aria-label="Close"
+ className="inline-flex size-8 items-center justify-center rounded-md border border-ds-border-subtlest text-ds-text-subtle hover:bg-ds-gray-subtlest"
+ >
+ <X size={14} aria-hidden />
+ </DialogClose>
+ </div>
+ {t.paras.map((p) => (
+ <p key={p} className="ds-text-body-sm-medium text-ds-text-default">
+ {p}
+ </p>
+ ))}
+ {'rows' in t && t.rows ? (
+ <dl className="grid grid-cols-[max-content_1fr] gap-x-4 border-t border-ds-border-subtlest">
+ {t.rows.map(([k, v]) => (
+ <div key={k} className="contents">
+ <dt className="border-b border-ds-border-subtlest py-2 ds-text-body-xs-semibold text-ds-text-darker">{k}</dt>
+ <dd className="border-b border-ds-border-subtlest py-2 ds-text-body-xs-medium text-ds-text-default">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
+ {'formula' in t && t.formula ? (
+ <p className="rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest px-3 py-2 font-mono text-xs text-ds-text-default">
+ {t.formula}
+ </p>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/viewer/src/insights/InsightsView.tsx b/viewer/src/insights/InsightsView.tsx
new file mode 100644
index 0000000..c413f2f
--- /dev/null
+++ b/viewer/src/insights/InsightsView.tsx
@@ -0,0 +1,209 @@
+import { useMemo, useState } from 'react';
+import { CalendarBlankIcon } from '@phosphor-icons/react';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useInsightsStats } from '@/data/hooks';
+import { useSessionMapSource } from '@/data/SourceContext';
+import { sessionWindowRange } from '@/core/sessionWindow';
+import { WINDOW_OPTIONS, type WindowKey } from '@/core/windowOptions';
+import { filterOptions, filterSessions, type InsightsFilter } from '@/core/insights';
+import {
+ CompactionPanel,
+ FailingCommands,
+ KpiTiles,
+ OutcomeMix,
+ SpendPanel,
+ WastePanel,
+ WhatFails,
+} from './panels';
+import { SearchHeatmap } from './SearchHeatmap';
+
+const ALL = '__all__';
+
+function FilterSelect({
+ label,
+ value,
+ options,
+ allLabel,
+ onChange,
+ format = (v) => v,
+}: {
+ label: string;
+ value: string | null;
+ options: string[];
+ allLabel: string;
+ onChange: (v: string | null) => void;
+ format?: (v: string) => string;
+}) {
+ const items = [{ value: ALL, label: allLabel }, ...options.map((o) => ({ value: o, label: format(o) }))];
+ return (
+ <label className="flex min-w-40 flex-col gap-1 ds-text-body-xs-semibold uppercase tracking-wide text-ds-text-subtle">
+ {label}
+ <Select
+ value={value ?? ALL}
+ items={items}
+ onValueChange={(v: string | null) => onChange(!v || v === ALL ? null : v)}
+ >
+ <SelectTrigger aria-label={label} className="h-8 normal-case tracking-normal">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="start">
+ {items.map((i) => (
+ <SelectItem key={i.value} value={i.value}>
+ {i.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ );
+}
+
+const AGENT_LABEL: Record<string, string> = {
+ 'claude-code': 'Claude Code',
+ codex: 'Codex',
+ cursor: 'Cursor',
+ kiro: 'Kiro',
+ opencode: 'OpenCode',
+ copilot: 'Copilot',
+};
+
+/**
+ * Insights: patterns across every stored session. Shares the time window
+ * with the session list; agent, repo and model filters are local to the page.
+ */
+export function InsightsView({
+ windowKey,
+ onWindowChange,
+}: {
+ windowKey: WindowKey;
+ onWindowChange: (key: WindowKey) => void;
+}) {
+ const source = useSessionMapSource();
+ // Recomputed per window change only: a range off "now" that moved every
+ // render would refetch forever.
+ const range = useMemo(() => sessionWindowRange(windowKey, new Date()), [windowKey]);
+ const stats = useInsightsStats(range);
+ const [filter, setFilter] = useState<InsightsFilter>({});
+ const all = stats.data?.sessions ?? [];
+ const options = useMemo(() => filterOptions(all), [all]);
+ const rows = useMemo(() => filterSessions(all, filter), [all, filter]);
+
+ if (!source.stats) {
+ return (
+ <Notice>
+ Insights read the facts the CLI stores for each session, so they are not available for opened map files. Go back
+ to your local sessions, or run <code className="font-mono">agentplay</code> to see them.
+ </Notice>
+ );
+ }
+
+ return (
+ <main className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto pb-6">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h1 className="ds-text-title-md-semibold text-ds-text-darker">Insights</h1>
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">
+ Patterns across your sessions. Root sessions only; computed on this machine.
+ </p>
+ </div>
+ <div className="flex flex-wrap items-end gap-2" role="group" aria-label="Filters">
+ <label className="flex min-w-36 flex-col gap-1 ds-text-body-xs-semibold uppercase tracking-wide text-ds-text-subtle">
+ Window
+ <Select
+ value={windowKey}
+ items={WINDOW_OPTIONS.map((o) => ({ value: o.key, label: o.label }))}
+ onValueChange={(v: string | null) => {
+ if (v) onWindowChange(v as WindowKey);
+ }}
+ >
+ <SelectTrigger aria-label="Time window" className="h-8 gap-2 normal-case tracking-normal">
+ <CalendarBlankIcon size={14} weight="duotone" className="shrink-0 text-ds-text-subtle" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="start">
+ {WINDOW_OPTIONS.map((o) => (
+ <SelectItem key={o.key} value={o.key}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <FilterSelect
+ label="Agent"
+ value={filter.agent ?? null}
+ options={options.agents}
+ allLabel="All agents"
+ format={(a) => AGENT_LABEL[a] ?? a}
+ onChange={(agent) => setFilter((f) => ({ ...f, agent }))}
+ />
+ <FilterSelect
+ label="Repo"
+ value={filter.repo ?? null}
+ options={options.repos}
+ allLabel="All repos"
+ onChange={(repo) => setFilter((f) => ({ ...f, repo }))}
+ />
+ <FilterSelect
+ label="Model"
+ value={filter.model ?? null}
+ options={options.models}
+ allLabel="All models"
+ onChange={(model) => setFilter((f) => ({ ...f, model }))}
+ />
+ </div>
+ </div>
+
+ {stats.isPending ? (
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-3">
+ {[0, 1, 2, 3].map((i) => (
+ <Skeleton key={i} className="h-28 rounded-xl" />
+ ))}
+ <Skeleton className="col-span-full h-72 rounded-xl" />
+ </div>
+ ) : stats.isError ? (
+ <Notice>
+ Insights could not be loaded. If the CLI is older than this viewer, update it with{' '}
+ <code className="font-mono">uvx agentplay@latest</code>.
+ </Notice>
+ ) : !rows.length ? (
+ <Notice>No sessions match this window and these filters.</Notice>
+ ) : (
+ <>
+ <KpiTiles rows={rows} />
+ <div className="flex flex-wrap gap-3">
+ <OutcomeMix rows={rows} />
+ <WastePanel rows={rows} />
+ </div>
+ <div className="flex flex-wrap gap-3">
+ <SpendPanel rows={rows} />
+ <CompactionPanel rows={rows} />
+ </div>
+ <div className="flex flex-wrap gap-3">
+ <FailingCommands rows={rows} />
+ <WhatFails rows={rows} />
+ </div>
+ <SearchHeatmap rows={rows} />
+ </>
+ )}
+ </main>
+ );
+}
+
+function Notice({ children }: { children: React.ReactNode }) {
+ return (
+ <div
+ role="note"
+ className="rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-6 text-center ds-text-body-sm-medium text-ds-text-default"
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/viewer/src/insights/SearchHeatmap.tsx b/viewer/src/insights/SearchHeatmap.tsx
new file mode 100644
index 0000000..e7a09ac
--- /dev/null
+++ b/viewer/src/insights/SearchHeatmap.tsx
@@ -0,0 +1,205 @@
+import { useMemo, useState } from 'react';
+import { MagnifyingGlass } from '@phosphor-icons/react';
+import { Input } from '@/components/ui/input';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { SEQUENTIAL } from '@/components/dataviz';
+import { cn } from '@/lib/utils';
+import { fileHeat, type FileHeat, type InsightsSession } from '@/core/insights';
+import { squarify } from '@/core/treemap';
+import { Panel } from './panels';
+
+/** Files drawn as tiles; the rest are counted in the footnote. Small tiles
+ * would be unreadable slivers, and a 1,000-file store would make the layout
+ * itself the slow part. */
+const MAX_TILES = 150;
+/** Folder header height inside its block, in % of the map's height. */
+const HEAD = 4.5;
+/** The map's aspect: width units per height unit, so squarify sees real shapes. */
+const ASPECT = 2.6;
+
+type Metric = 'sessions' | 'ratio';
+
+const metricValue = (f: FileHeat, m: Metric) => (m === 'sessions' ? f.sessions : f.hits / (f.edits + 1));
+
+export function SearchHeatmap({ rows }: { rows: InsightsSession[] }) {
+ const [metric, setMetric] = useState<Metric>('sessions');
+ const [query, setQuery] = useState('');
+ const [selected, setSelected] = useState<string | null>(null);
+ const all = useMemo(() => fileHeat(rows).filter((f) => f.hits > 0), [rows]);
+ const shown = useMemo(() => all.slice(0, MAX_TILES), [all]);
+
+ const layout = useMemo(() => {
+ const folders = new Map<string, FileHeat[]>();
+ for (const f of shown) {
+ const k = `${f.repo}:${f.dir}`;
+ folders.set(k, [...(folders.get(k) ?? []), f]);
+ }
+ const groups = [...folders.entries()].map(([key, files]) => ({
+ key,
+ files,
+ hits: files.reduce((s, f) => s + f.hits, 0),
+ }));
+ // Lay out in (ASPECT x 100) units so tiles come out square on screen,
+ // then convert x and w to percentages of the width.
+ const W = 100 * ASPECT;
+ const blocks = squarify(groups, (g) => g.hits, { x: 0, y: 0, w: W, h: 100 });
+ return blocks.map((b) => {
+ const head = b.h > 12 && b.w > 30 ? HEAD : 0;
+ const pad = 0.6;
+ const tiles = squarify(b.item.files, (f) => f.hits, {
+ x: b.x + pad,
+ y: b.y + head + pad,
+ w: Math.max(0, b.w - 2 * pad),
+ h: Math.max(0, b.h - head - 2 * pad),
+ });
+ const toPct = (r: { x: number; y: number; w: number; h: number }) => ({
+ left: `${(r.x / W) * 100}%`,
+ top: `${r.y}%`,
+ width: `${(r.w / W) * 100}%`,
+ height: `${r.h}%`,
+ });
+ return { key: b.item.key, head, box: toPct(b), raw: b, tiles: tiles.map((t) => ({ f: t.item, box: toPct(t), raw: t })) };
+ });
+ }, [shown]);
+
+ const values = shown.map((f) => metricValue(f, metric));
+ const lo = Math.min(...values, 0);
+ const hi = Math.max(...values, 1);
+ // Four steps of the brand ramp: dark enough to read text on in both themes.
+ const ramp = SEQUENTIAL.slice(0, 4);
+ const level = (f: FileHeat) =>
+ Math.min(ramp.length - 1, Math.floor((ramp.length * (metricValue(f, metric) - lo)) / ((hi - lo) || 1)));
+ const q = query.trim().toLowerCase();
+ const sel = selected ? shown.find((f) => f.key === selected) : undefined;
+
+ return (
+ <Panel
+ title="Search heatmap"
+ term="searchHeatmap"
+ question={`Where do agents spend effort finding code? ${all.length} ${all.length === 1 ? 'file' : 'files'} came up in searches.`}
+ >
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="relative w-full max-w-xs">
+ <MagnifyingGlass size={14} aria-hidden className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-ds-text-subtle" />
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Highlight a path or name"
+ aria-label="Highlight files"
+ className="h-8 pl-8 font-mono text-xs"
+ />
+ </div>
+ <div className="flex items-center gap-2 ds-text-body-xs-medium text-ds-text-subtle">
+ Colour
+ <ToggleGroup
+ value={[metric]}
+ onValueChange={(v: unknown[]) => {
+ const next = v.find((x): x is Metric => x === 'sessions' || x === 'ratio');
+ if (next) setMetric(next);
+ }}
+ aria-label="Colour tiles by"
+ >
+ <ToggleGroupItem value="sessions">Sessions</ToggleGroupItem>
+ <ToggleGroupItem value="ratio">Searched vs edited</ToggleGroupItem>
+ </ToggleGroup>
+ </div>
+ </div>
+
+ {shown.length ? (
+ <div className="relative h-[420px] overflow-hidden rounded-lg bg-ds-gray-subtlest" role="group" aria-label="Searched files by folder">
+ {layout.map((g) => (
+ <div
+ key={g.key}
+ className="absolute overflow-hidden rounded-md border border-ds-border-subtler"
+ style={g.box}
+ >
+ {g.head ? (
+ <span className="block truncate px-1.5 pt-0.5 font-mono text-[10.5px] font-semibold text-ds-text-default">
+ {g.key}
+ </span>
+ ) : null}
+ </div>
+ ))}
+ {layout.flatMap((g) =>
+ g.tiles.map(({ f, box, raw }) => {
+ const match = !q || f.key.toLowerCase().includes(q);
+ // Room for a name and a count: about 70 x 34 px on a 1,300 px wide map.
+ const label = raw.w > 14 && raw.h > 8;
+ const tip = `${f.key}: ${f.sessions} sessions, ${f.hits} search hits, ${f.reads} reads, ${f.edits} edits`;
+ return (
+ <button
+ key={f.key}
+ type="button"
+ title={tip}
+ aria-label={tip}
+ aria-pressed={selected === f.key}
+ onClick={() => setSelected(selected === f.key ? null : f.key)}
+ className={cn(
+ 'absolute overflow-hidden rounded-sm border border-ds-surface-white px-1.5 py-1 text-left text-ds-text-darker transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ds-brand-subtle',
+ selected === f.key && 'ring-2 ring-ds-text-darker'
+ )}
+ style={{ ...box, background: ramp[level(f)], opacity: match ? 1 : 0.2 }}
+ >
+ {label ? (
+ <>
+ <span className="block truncate font-mono text-[11px] font-semibold">{f.name}</span>
+ <span className="block truncate text-[10.5px] opacity-80">
+ {metric === 'sessions'
+ ? `${f.sessions} ${f.sessions === 1 ? 'session' : 'sessions'}`
+ : f.edits
+ ? `${(f.hits / f.edits).toFixed(1)} hits per edit`
+ : 'never edited'}
+ </span>
+ </>
+ ) : null}
+ </button>
+ );
+ })
+ )}
+ </div>
+ ) : (
+ <p className="py-6 text-center ds-text-body-xs-medium text-ds-text-subtle">No file searches in this window.</p>
+ )}
+
+ <div className="flex flex-wrap items-center justify-between gap-2 ds-text-body-xs-medium text-ds-text-subtle">
+ <span className="flex items-center gap-2">
+ {metric === 'sessions' ? 'Fewer sessions' : 'Often edited'}
+ <span className="flex gap-0.5" aria-hidden>
+ {ramp.map((c) => (
+ <span key={c} className="h-3 w-5 rounded-sm" style={{ background: c }} />
+ ))}
+ </span>
+ {metric === 'sessions' ? 'More sessions' : 'Searched, rarely edited'}
+ </span>
+ <span>
+ {all.length > shown.length
+ ? `Top ${shown.length} files by search hits shown; ${all.length - shown.length} smaller ones hidden.`
+ : 'Size is search hits.'}
+ </span>
+ </div>
+
+ {sel ? (
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-1 rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest px-3 py-2 ds-text-body-xs-medium">
+ <span className="min-w-0 flex-1 break-all font-mono">
+ <span className="text-ds-text-subtle">
+ {sel.repo}:{sel.dir}
+ </span>
+ <strong className="text-ds-text-darker">{sel.name}</strong>
+ </span>
+ {(
+ [
+ ['sessions', sel.sessions],
+ ['search hits', sel.hits],
+ ['reads', sel.reads],
+ ['edits', sel.edits],
+ ] as const
+ ).map(([k, v]) => (
+ <span key={k}>
+ <strong className="text-ds-text-darker">{v}</strong> <span className="text-ds-text-subtle">{k}</span>
+ </span>
+ ))}
+ </div>
+ ) : null}
+ </Panel>
+ );
+}
diff --git a/viewer/src/insights/glossary.ts b/viewer/src/insights/glossary.ts
new file mode 100644
index 0000000..4b63293
--- /dev/null
+++ b/viewer/src/insights/glossary.ts
@@ -0,0 +1,127 @@
+/**
+ * Plain-language definitions behind every Insights info button. One list, so
+ * a term reads the same wherever it appears.
+ */
+import { OUTCOME_META, type SessionOutcome } from '@/core/sessionMapModel';
+import { MIN_SAMPLE } from '@/core/insights';
+
+export interface Term {
+ title: string;
+ paras: string[];
+ rows?: [string, string][];
+ formula?: string;
+}
+
+const OUTCOME_HELP: Record<SessionOutcome, string> = {
+ pr_created: 'The agent opened a pull request. Wins over everything else, even errors afterwards.',
+ verified: 'Tests, a build or a linter passed, and nothing was edited after that.',
+ completed: 'No errors at the end and the agent gave a final reply, but no PR and no passing check.',
+ interrupted: 'You stopped the agent near the end. Often the right call, so it is not treated as a failure.',
+ blocked: 'A command or tool was refused near the end: blocked by a hook or setting, or permission denied.',
+ unresolved_errors: 'Two or more of the last 12 actions failed and the session ended there.',
+ incomplete: 'Stopped mid-work: the last step was an edit or command and the agent never replied.',
+};
+
+export const GLOSSARY = {
+ sessions: {
+ title: 'Sessions',
+ paras: [
+ 'A session is one conversation with a coding agent, from your first prompt to the end.',
+ 'Only root sessions are counted: the ones you started. Subagents and helper runs an agent launches belong to their parent session.',
+ ],
+ },
+ spend: {
+ title: 'Spend',
+ paras: [
+ 'What the model requests in these sessions would cost at list API prices, worked out from their token counts.',
+ 'It is an estimate, not your bill. Cursor records no tokens or cost, so its sessions are left out of every spend figure.',
+ ],
+ },
+ costPerPr: {
+ title: 'Cost per PR',
+ paras: [
+ 'Total spend divided by the number of PRs opened.',
+ 'Spend on sessions that opened no PR is charged to the ones that did, so this falls when fewer sessions are wasted, not only when sessions get cheaper.',
+ ],
+ formula: 'spend ÷ PRs opened',
+ },
+ prRate: {
+ title: 'PR rate',
+ paras: [
+ 'The share of sessions that edited code and opened a pull request. Sessions that only answered a question or explored are left out, so they neither raise nor lower it.',
+ 'Merged is how many of those PRs agentplay later saw merged in an agent session. Merges done outside an agent are not visible yet.',
+ `Rates over fewer than ${MIN_SAMPLE} sessions are shown greyed.`,
+ ],
+ formula: 'sessions that opened a PR ÷ sessions with at least one edit',
+ },
+ outcomes: {
+ title: 'How sessions end',
+ paras: [
+ 'Every session gets exactly one outcome, read from how it ended: its last actions, any PR, and whether checks passed. agentplay never reads what was said. The first match in this order wins.',
+ ],
+ rows: (Object.keys(OUTCOME_HELP) as SessionOutcome[]).map((o) => [OUTCOME_META[o].label, OUTCOME_HELP[o]]),
+ formula: 'Number above each bar: that week’s PR rate (sessions that opened a PR ÷ sessions that edited code).',
+ },
+ failingCommands: {
+ title: 'Failing commands',
+ paras: [
+ 'Fail rate is failed runs of a command divided by all its runs. Retries are runs that repeat one that just failed. Only the command name is stored (pnpm test), never its arguments.',
+ 'Each bar is split by why the command failed:',
+ ],
+ rows: [
+ ['exit_code', 'It ran and exited with an error, e.g. failing tests or a compile error.'],
+ ['timeout', 'It ran too long and was stopped.'],
+ ['permission_denied', 'The agent was not allowed to run it.'],
+ ['not_found', 'The command, or a file it needed, does not exist.'],
+ ],
+ },
+ whatFails: {
+ title: 'What fails',
+ paras: ['Every failed action, grouped by where it failed. The names under each group are error classes.'],
+ rows: [
+ ['Tool', 'Shell commands and file tools: running tests, reading or editing files.'],
+ ['MCP', 'Calls to MCP servers, the external tools an agent can use, like Linear or GitHub.'],
+ ['LLM', 'The model request itself: rate limits, overloaded servers, or a prompt too long for the context.'],
+ ['Hook', 'Your own hook scripts that run before or after tool calls.'],
+ ['Orchestration', 'Subagents that failed or were killed.'],
+ ],
+ },
+ searchHeatmap: {
+ title: 'Search heatmap',
+ paras: [
+ 'Where agents spend effort finding code. Each tile is a file, grouped by folder. Size is how often it came up in search results; colour is how many sessions touched it, or how often it is searched compared with edited.',
+ 'A few heavily searched files are normal. The useful signal is a folder agents search through in many sessions before reading anything.',
+ ],
+ rows: [
+ ['Search hits', 'Times the file came up in a search result (grep, find, glob).'],
+ ['Reads', 'Times it was opened.'],
+ ['Edits', 'Times it was changed.'],
+ ],
+ },
+ waste: {
+ title: 'Waste',
+ paras: ['Spend on work that did not lead to a PR or a passing check, split into five buckets. Each dollar is counted once, in this order:'],
+ rows: [
+ ['Retry loops', 'Failed tool or MCP calls and their retries.'],
+ ['Abandoned spend', 'The rest of the cost of sessions that ended with unresolved errors or stopped mid-work.'],
+ ['Cache misses', 'Paying full price for input that could have come from the prompt cache at about a tenth of the cost.'],
+ ['Re-reads', 'Reading a file again when nothing had changed it.'],
+ ['Dead subagents', 'Subagents that ended with no result, failed or were killed.'],
+ ['Stalls', 'Long pauses with no progress. Time lost, not money, so shown separately.'],
+ ],
+ formula: 'Cost is only known per model request, so a failed command is charged the request that read its result. Every bucket is an estimate.',
+ },
+ compaction: {
+ title: 'Compaction',
+ paras: [
+ 'When a conversation gets close to the model’s context limit, the agent summarises earlier turns and drops the detail to make room. That is a compaction.',
+ 'Detail is lost, so agents often re-read files afterwards, and sessions that compact can open PRs less often.',
+ ],
+ rows: [
+ ['Tokens at compaction', 'How full the context was when it happened.'],
+ ['Re-reads after compaction', 'Files read again after a compaction with no change to them in between.'],
+ ],
+ },
+} satisfies Record<string, Term>;
+
+export type TermKey = keyof typeof GLOSSARY;
diff --git a/viewer/src/insights/panels.tsx b/viewer/src/insights/panels.tsx
new file mode 100644
index 0000000..7d35e2f
--- /dev/null
+++ b/viewer/src/insights/panels.tsx
@@ -0,0 +1,516 @@
+import { useState, type ReactNode } from 'react';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { Badge } from '@/components/ui/badge';
+import { SERIES_OTHER, seriesColor } from '@/components/dataviz';
+import { cn } from '@/lib/utils';
+import { fmtDur, fmtUsd, OUTCOME_META, type SessionOutcome } from '@/core/sessionMapModel';
+import {
+ compactionSummary,
+ dayRange,
+ failuresBySource,
+ headline,
+ MIN_SAMPLE,
+ OUTCOME_ORDER,
+ outcomesByWeek,
+ spendByDay,
+ topFailingCommands,
+ WASTE_BUCKETS,
+ wasteSummary,
+ weekStart,
+ type InsightsSession,
+ type PrRate,
+ type WasteBucket,
+} from '@/core/insights';
+import { InfoButton } from './InfoButton';
+import type { TermKey } from './glossary';
+
+// ------------------------------------------------------------------ shared
+
+export function Panel({
+ title,
+ term,
+ question,
+ action,
+ className,
+ children,
+}: {
+ title: string;
+ term?: TermKey;
+ question?: string;
+ action?: ReactNode;
+ className?: string;
+ children: ReactNode;
+}) {
+ const id = `insights-${title.toLowerCase().replace(/[^a-z]+/g, '-')}`;
+ return (
+ <section
+ aria-labelledby={id}
+ className={cn(
+ 'flex min-w-0 flex-col gap-3 rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-4',
+ className
+ )}
+ >
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0">
+ <h2 id={id} className="flex items-center gap-1 ds-text-body-sm-semibold text-ds-text-darker">
+ {title}
+ {term ? <InfoButton term={term} /> : null}
+ </h2>
+ {question ? <p className="ds-text-body-xs-medium text-ds-text-subtle">{question}</p> : null}
+ </div>
+ {action}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+export const pct = (x: number | null): string => (x == null ? '–' : `${Math.round(x * 100)}%`);
+
+/** A rate with its sample size; greyed below `MIN_SAMPLE`. */
+function Rate({ r, className }: { r: PrRate; className?: string }) {
+ const thin = r.edited < MIN_SAMPLE;
+ return (
+ <span
+ // The grey wins over the caller's ink: a thin rate must never read as a firm one.
+ className={cn(className, thin && 'text-ds-text-subtle')}
+ title={thin ? `Only ${r.edited} sessions edited code: too few for a reliable rate` : undefined}
+ >
+ {pct(r.rate)}
+ </span>
+ );
+}
+
+function Swatch({ color }: { color: string }) {
+ return <span aria-hidden className="inline-block size-2.5 shrink-0 rounded-sm" style={{ background: color }} />;
+}
+
+function Legend({ items }: { items: { label: string; color: string }[] }) {
+ return (
+ <ul className="flex flex-wrap gap-x-3 gap-y-1 ds-text-body-xs-medium text-ds-text-default">
+ {items.map((i) => (
+ <li key={i.label} className="flex items-center gap-1.5">
+ <Swatch color={i.color} />
+ {i.label}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+const shortDate = (iso: string) =>
+ new Date(`${iso}T00:00:00Z`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' });
+
+// ------------------------------------------------------------------ tiles
+
+function Tile({ label, term, value, foot }: { label: string; term: TermKey; value: ReactNode; foot: ReactNode }) {
+ return (
+ <div className="flex min-w-0 flex-col gap-1 rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-4">
+ <div className="flex items-center justify-between gap-2 ds-text-body-xs-medium text-ds-text-subtle">
+ {label}
+ <InfoButton term={term} />
+ </div>
+ <div className="text-2xl font-semibold tracking-tight text-ds-text-darker">{value}</div>
+ <div className="ds-text-body-xs-medium text-ds-text-subtle">{foot}</div>
+ </div>
+ );
+}
+
+export function KpiTiles({ rows }: { rows: InsightsSession[] }) {
+ const h = headline(rows);
+ return (
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-3">
+ <Tile label="Sessions" term="sessions" value={h.sessions} foot="root sessions in the window" />
+ <Tile
+ label="Spend"
+ term="spend"
+ value={fmtUsd(h.spend)}
+ foot={h.noCost ? `${h.noCost} Cursor ${h.noCost === 1 ? 'session' : 'sessions'} without cost data left out` : 'at list API prices'}
+ />
+ <Tile
+ label="Cost per PR"
+ term="costPerPr"
+ value={h.costPerPr == null ? '–' : fmtUsd(h.costPerPr)}
+ foot={`spend ÷ ${h.prsOpened} ${h.prsOpened === 1 ? 'PR' : 'PRs'} opened`}
+ />
+ <Tile
+ label="PR rate"
+ term="prRate"
+ value={<Rate r={h.pr} />}
+ foot={`${h.pr.opened} of ${h.pr.edited} code-changing sessions · ${h.prsMerged} merged`}
+ />
+ </div>
+ );
+}
+
+// ------------------------------------------------------------------ outcomes
+
+export const OUTCOME_COLOR: Record<SessionOutcome, string> = {
+ pr_created: 'var(--ds-series-1)',
+ verified: 'var(--ds-series-6)',
+ completed: 'var(--ds-series-other)',
+ interrupted: 'var(--ds-series-4)',
+ blocked: 'var(--ds-series-5)',
+ unresolved_errors: 'var(--ds-danger-default)',
+ incomplete: 'var(--primitive-gray-300)',
+};
+
+const MAX_WEEKS = 16;
+
+export function OutcomeMix({ rows }: { rows: InsightsSession[] }) {
+ const weeks = outcomesByWeek(rows).slice(-MAX_WEEKS);
+ const max = Math.max(1, ...weeks.map((w) => w.total));
+ return (
+ <Panel
+ title="Outcome mix"
+ term="outcomes"
+ question="Weekly session outcomes, and the trend in PR rate"
+ className="flex-[7_1_520px]"
+ >
+ {weeks.length ? (
+ <>
+ <div className="flex h-48 items-end gap-2 border-b border-ds-border-subtlest pt-5">
+ {weeks.map((w) => (
+ <div key={w.week} className="flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-1">
+ <Rate r={w.pr} className="ds-text-body-xs-semibold text-ds-text-darker" />
+ <div
+ role="img"
+ aria-label={`Week of ${shortDate(w.week)}: ${w.total} sessions, PR rate ${pct(w.pr.rate)}`}
+ className="flex w-full max-w-10 flex-col-reverse overflow-hidden rounded-t"
+ style={{ height: `${(w.total / max) * 100}%` }}
+ >
+ {OUTCOME_ORDER.map((o) =>
+ w.counts[o] ? (
+ <div key={o} style={{ height: `${(w.counts[o] / w.total) * 100}%`, background: OUTCOME_COLOR[o] }} />
+ ) : null
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ <div className="-mt-2 flex gap-2">
+ {weeks.map((w) => (
+ <span key={w.week} className="min-w-0 flex-1 truncate text-center ds-text-body-xs-medium text-ds-text-subtle">
+ {shortDate(w.week)}
+ </span>
+ ))}
+ </div>
+ <Legend items={OUTCOME_ORDER.map((o) => ({ label: OUTCOME_META[o].label, color: OUTCOME_COLOR[o] }))} />
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">
+ Number above each bar: that week&rsquo;s PR rate. Grey means too few sessions to read much into it.
+ </p>
+ </>
+ ) : (
+ <Empty>No sessions in this window.</Empty>
+ )}
+ </Panel>
+ );
+}
+
+function Empty({ children }: { children: ReactNode }) {
+ return <p className="py-6 text-center ds-text-body-xs-medium text-ds-text-subtle">{children}</p>;
+}
+
+// ------------------------------------------------------------------ spend
+
+export function SpendPanel({ rows }: { rows: InsightsSession[] }) {
+ const [by, setBy] = useState<'agent' | 'model'>('agent');
+ const { days, series } = spendByDay(rows, by);
+ const h = headline(rows);
+ const colorOf = (key: string) => {
+ const i = series.findIndex((s) => s.key === key);
+ return key === 'Other' ? SERIES_OTHER : seriesColor(i);
+ };
+ // Daily bars up to three months; weekly beyond that so bars stay readable.
+ const range = days.length ? dayRange(days[0].day, days[days.length - 1].day) : [];
+ const weekly = range.length > 92;
+ const buckets = new Map<string, Record<string, number>>();
+ for (const d of range) buckets.set(weekly ? weekStart(d) : d, buckets.get(weekly ? weekStart(d) : d) ?? {});
+ for (const d of days) {
+ const b = buckets.get(weekly ? weekStart(d.day) : d.day)!;
+ for (const [k, v] of Object.entries(d.parts)) b[k] = (b[k] ?? 0) + v;
+ }
+ const bars = [...buckets.entries()].map(([key, parts]) => ({
+ key,
+ parts,
+ total: Object.values(parts).reduce((s, v) => s + v, 0),
+ }));
+ const max = Math.max(0.01, ...bars.map((b) => b.total));
+ return (
+ <Panel
+ title="Spend"
+ term="spend"
+ question={`Where does the money go? ${fmtUsd(h.spend)} in this window${weekly ? ', by week' : ', by day'}.`}
+ className="flex-[7_1_520px]"
+ action={
+ <ToggleGroup
+ value={[by]}
+ onValueChange={(v: unknown[]) => {
+ const next = v.find((x): x is 'agent' | 'model' => x === 'agent' || x === 'model');
+ if (next) setBy(next);
+ }}
+ aria-label="Split spend by"
+ >
+ <ToggleGroupItem value="agent">By agent</ToggleGroupItem>
+ <ToggleGroupItem value="model">By model</ToggleGroupItem>
+ </ToggleGroup>
+ }
+ >
+ {bars.length ? (
+ <>
+ <div className="flex gap-2">
+ <div className="flex h-40 w-12 flex-col justify-between text-right font-mono text-[11px] text-ds-text-subtle">
+ <span>{fmtUsd(max)}</span>
+ <span>$0</span>
+ </div>
+ <div className="flex h-40 min-w-0 flex-1 items-end gap-px border-b border-ds-border-subtlest">
+ {bars.map((b) => (
+ <div
+ key={b.key}
+ role="img"
+ aria-label={`${shortDate(b.key)}: ${fmtUsd(b.total)}`}
+ title={`${shortDate(b.key)} · ${fmtUsd(b.total)}`}
+ className="flex min-w-0 flex-1 flex-col-reverse overflow-hidden rounded-t-sm"
+ style={{ height: `${(b.total / max) * 100}%` }}
+ >
+ {series.map((s) =>
+ b.parts[s.key] ? (
+ <div key={s.key} style={{ height: `${(b.parts[s.key] / b.total) * 100}%`, background: colorOf(s.key) }} />
+ ) : null
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="flex justify-between pl-14 ds-text-body-xs-medium text-ds-text-subtle">
+ <span>{shortDate(bars[0].key)}</span>
+ <span>{shortDate(bars[bars.length - 1].key)}</span>
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Legend items={series.map((s) => ({ label: `${s.key} · ${fmtUsd(s.total)}`, color: colorOf(s.key) }))} />
+ {h.noCost ? (
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">
+ {h.noCost} Cursor {h.noCost === 1 ? 'session has' : 'sessions have'} no cost data and {h.noCost === 1 ? 'is' : 'are'} left out.
+ </span>
+ ) : null}
+ </div>
+ </>
+ ) : (
+ <Empty>No sessions with cost data in this window.</Empty>
+ )}
+ </Panel>
+ );
+}
+
+// ------------------------------------------------------------------ failures
+
+const ERR_CLASS_ORDER = ['exit_code', 'timeout', 'permission_denied', 'not_found', 'blocked'];
+const classColor = (cls: string) => {
+ const i = ERR_CLASS_ORDER.indexOf(cls);
+ return i < 0 ? SERIES_OTHER : seriesColor(i);
+};
+
+export function FailingCommands({ rows }: { rows: InsightsSession[] }) {
+ const cmds = topFailingCommands(rows);
+ const max = Math.max(1, ...cmds.map((c) => c.fails));
+ const classes = [...new Set(cmds.flatMap((c) => Object.keys(c.byClass)))].sort(
+ (a, b) => (ERR_CLASS_ORDER.indexOf(a) + 99) % 99 - ((ERR_CLASS_ORDER.indexOf(b) + 99) % 99)
+ );
+ return (
+ <Panel
+ title="Top failing commands"
+ term="failingCommands"
+ question="Which commands fail most? Command names only; arguments are never stored."
+ className="flex-[7_1_520px]"
+ >
+ {cmds.length ? (
+ <>
+ <ul className="flex flex-col gap-2">
+ {cmds.map((c) => (
+ <li key={c.verb} className="flex items-center gap-3">
+ <span className="w-36 shrink-0 truncate font-mono text-xs text-ds-text-darker" title={c.verb}>
+ {c.verb}
+ </span>
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <span
+ role="img"
+ aria-label={`${c.fails} failures`}
+ className="flex h-3.5 overflow-hidden rounded-sm"
+ style={{ width: `${(c.fails / max) * 100}%` }}
+ >
+ {Object.entries(c.byClass)
+ .sort((a, b) => b[1] - a[1])
+ .map(([cls, n]) => (
+ <span key={cls} title={`${cls}: ${n}`} style={{ width: `${(n / c.fails) * 100}%`, background: classColor(cls) }} />
+ ))}
+ </span>
+ <span className="ds-text-body-xs-semibold text-ds-text-darker">{c.fails}</span>
+ </span>
+ <span className="w-40 shrink-0 text-right ds-text-body-xs-medium text-ds-text-subtle">
+ {pct(c.failRate)} fail · {c.retries} {c.retries === 1 ? 'retry' : 'retries'}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <Legend items={classes.map((cls) => ({ label: cls, color: classColor(cls) }))} />
+ </>
+ ) : (
+ <Empty>No failed commands in this window.</Empty>
+ )}
+ </Panel>
+ );
+}
+
+const SOURCE_LABEL: Record<string, string> = {
+ tool: 'Tool',
+ mcp: 'MCP',
+ llm: 'LLM',
+ hook: 'Hook',
+ orchestration: 'Orchestration',
+};
+
+export function WhatFails({ rows }: { rows: InsightsSession[] }) {
+ const groups = failuresBySource(rows);
+ const max = Math.max(1, ...groups.flatMap((g) => g.classes.map((c) => c.n)));
+ return (
+ <Panel
+ title="What fails"
+ term="whatFails"
+ question="Which kinds of failure dominate? By error class, grouped by source."
+ className="flex-[5_1_360px]"
+ >
+ {groups.length ? (
+ <div className="flex flex-col gap-3">
+ {groups.map((g) => (
+ <div key={g.source} className="flex flex-col gap-1">
+ <div className="flex justify-between ds-text-body-xs-semibold uppercase tracking-wide text-ds-text-subtle">
+ <span>{SOURCE_LABEL[g.source] ?? g.source}</span>
+ <span>{g.total}</span>
+ </div>
+ {g.classes.map((c) => (
+ <div key={c.cls} className="flex items-center gap-2 ds-text-body-xs-medium">
+ <span className="w-36 shrink-0 truncate font-mono text-ds-text-default">{c.cls}</span>
+ <span className="min-w-0 flex-1">
+ <span
+ className="block h-2.5 rounded-sm bg-ds-brand-subtler"
+ style={{ width: `${Math.max(2, (c.n / max) * 100)}%` }}
+ />
+ </span>
+ <span className="w-10 text-right font-mono text-ds-text-darker">{c.n}</span>
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <Empty>No failures in this window.</Empty>
+ )}
+ </Panel>
+ );
+}
+
+// ------------------------------------------------------------------ waste
+
+const WASTE_LABEL: Record<WasteBucket, { label: string; note: string }> = {
+ abandoned: { label: 'Abandoned spend', note: 'unresolved or stopped mid-work' },
+ retry: { label: 'Retry loops', note: 'failed calls and their retries' },
+ cacheMiss: { label: 'Cache misses', note: 'fresh input past a warm cache' },
+ reread: { label: 'Re-reads', note: 'files read again unchanged' },
+ deadSubagent: { label: 'Dead subagents', note: 'no result, failed or killed' },
+};
+
+export function WastePanel({ rows }: { rows: InsightsSession[] }) {
+ const w = wasteSummary(rows);
+ return (
+ <Panel
+ title="Waste"
+ term="waste"
+ question="Where is spend wasted?"
+ action={<Badge variant="warning">estimate</Badge>}
+ className="flex-[5_1_360px]"
+ >
+ <div className="flex items-baseline gap-2">
+ <span className="text-2xl font-semibold tracking-tight text-ds-text-darker">{fmtUsd(w.total)}</span>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">{pct(w.share)} of spend</span>
+ </div>
+ {w.total > 0 ? (
+ <div role="img" aria-label="Waste split by bucket" className="flex h-5 gap-0.5 overflow-hidden rounded-md">
+ {WASTE_BUCKETS.map((b, i) =>
+ w.buckets[b] > 0 ? (
+ <span key={b} style={{ width: `${(w.buckets[b] / w.total) * 100}%`, background: seriesColor(i) }} />
+ ) : null
+ )}
+ </div>
+ ) : null}
+ <ul className="flex flex-col gap-1">
+ {WASTE_BUCKETS.map((b, i) => (
+ <li key={b} className="flex items-center gap-2 ds-text-body-xs-medium">
+ <Swatch color={seriesColor(i)} />
+ <span className="min-w-0 flex-1 text-ds-text-default">
+ {WASTE_LABEL[b].label}
+ <span className="text-ds-text-subtle"> · {WASTE_LABEL[b].note}</span>
+ </span>
+ <span className="font-mono text-ds-text-darker">{fmtUsd(w.buckets[b])}</span>
+ </li>
+ ))}
+ </ul>
+ <p className="border-t border-ds-border-subtlest pt-2 ds-text-body-xs-medium text-ds-text-subtle">
+ Stalls (time, not money): {w.stallMs ? fmtDur(w.stallMs) : 'none'}
+ </p>
+ </Panel>
+ );
+}
+
+// ------------------------------------------------------------------ compaction
+
+function RateBar({ label, r, color }: { label: string; r: PrRate; color: string }) {
+ return (
+ <div className="flex items-center gap-3 ds-text-body-xs-medium">
+ <span className="w-28 shrink-0 text-ds-text-default">{label}</span>
+ <span className="h-3 min-w-0 flex-1 overflow-hidden rounded-sm bg-ds-gray-subtlest">
+ <span className="block h-full" style={{ width: `${(r.rate ?? 0) * 100}%`, background: color }} />
+ </span>
+ <span className="w-24 shrink-0 text-right">
+ <Rate r={r} className="ds-text-body-xs-semibold text-ds-text-darker" />{' '}
+ <span className="text-ds-text-subtle">n={r.edited}</span>
+ </span>
+ </div>
+ );
+}
+
+const fmtTokens = (n: number | null) => (n == null ? '–' : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
+
+export function CompactionPanel({ rows }: { rows: InsightsSession[] }) {
+ const c = compactionSummary(rows);
+ const stat = (value: string, label: string) => (
+ <div className="rounded-lg bg-ds-gray-subtlest p-3">
+ <div className="text-lg font-semibold text-ds-text-darker">{value}</div>
+ <div className="ds-text-body-xs-medium text-ds-text-subtle">{label}</div>
+ </div>
+ );
+ return (
+ <Panel
+ title="Compaction"
+ term="compaction"
+ question="How often does context fill up, and does it hurt?"
+ className="flex-[5_1_360px]"
+ >
+ <div className="grid grid-cols-3 gap-2">
+ {stat(c.perSession.toFixed(1), 'avg per session')}
+ {stat(pct(c.share), 'of sessions compact')}
+ {stat(fmtTokens(c.medianPreTokens), 'median tokens at compaction')}
+ </div>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-1 ds-text-body-xs-semibold text-ds-text-default">
+ PR rate
+ <InfoButton term="prRate" />
+ </div>
+ <RateBar label="No compaction" r={c.without} color="var(--ds-series-1)" />
+ <RateBar label="Compacted" r={c.withCompaction} color="var(--ds-series-5)" />
+ </div>
+ <p className="border-t border-ds-border-subtlest pt-2 ds-text-body-xs-medium text-ds-text-subtle">
+ {c.rereads} {c.rereads === 1 ? 'file' : 'files'} re-read after a compaction with no change in between.
+ </p>
+ </Panel>
+ );
+}