Skip to content

Replay your coding agent sessions as a map and a timeline

feat(viewer): search matches, Run health and Autotune pages

aiswaryasankartest80899abf842e
diff --git a/python/src/agentplay/facts.py b/python/src/agentplay/facts.py
index 66b55c5..674d772 100644
--- a/python/src/agentplay/facts.py
+++ b/python/src/agentplay/facts.py
@@ -18,7 +18,7 @@ from typing import Any
from .builder import _NON_CALL_KINDS, _error_source, estimate_cost_usd
-FACTS_VERSION = 2
+FACTS_VERSION = 3
# Outcomes whose whole cost counts as abandoned spend. `interrupted` is left
# out on purpose: stopping an agent is often the right call.
@@ -246,7 +246,7 @@ def command_label(e: dict[str, Any]) -> str:
"""
verb = str(e.get("verb") or e.get("tool") or "?")
action = (e.get("vcs") or {}).get("action")
- if action and str(action) not in verb:
+ if action and verb.split(" ")[0] in ("git", "gh") and str(action) not in verb:
verb = f"{verb} {action}"
return verb[:60]
diff --git a/python/src/agentplay/health.py b/python/src/agentplay/health.py
index 1bfd813..0fb27e9 100644
--- a/python/src/agentplay/health.py
+++ b/python/src/agentplay/health.py
@@ -44,6 +44,24 @@ QUIET_FORMS = {
}
NOISY_BYTES = 40_000 # about 10k tokens of output per run
+# What a check command is for. A passing command only replaces a failing one
+# that does the same job: `pnpm vitest` for `pnpm test`, never `git commit`
+# for `git push` or a linter for a test runner.
+_PURPOSES = (
+ ("test", ("test", "vitest", "jest", "pytest", "mocha", "spec")),
+ ("lint", ("lint", "ruff", "eslint", "clippy", "flake8", "biome")),
+ ("typecheck", ("tsc", "mypy", "pyright", "typecheck", "type-check")),
+ ("build", ("build", "compile")),
+)
+
+
+def purpose(verb: str) -> str | None:
+ low = verb.lower()
+ for name, words in _PURPOSES:
+ if any(w in low for w in words):
+ return name
+ return None
+
@dataclass
class Totals:
@@ -236,14 +254,15 @@ def fixes(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
{"name": "verified_share"},
))
- # Efficiency: a failing command whose sibling passes.
+ # Efficiency: a failing check whose sibling, doing the same job, passes.
for bad, c in cmds.items():
- if c["fails"] < 5 or c["fails"] / c["calls"] < 0.4:
+ job = purpose(bad)
+ if job is None or " " not in bad or c["fails"] < 5 or c["fails"] / c["calls"] < 0.4:
continue
family = bad.split()[0]
good = sorted(
- (v for v, g in cmds.items() if v != bad and v.split()[0] == family and g["calls"] >= 3
- and 1 - g["fails"] / g["calls"] >= 0.8),
+ (v for v, g in cmds.items() if v != bad and v.split()[0] == family and purpose(v) == job
+ and g["calls"] >= 3 and 1 - g["fails"] / g["calls"] >= 0.8),
key=lambda v: -cmds[v]["calls"],
)
if not good:
diff --git a/python/src/agentplay/search.py b/python/src/agentplay/search.py
index e53932f..aaf2a50 100644
--- a/python/src/agentplay/search.py
+++ b/python/src/agentplay/search.py
@@ -19,7 +19,7 @@ from typing import Any
from .facts import command_label
-SEARCH_VERSION = 1
+SEARCH_VERSION = 2
FACETS = ("file", "cmd", "mcp", "skill", "subagent", "model", "repo", "host", "err")
# Postings kept per term per session: enough to step through, small enough to load.
MAX_SEQS = 40
diff --git a/python/src/agentplay/server.py b/python/src/agentplay/server.py
index 63984c8..1521efe 100644
--- a/python/src/agentplay/server.py
+++ b/python/src/agentplay/server.py
@@ -582,10 +582,6 @@ class _Handler(BaseHTTPRequestHandler):
if search not in hay and r.get("sessionId") not in hits:
continue
out.append(r)
- if hits:
- # Ranked by matches, then recency; title-only matches after.
- out.sort(key=lambda r: (-(hits.get(r.get("sessionId"), {}).get("count") or 0),
- "" if r.get("sessionId") in hits else "1"))
start = _cursor_decode((q.get("cursor") or [None])[0])
if start is None:
return self._error(400, "invalid_input", "That page cursor is not valid.")
diff --git a/python/tests/test_search_health_fixes.py b/python/tests/test_search_health_fixes.py
index e580348..a676bec 100644
--- a/python/tests/test_search_health_fixes.py
+++ b/python/tests/test_search_health_fixes.py
@@ -290,3 +290,19 @@ def test_sessions_search_returns_chips(tmp_path):
finally:
httpd.shutdown()
httpd.server_close()
+
+
+def test_replacement_commands_must_do_the_same_job():
+ cmd = {"git push": {"calls": 10, "fails": 8, "retries": 0, "byClass": {"exit_code": 8}, "outBytes": 0},
+ "git commit": {"calls": 9, "fails": 0, "retries": 0, "byClass": {}, "outBytes": 0},
+ "pnpm vitest": {"calls": 10, "fails": 8, "retries": 0, "byClass": {"exit_code": 8}, "outBytes": 0},
+ "pnpm lint": {"calls": 9, "fails": 0, "retries": 0, "byClass": {}, "outBytes": 0}}
+ rows = [_row("s1", cmd=cmd, verifyAfterLastEdit=True)]
+ assert [f for f in health.fixes(rows) if f["rule"] == "use_working_command"] == []
+
+
+def test_command_label_only_names_vcs_actions_on_git_and_gh():
+ from agentplay.facts import command_label
+
+ assert command_label({"verb": "git", "vcs": {"action": "push"}}) == "git push"
+ assert command_label({"verb": "pnpm test", "vcs": {"action": "status"}}) == "pnpm test"
diff --git a/viewer/public/demo/index.json b/viewer/public/demo/index.json
index c6c0200..2f6503c 100644
--- a/viewer/public/demo/index.json
+++ b/viewer/public/demo/index.json
@@ -234,7 +234,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 5
},
- "factsVersion": 2
+ "factsVersion": 3
},
{
"sessionId": "local:codex:0199a3b2-demo-4f0c-8e55-000000000002",
@@ -389,7 +389,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 7
},
- "factsVersion": 2
+ "factsVersion": 3
},
{
"sessionId": "local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003",
@@ -486,7 +486,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 2
},
- "factsVersion": 2
+ "factsVersion": 3
}
]
}
diff --git a/viewer/src/core/health.test.ts b/viewer/src/core/health.test.ts
new file mode 100644
index 0000000..fdcef48
--- /dev/null
+++ b/viewer/src/core/health.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+import { actionText, addedLines, healthReportSchema } from './health';
+
+describe('health helpers', () => {
+ it('marks only the lines a fix adds', () => {
+ const lines = addedLines('# Notes\n\nKeep.\n', '# Notes\n\nKeep.\n\n- Run `pytest -q`.\n');
+ expect(lines.filter((l) => l.added).map((l) => l.text)).toEqual(['- Run `pytest -q`.']);
+ });
+
+ it('turns each action into text a person can paste', () => {
+ expect(actionText({ kind: 'claude_md', label: 'x', file: 'CLAUDE.md', lines: ['A', 'B'] })).toBe('- A\n- B');
+ expect(actionText({ kind: 'settings_allow', label: 'x', file: 's', entry: 'Bash(git push:*)' })).toContain('Bash(git push:*)');
+ expect(actionText({ kind: 'stop_hook', label: 'x', file: 's', command: 'pytest' })).toContain('"command": "pytest"');
+ });
+
+ it('keeps the readable fixes from a partly unreadable report', () => {
+ const r = healthReportSchema.parse({ sessions: 3, fixes: [{ id: 'a', title: 'T' }, { nope: true }] });
+ expect(r.fixes.map((f) => f.id)).toEqual(['a']);
+ expect(r.score).toBeNull();
+ });
+});
diff --git a/viewer/src/core/health.ts b/viewer/src/core/health.ts
new file mode 100644
index 0000000..d7359ee
--- /dev/null
+++ b/viewer/src/core/health.ts
@@ -0,0 +1,153 @@
+/**
+ * Run health, fixes and Autotune: the shapes `/api/health`, `/api/fix-preview`
+ * and `/api/autotune` answer with (computed by the CLI's `health.py`,
+ * `fixes.py` and `autotune.py`). Lenient on purpose: an older or newer CLI
+ * should degrade a field, not the page.
+ */
+import { z } from 'zod';
+
+const n = z.number().catch(0);
+
+export const fixActionSchema = z
+ .object({
+ kind: z.string(),
+ label: z.string().catch('Apply'),
+ file: z.string().catch(''),
+ lines: z.array(z.string()).optional().catch(undefined),
+ entry: z.string().optional().catch(undefined),
+ command: z.string().optional().catch(undefined),
+ })
+ .passthrough();
+export type FixAction = z.infer<typeof fixActionSchema>;
+
+export const fixSchema = z.object({
+ id: z.string(),
+ rule: z.string().catch(''),
+ repo: z.string().catch(''),
+ component: z.string().catch(''),
+ title: z.string(),
+ pattern: z.string().catch(''),
+ effect: z.string().catch(''),
+ points: n,
+ sessions: z.array(z.string()).catch([]),
+ actions: z.array(fixActionSchema).catch([]),
+});
+export type Fix = z.infer<typeof fixSchema>;
+
+const componentSchema = z.object({
+ key: z.string(),
+ name: z.string(),
+ value: z.number().nullable().catch(null),
+ points: z.number().nullable().catch(null),
+ prevPoints: z.number().nullable().catch(null),
+ inputs: z.array(z.tuple([z.string(), z.union([z.string(), z.number()])])).catch([]),
+ worst: z.array(z.object({ sessionId: z.string(), why: z.string() })).catch([]),
+});
+export type HealthComponent = z.infer<typeof componentSchema>;
+
+const repoSchema = z.object({
+ name: z.string(),
+ root: z.string().nullable().catch(null),
+ granted: z.boolean().catch(false),
+});
+export type RepoAccess = z.infer<typeof repoSchema>;
+
+export const healthReportSchema = z.object({
+ sessions: n,
+ minSessions: z.number().catch(10),
+ score: z.number().nullable().catch(null),
+ prevScore: z.number().nullable().catch(null),
+ components: z.array(componentSchema).catch([]),
+ fixes: z.array(z.unknown()).transform((xs) =>
+ xs.flatMap((x) => {
+ const p = fixSchema.safeParse(x);
+ return p.success ? [p.data] : [];
+ })
+ ),
+ titles: z.record(z.string(), z.string().nullable()).catch({}),
+ repos: z.array(repoSchema).catch([]),
+ applied: z
+ .array(z.object({ id: z.string(), fixId: z.string(), file: z.string(), kind: z.string().catch('') }))
+ .catch([]),
+});
+export type HealthReport = z.infer<typeof healthReportSchema>;
+
+export const fixPreviewSchema = z.object({
+ file: z.string(),
+ hash: z.string(),
+ before: z.string().catch(''),
+ after: z.string().catch(''),
+});
+export type FixPreview = z.infer<typeof fixPreviewSchema>;
+
+const effectSchema = z
+ .object({
+ id: z.string(),
+ title: z.string().nullable().catch(null),
+ repo: z.string().catch(''),
+ file: z.string().catch(''),
+ source: z.string().catch(''),
+ at: z.string().catch(''),
+ baseline: z.number().nullable().catch(null),
+ current: z.number().nullable().catch(null),
+ sessionsSince: n,
+ metric: z.object({ name: z.string() }).passthrough().nullable().catch(null),
+ })
+ .passthrough();
+export type AppliedEffect = z.infer<typeof effectSchema>;
+
+export const autotuneStatusSchema = z.object({
+ when: z.string().nullable().catch('manual'),
+ lastRun: z.string().nullable().catch(null),
+ hookInstalled: z.boolean().catch(false),
+ repos: z
+ .array(repoSchema.extend({ enabled: z.boolean().catch(false), claudeMd: z.string().catch('ask') }))
+ .catch([]),
+ pending: z
+ .array(
+ z.object({
+ fixId: z.string(),
+ title: z.string(),
+ pattern: z.string().catch(''),
+ points: n,
+ repo: z.string().catch(''),
+ action: fixActionSchema,
+ })
+ )
+ .catch([]),
+ log: z
+ .array(
+ z
+ .object({
+ at: z.string().catch(''),
+ kind: z.string(),
+ title: z.string().nullable().catch(null),
+ repo: z.string().nullable().catch(null),
+ file: z.string().nullable().optional().catch(undefined),
+ detail: z.string().nullable().optional().catch(undefined),
+ entry: z.string().nullable().optional().catch(undefined),
+ })
+ .passthrough()
+ )
+ .catch([]),
+ active: z.array(effectSchema).catch([]),
+});
+export type AutotuneStatus = z.infer<typeof autotuneStatusSchema>;
+
+/** Lines `after` adds to `before`, for a compact preview (the writer only ever adds). */
+export function addedLines(before: string, after: string): { text: string; added: boolean }[] {
+ const old = new Set(before.split('\n'));
+ return after
+ .split('\n')
+ .filter((l, i, all) => l.trim() || (i > 0 && i < all.length - 1))
+ .map((text) => ({ text, added: !old.has(text) }));
+}
+
+/** The fix text an action writes, for copying when agentplay can't write it. */
+export function actionText(a: FixAction): string {
+ if (a.kind === 'claude_md') return (a.lines ?? []).map((l) => `- ${l}`).join('\n');
+ if (a.kind === 'settings_allow') return JSON.stringify({ permissions: { allow: [a.entry] } }, null, 2);
+ if (a.kind === 'stop_hook')
+ return JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: a.command }] }] } }, null, 2);
+ return '';
+}
diff --git a/viewer/src/core/schema.ts b/viewer/src/core/schema.ts
index 3406917..551e6db 100644
--- a/viewer/src/core/schema.ts
+++ b/viewer/src/core/schema.ts
@@ -97,6 +97,25 @@ export const sessionExplorerSessionSchema = z
)
.optional()
.catch(undefined),
+ // Present when the list was searched and this session matched on what it
+ // touched (files, commands, MCP servers...), not only on its title.
+ search: z
+ .object({
+ count: z.number().default(0),
+ seqs: z.array(z.number()).default([]),
+ chips: z
+ .array(
+ z.object({
+ label: z.string(),
+ touch: z.string(),
+ seq: z.number().nullable().default(null),
+ n: z.number().default(1),
+ })
+ )
+ .default([]),
+ })
+ .optional()
+ .catch(undefined),
})
.passthrough();
export type SessionExplorerSession = z.infer<
@@ -109,6 +128,13 @@ export const sessionExplorerSessionsSchema = z
sessions: z.array(sessionExplorerSessionSchema).default([]),
nextCursor: z.string().nullable().default(null),
hasMore: z.boolean().default(false),
+ // Set when a search named command arguments, which are never stored, and
+ // the results are for the command alone.
+ searchNote: z
+ .object({ code: z.string(), command: z.string().optional() })
+ .nullable()
+ .optional()
+ .catch(undefined),
})
.passthrough();
export type SessionExplorerSessionsPage = z.infer<
diff --git a/viewer/src/data/hooks.ts b/viewer/src/data/hooks.ts
index d4aa91e..35e212e 100644
--- a/viewer/src/data/hooks.ts
+++ b/viewer/src/data/hooks.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef } from 'react';
import {
keepPreviousData,
useInfiniteQuery,
+ useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
@@ -264,3 +265,50 @@ export function useInsightsStats(range: { from?: string; to?: string }) {
retry: false,
});
}
+
+/** Run health for a range. Local server only. */
+export function useHealth(range: { from?: string; to?: string }) {
+ const source = useSessionMapSource();
+ return useQuery({
+ queryKey: ['health', source.id, range.from ?? '', range.to ?? ''] as const,
+ queryFn: () => {
+ if (!source.health) throw new SessionExplorerError('Run health needs the local CLI', 'unsupported');
+ return source.health(range);
+ },
+ enabled: !!source.health,
+ staleTime: 30 * 1000,
+ placeholderData: keepPreviousData,
+ retry: false,
+ });
+}
+
+/** Autotune status. Local server only. */
+export function useAutotune() {
+ const source = useSessionMapSource();
+ return useQuery({
+ queryKey: ['autotune', source.id] as const,
+ queryFn: () => {
+ if (!source.autotune) throw new SessionExplorerError('Autotune needs the local CLI', 'unsupported');
+ return source.autotune();
+ },
+ enabled: !!source.autotune,
+ staleTime: 15 * 1000,
+ retry: false,
+ });
+}
+
+/** A write to the local server; refreshes health and Autotune afterwards. */
+export function useWrite() {
+ const source = useSessionMapSource();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (v: { path: '/api/fix' | '/api/repos' | '/api/autotune'; body: Record<string, unknown> }) => {
+ if (!source.write) throw new SessionExplorerError('Writing fixes needs the local CLI', 'unsupported');
+ return source.write(v.path, v.body);
+ },
+ onSettled: () => {
+ void queryClient.invalidateQueries({ queryKey: ['health'] });
+ void queryClient.invalidateQueries({ queryKey: ['autotune'] });
+ },
+ });
+}
diff --git a/viewer/src/data/httpSource.ts b/viewer/src/data/httpSource.ts
index df59f58..f092449 100644
--- a/viewer/src/data/httpSource.ts
+++ b/viewer/src/data/httpSource.ts
@@ -7,6 +7,7 @@ import {
type SessionMap,
} from '@/core/schema';
import { insightsStatsSchema } from '@/core/insights';
+import { autotuneStatusSchema, fixPreviewSchema, healthReportSchema } from '@/core/health';
import { SessionExplorerError } from './errors';
import { parseMapBytes } from './parse';
import { SESSION_MAP_BATCH_MAX, type SessionMapSource } from './source';
@@ -106,6 +107,41 @@ export function httpSource(baseUrl: string): SessionMapSource {
if (!r.ok) throw await failure(r, 'stats');
return insightsStatsSchema.parse(await json(r, 'stats'));
},
+ async health(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/health?${qs.toString()}`);
+ if (!r.ok) throw await failure(r, 'health');
+ return healthReportSchema.parse(await json(r, 'health'));
+ },
+ async fixPreview(p) {
+ const qs = new URLSearchParams({ fix: p.fix, i: String(p.i) });
+ if (p.file) qs.set('file', p.file);
+ if (p.from) qs.set('from', p.from);
+ if (p.to) qs.set('to', p.to);
+ const r = await get(`/api/fix-preview?${qs.toString()}`);
+ if (!r.ok) throw await failure(r, 'fixPreview');
+ return fixPreviewSchema.parse(await json(r, 'fixPreview'));
+ },
+ async autotune() {
+ const r = await get('/api/autotune');
+ if (!r.ok) throw await failure(r, 'autotune');
+ return autotuneStatusSchema.parse(await json(r, 'autotune'));
+ },
+ async write(path, body) {
+ const r = await fetch(`${base}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const out: unknown = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ const o = out as { code?: string; error?: string };
+ throw new SessionExplorerError(o.error ?? `write failed: ${r.status}`, o.code ?? 'internal_error');
+ }
+ return out;
+ },
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 1f0a749..2dc4a23 100644
--- a/viewer/src/data/source.ts
+++ b/viewer/src/data/source.ts
@@ -8,6 +8,7 @@ import type {
SessionMap,
} from '@/core/schema';
import type { InsightsStats } from '@/core/insights';
+import type { AutotuneStatus, FixPreview, HealthReport } from '@/core/health';
export interface SessionsParams {
/** inclusive UTC `YYYY-MM-DD` */
@@ -57,6 +58,14 @@ export interface SessionMapSource {
* source with no precomputed facts (opened files).
*/
stats?(range: { from?: string; to?: string }): Promise<InsightsStats>;
+ /** Optional, local server only: Run health and its fixes for the range. */
+ health?(range: { from?: string; to?: string }): Promise<HealthReport>;
+ /** Optional, local server only: a fix action's file before and after. */
+ fixPreview?(p: { fix: string; i: number; file?: string; from?: string; to?: string }): Promise<FixPreview>;
+ /** Optional, local server only: Autotune's settings, queue and log. */
+ autotune?(): Promise<AutotuneStatus>;
+ /** Optional, local server only: a write (`/api/fix`, `/api/repos`, `/api/autotune`). */
+ write?(path: '/api/fix' | '/api/repos' | '/api/autotune', body: Record<string, unknown>): Promise<unknown>;
}
/** Max ids per `maps()` call. */
diff --git a/viewer/src/explorer/SessionExplorer.tsx b/viewer/src/explorer/SessionExplorer.tsx
index a6f5e45..67d186e 100644
--- a/viewer/src/explorer/SessionExplorer.tsx
+++ b/viewer/src/explorer/SessionExplorer.tsx
@@ -220,6 +220,8 @@ export function SessionExplorer({
const { list, sessions, selectedId } = data;
const scanning = !!useSessionExplorerStatus().data?.scanning;
const [, setScopeParams] = useQueryStates(SCOPE_PARAMS);
+ // A search chip opens its session at the matching event (`useSeekParam`).
+ const [, setJumpAt] = useQueryState('at', parseAsInteger);
// One sidebar: the list until a session is picked (or one is linked), then
// only that session; "All sessions" flips back without touching the URL.
const [sidebarMode, setSidebarMode] = useState<'list' | 'session'>(() =>
@@ -307,6 +309,19 @@ export function SessionExplorer({
loadingMore={list.isFetchingNextPage}
onLoadMore={() => void list.fetchNextPage()}
unavailable={data.mapQuery.unavailable}
+ onJump={(id, seq) => {
+ if (id !== selectedId) void setScopeParams(CLEAR_SCOPE_PARAMS);
+ void data.setSelected(id);
+ void setJumpAt(seq);
+ }}
+ searchNote={
+ list.data?.pages[0]?.searchNote?.code === 'arguments' ? (
+ <p role="note" className="rounded-md bg-ds-warning-subtlest px-2 py-1.5 ds-text-body-xs-medium text-ds-warning-darker">
+ Command arguments are never stored, so they can&rsquo;t be searched. Showing sessions that ran{' '}
+ <code className="font-mono">{list.data.pages[0].searchNote.command}</code>.
+ </p>
+ ) : null
+ }
header={
<SessionListHeader
count={sessions.length}
diff --git a/viewer/src/explorer/SessionList.tsx b/viewer/src/explorer/SessionList.tsx
index 4266ab0..1406b09 100644
--- a/viewer/src/explorer/SessionList.tsx
+++ b/viewer/src/explorer/SessionList.tsx
@@ -52,6 +52,10 @@ interface Props {
header?: ReactNode;
/** extra controls under the search (the window range select) */
toolbar?: ReactNode;
+ /** open a session at one event (a search match chip) */
+ onJump?: (sessionId: string, seq: number) => void;
+ /** a note about the search itself, under the box */
+ searchNote?: ReactNode;
}
/**
@@ -81,6 +85,8 @@ export function SessionList({
unavailable,
header,
toolbar,
+ onJump,
+ searchNote,
}: Props) {
const [tool, setTool] = useState<string>('all');
const main = sessions.filter(isMainSession);
@@ -131,11 +137,12 @@ export function SessionList({
<Input
value={search}
onChange={(e) => onSearch(e.target.value)}
- placeholder="Filter by title or repo"
- aria-label="Filter sessions"
+ placeholder="Search titles, files, commands, MCP…"
+ aria-label="Search sessions"
className="h-8 pl-8"
/>
</div>
+ {searchNote}
{toolbar}
{tools.length > 1 ? (
<ToolFilter tools={tools} tool={tool} onTool={setTool} />
@@ -170,6 +177,7 @@ export function SessionList({
rowRef={s.sessionId === selectedId ? selectedRef : undefined}
onSelect={() => onSelect(s.sessionId)}
onOpen={() => onOpen(s.sessionId)}
+ onJump={onJump ? (seq) => onJump(s.sessionId, seq) : undefined}
/>
))}
</div>
@@ -240,6 +248,7 @@ function SessionRow({
unavailable,
onSelect,
onOpen,
+ onJump,
rowRef,
}: {
s: SessionExplorerSession;
@@ -247,6 +256,7 @@ function SessionRow({
unavailable: boolean;
onSelect: () => void;
onOpen: () => void;
+ onJump?: (seq: number) => void;
rowRef?: React.Ref<HTMLDivElement>;
}) {
return (
@@ -275,6 +285,9 @@ function SessionRow({
</span>
<SessionRowBadges s={s} unavailable={unavailable} />
</button>
+ {s.search && onJump ? (
+ <SearchMatches search={s.search} selected={selected} onJump={onJump} />
+ ) : null}
{/* Always there for the selected row -- you just clicked it, so that
* is where the next step belongs. Quiet on the rest until pointed at
* or tabbed to, so a long list does not grow a button per row. */}
@@ -341,3 +354,62 @@ function SessionRowBadges({
</span>
);
}
+
+const TOUCH_DOT: Record<string, string> = {
+ hit: 'bg-ds-gray-subtler',
+ read: 'bg-ds-brand-subtler',
+ edit: 'bg-ds-brand-default',
+ fail: 'bg-ds-danger-default',
+};
+
+/**
+ * What a searched session matched on, as chips that open it at that event,
+ * and on the selected row a stepper through every matching event.
+ */
+function SearchMatches({
+ search,
+ selected,
+ onJump,
+}: {
+ search: NonNullable<SessionExplorerSession['search']>;
+ selected: boolean;
+ onJump: (seq: number) => void;
+}) {
+ const [i, setI] = useState(0);
+ const seqs = search.seqs;
+ const go = (next: number) => {
+ const k = (next + seqs.length) % seqs.length;
+ setI(k);
+ onJump(seqs[k]);
+ };
+ return (
+ <div className="flex flex-col gap-1.5 px-2 pb-2">
+ <div className="flex flex-wrap gap-1">
+ {search.chips.map((c) => (
+ <button
+ key={`${c.label}:${c.touch}`}
+ type="button"
+ disabled={c.seq == null}
+ onClick={() => c.seq != null && onJump(c.seq)}
+ aria-label={c.seq != null ? `${c.label}: open at that event` : c.label}
+ className="inline-flex items-center gap-1.5 rounded-full border border-ds-border-subtlest bg-ds-surface-white px-2 py-0.5 ds-text-body-xs-medium text-ds-text-default hover:border-ds-brand-subtler disabled:cursor-default"
+ >
+ <span aria-hidden className={cn('size-2 rounded-full', TOUCH_DOT[c.touch] ?? TOUCH_DOT.hit)} />
+ {c.label}
+ </button>
+ ))}
+ </div>
+ {selected && seqs.length > 1 ? (
+ <div className="flex items-center gap-1 ds-text-body-xs-medium text-ds-text-subtle">
+ <Button variant="ghost" size="iconSm" className="size-6" aria-label="Previous match" onClick={() => go(i - 1)}>
+ ‹
+ </Button>
+ Match {i + 1} of {seqs.length}
+ <Button variant="ghost" size="iconSm" className="size-6" aria-label="Next match" onClick={() => go(i + 1)}>
+ ›
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/viewer/src/insights/AutotuneView.tsx b/viewer/src/insights/AutotuneView.tsx
new file mode 100644
index 0000000..048a8b4
--- /dev/null
+++ b/viewer/src/insights/AutotuneView.tsx
@@ -0,0 +1,261 @@
+import { Check } from '@phosphor-icons/react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useAutotune, useWrite } from '@/data/hooks';
+import { useSessionMapSource } from '@/data/SourceContext';
+import { cn } from '@/lib/utils';
+import type { AppliedEffect, AutotuneStatus } from '@/core/health';
+import { InfoButton } from './InfoButton';
+import { Panel } from './panels';
+
+export function AutotuneView() {
+ const source = useSessionMapSource();
+ const q = useAutotune();
+ if (!source.autotune) {
+ 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">
+ Autotune writes to your own repos, so it runs from the CLI on your machine. Run{' '}
+ <code className="font-mono">uvx agentplay</code> to set it up.
+ </div>
+ );
+ }
+ if (q.isPending) return <Skeleton className="h-96 rounded-xl" />;
+ if (q.isError || !q.data) {
+ return <p className="ds-text-body-sm-medium text-ds-text-default">Autotune could not be loaded. Update the CLI if it is older than this viewer.</p>;
+ }
+ const s = q.data;
+ return (
+ <div className="flex flex-col gap-3">
+ <Summary s={s} />
+ <div className="flex flex-wrap items-start gap-3">
+ <div className="flex min-w-0 flex-[5_1_400px] flex-col gap-3">
+ <Repos s={s} />
+ <Schedule s={s} />
+ </div>
+ <div className="flex min-w-0 flex-[7_1_520px] flex-col gap-3">
+ <Waiting s={s} />
+ <Log s={s} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Summary({ s }: { s: AutotuneStatus }) {
+ const on = s.repos.filter((r) => r.enabled && r.granted);
+ const write = useWrite();
+ return (
+ <section className="flex flex-wrap items-center gap-4 rounded-xl border border-ds-border-subtlest bg-ds-surface-white p-4">
+ <div className="min-w-0 flex-1">
+ <h2 className="flex items-center gap-1 ds-text-title-sm-semibold text-ds-text-darker">
+ Autotune daily <InfoButton term="autotune" />
+ </h2>
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">
+ {on.length
+ ? `On for ${on.map((r) => r.name).join(', ')}. Last run ${s.lastRun ? new Date(s.lastRun).toLocaleString() : 'never'}.`
+ : 'Off. Allow writes to a repo and turn it on below.'}
+ </p>
+ </div>
+ <Badge variant={on.length ? 'success' : 'secondary'}>{on.length ? 'On' : 'Off'}</Badge>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!on.length || write.isPending}
+ onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'run' } })}
+ >
+ Run now
+ </Button>
+ </section>
+ );
+}
+
+function Repos({ s }: { s: AutotuneStatus }) {
+ const write = useWrite();
+ return (
+ <Panel title="Repos it can write to" question="Found in your sessions. It writes nowhere else.">
+ {s.repos.length ? (
+ <ul className="flex flex-col gap-2">
+ {s.repos.map((r) => (
+ <li key={r.name} className="flex flex-col gap-2 rounded-lg border border-ds-border-subtlest p-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="min-w-0 flex-1">
+ <div className="ds-text-body-sm-semibold text-ds-text-darker">{r.name}</div>
+ <div className="truncate font-mono text-xs text-ds-text-subtle">{r.root ?? 'no checkout on this machine'}</div>
+ </div>
+ {r.granted ? (
+ <>
+ <span className="inline-flex items-center gap-1 ds-text-body-xs-semibold text-ds-success-darker">
+ <Check size={13} aria-hidden /> Can write
+ </span>
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => write.mutate({ path: '/api/repos', body: { action: 'revoke', repo: r.name } })}>
+ Revoke
+ </Button>
+ </>
+ ) : r.root ? (
+ <Button size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/repos', body: { action: 'grant', repo: r.name } })}>
+ Allow writes
+ </Button>
+ ) : (
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">Copy-only</span>
+ )}
+ </div>
+ {r.granted ? (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 ds-text-body-xs-medium text-ds-text-default">
+ <label className="inline-flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={r.enabled}
+ onChange={(e) => write.mutate({ path: '/api/autotune', body: { action: e.target.checked ? 'enable' : 'disable', repo: r.name } })}
+ className="size-4 accent-[var(--ds-brand-default)]"
+ />
+ Autotune this repo
+ </label>
+ <label className="inline-flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={r.claudeMd === 'auto'}
+ disabled={!r.enabled}
+ onChange={(e) => write.mutate({ path: '/api/autotune', body: { action: 'shared', repo: r.name, value: e.target.checked } })}
+ className="size-4 accent-[var(--ds-brand-default)]"
+ />
+ Write to shared CLAUDE.md instead of CLAUDE.local.md
+ <InfoButton term="scopeFiles" />
+ </label>
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">No repos yet. Build your sessions with the CLI first.</p>
+ )}
+ </Panel>
+ );
+}
+
+function Schedule({ s }: { s: AutotuneStatus }) {
+ return (
+ <Panel title="When it runs" question="No background service needed.">
+ <p className="ds-text-body-xs-medium text-ds-text-default">
+ {s.hookInstalled
+ ? 'At the first Claude Code session each day, from a SessionStart hook in your user settings.'
+ : s.when && /^\d{1,2}:\d{2}$/.test(s.when)
+ ? `Daily at ${s.when}, from the cron line \`agentplay autotune on --at ${s.when}\` printed.`
+ : 'Not scheduled yet. Turn it on from a terminal:'}
+ </p>
+ <pre className="overflow-x-auto rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest px-3 py-2 font-mono text-xs leading-relaxed text-ds-text-darker">
+ {`$ agentplay autotune on # at session start\n$ agentplay autotune on --at 09:00 # or a set time, via cron\n$ agentplay autotune status`}
+ </pre>
+ <p className="flex items-center gap-1 ds-text-body-xs-medium text-ds-text-subtle">
+ It only edits its own block in each file.
+ <InfoButton term="managedBlock" />
+ </p>
+ </Panel>
+ );
+}
+
+function Waiting({ s }: { s: AutotuneStatus }) {
+ const write = useWrite();
+ return (
+ <Panel
+ title="Waiting for you"
+ question="Changes that grant access or run code. Autotune never makes these on its own."
+ action={s.pending.length ? <Badge variant="warning">{s.pending.length} waiting</Badge> : null}
+ >
+ {s.pending.length ? (
+ <ul className="flex flex-col gap-2">
+ {s.pending.map((p) => (
+ <li key={p.fixId} className="flex flex-col gap-2 rounded-lg border border-ds-border-subtlest p-3">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <span className="ds-text-body-sm-semibold text-ds-text-darker">{p.title}</span>
+ {p.points ? <span className="ds-text-body-xs-semibold text-ds-success-darker">+{p.points.toFixed(1)} pts</span> : null}
+ </div>
+ <p className="ds-text-body-xs-medium text-ds-text-default">{p.pattern}</p>
+ <div className="rounded-md border border-ds-border-subtlest font-mono text-xs">
+ <div className="bg-ds-gray-subtlest px-2 py-1 text-ds-text-default">{p.action.file}</div>
+ <div className="bg-ds-success-subtlest px-2 py-1 text-ds-success-darker">
+ + {p.action.entry ?? p.action.command ?? (p.action.lines ?? []).join(' ')}
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'approve', fixId: p.fixId } })}>
+ {p.action.label}
+ </Button>
+ <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'dismiss', fixId: p.fixId } })}>
+ Not now
+ </Button>
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'never', fixId: p.fixId } })}>
+ Never suggest this
+ </Button>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">Nothing waiting.</p>
+ )}
+ </Panel>
+ );
+}
+
+const fmtMetric = (e: AppliedEffect, v: number | null) => {
+ if (v == null) return '–';
+ const name = e.metric?.name;
+ if (name === 'verified_share' || name === 'fail_rate') return `${Math.round(v * 100)}%`;
+ if (name === 'out_bytes') return `${Math.round(v / 4000)}k tokens/run`;
+ return v.toFixed(2);
+};
+
+function Log({ s }: { s: AutotuneStatus }) {
+ const write = useWrite();
+ const active = new Map(s.active.map((e) => [e.id, e]));
+ return (
+ <Panel title="What Autotune changed" question="Each change is measured on its own metric. No effect after 15 sessions means it is removed.">
+ {s.log.length ? (
+ <ol className="flex flex-col">
+ {s.log.map((l, i) => {
+ const e = l.entry ? active.get(l.entry) : undefined;
+ return (
+ <li key={`${l.at}:${i}`} className="flex gap-3 border-b border-ds-border-subtlest py-2 last:border-0">
+ <span
+ aria-hidden
+ className={cn(
+ 'mt-1.5 size-2.5 shrink-0 rounded-full',
+ l.kind === 'retire' || l.kind === 'error' ? 'bg-ds-gray-subtler' : l.kind === 'queue' ? 'bg-ds-warning-default' : 'bg-ds-brand-subtler'
+ )}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap justify-between gap-2">
+ <span className="ds-text-body-xs-semibold text-ds-text-darker">
+ {{ add: 'Added', approve: 'You approved', queue: 'Waiting for you', retire: 'Retired', error: 'Could not write' }[l.kind] ?? l.kind}: {l.title}
+ </span>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">{l.at ? new Date(l.at).toLocaleDateString() : ''}</span>
+ </div>
+ <div className="ds-text-body-xs-medium text-ds-text-subtle">
+ {[l.file, l.repo].filter(Boolean).join(' · ')}
+ {l.detail ? ` · ${l.detail}` : ''}
+ </div>
+ {e ? (
+ <div className="ds-text-body-xs-medium text-ds-text-default">
+ {e.sessionsSince
+ ? `${fmtMetric(e, e.baseline)} before → ${fmtMetric(e, e.current)} over ${e.sessionsSince} sessions since`
+ : 'Measuring: no sessions since yet'}
+ </div>
+ ) : null}
+ </div>
+ {e ? (
+ <Button variant="link" size="sm" className="h-7 shrink-0 px-1 text-xs" onClick={() => write.mutate({ path: '/api/fix', body: { action: 'undo', entry: e.id } })}>
+ Undo
+ </Button>
+ ) : null}
+ </li>
+ );
+ })}
+ </ol>
+ ) : (
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">No changes yet.</p>
+ )}
+ </Panel>
+ );
+}
diff --git a/viewer/src/insights/InsightsView.tsx b/viewer/src/insights/InsightsView.tsx
index c413f2f..7c7ecc8 100644
--- a/viewer/src/insights/InsightsView.tsx
+++ b/viewer/src/insights/InsightsView.tsx
@@ -1,4 +1,6 @@
import { useMemo, useState } from 'react';
+import { parseAsStringEnum, useQueryState } from 'nuqs';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { CalendarBlankIcon } from '@phosphor-icons/react';
import {
Select,
@@ -23,6 +25,11 @@ import {
WhatFails,
} from './panels';
import { SearchHeatmap } from './SearchHeatmap';
+import { RunHealthView } from './RunHealthView';
+import { AutotuneView } from './AutotuneView';
+
+const PAGES = ['overview', 'health', 'autotune'] as const;
+type Page = (typeof PAGES)[number];
const ALL = '__all__';
@@ -91,11 +98,12 @@ export function InsightsView({
const range = useMemo(() => sessionWindowRange(windowKey, new Date()), [windowKey]);
const stats = useInsightsStats(range);
const [filter, setFilter] = useState<InsightsFilter>({});
+ const [page, setPage] = useQueryState('ipage', parseAsStringEnum([...PAGES]).withDefault('overview'));
const all = stats.data?.sessions ?? [];
const options = useMemo(() => filterOptions(all), [all]);
const rows = useMemo(() => filterSessions(all, filter), [all, filter]);
- if (!source.stats) {
+ if (!source.stats && page === 'overview') {
return (
<Notice>
Insights read the facts the CLI stores for each session, so they are not available for opened map files. Go back
@@ -113,6 +121,19 @@ export function InsightsView({
Patterns across your sessions. Root sessions only; computed on this machine.
</p>
</div>
+ <ToggleGroup
+ value={[page]}
+ onValueChange={(v: unknown[]) => {
+ const next = v.find((x): x is Page => (PAGES as readonly unknown[]).includes(x));
+ if (next) void setPage(next === 'overview' ? null : next);
+ }}
+ aria-label="Insights pages"
+ className="mr-auto"
+ >
+ <ToggleGroupItem value="overview">Overview</ToggleGroupItem>
+ <ToggleGroupItem value="health">Run health</ToggleGroupItem>
+ <ToggleGroupItem value="autotune">Autotune</ToggleGroupItem>
+ </ToggleGroup>
<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
@@ -136,6 +157,7 @@ export function InsightsView({
</SelectContent>
</Select>
</label>
+ {page === 'overview' ? (<>
<FilterSelect
label="Agent"
value={filter.agent ?? null}
@@ -158,9 +180,14 @@ export function InsightsView({
allLabel="All models"
onChange={(model) => setFilter((f) => ({ ...f, model }))}
/>
+ </>) : null}
</div>
</div>
+ {page === 'health' ? <RunHealthView range={range} /> : null}
+ {page === 'autotune' ? <AutotuneView /> : null}
+ {page !== 'overview' ? null : (<>
+
{stats.isPending ? (
<div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-3">
{[0, 1, 2, 3].map((i) => (
@@ -193,6 +220,7 @@ export function InsightsView({
<SearchHeatmap rows={rows} />
</>
)}
+ </>)}
</main>
);
}
diff --git a/viewer/src/insights/RunHealthView.tsx b/viewer/src/insights/RunHealthView.tsx
new file mode 100644
index 0000000..6cb5540
--- /dev/null
+++ b/viewer/src/insights/RunHealthView.tsx
@@ -0,0 +1,448 @@
+import { useState } from 'react';
+import { parseAsString, useQueryStates } from 'nuqs';
+import { Check, Copy, Plus } from '@phosphor-icons/react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useHealth, useWrite } from '@/data/hooks';
+import { useSessionMapSource } from '@/data/SourceContext';
+import { cn } from '@/lib/utils';
+import {
+ actionText,
+ addedLines,
+ type Fix,
+ type FixAction,
+ type FixPreview,
+ type HealthComponent,
+ type HealthReport,
+} from '@/core/health';
+import { Panel } from './panels';
+
+type Range = { from?: string; to?: string };
+
+/** Navigate to one session (and event) in the explorer. */
+function useOpenSession() {
+ const [, setNav] = useQueryStates({ tab: parseAsString, session: parseAsString, at: parseAsString });
+ return (sessionId: string) => void setNav({ tab: null, session: sessionId, at: null });
+}
+
+export function RunHealthView({ range }: { range: Range }) {
+ const source = useSessionMapSource();
+ const health = useHealth(range);
+ if (!source.health) {
+ return (
+ <Note>
+ Run health reads your local store through the CLI. Run <code className="font-mono">uvx agentplay</code> to see
+ yours; the demo has too few sessions to score.
+ </Note>
+ );
+ }
+ if (health.isPending) return <Skeleton className="h-96 rounded-xl" />;
+ if (health.isError || !health.data) {
+ return <Note>Run health could not be loaded. If the CLI is older than this viewer, update it.</Note>;
+ }
+ const h = health.data;
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap gap-3">
+ <ScoreCard h={h} />
+ <Components h={h} />
+ </div>
+ <PointsOnTheTable h={h} range={range} />
+ </div>
+ );
+}
+
+function Note({ 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>
+ );
+}
+
+// ------------------------------------------------------------------ score
+
+function ScoreCard({ h }: { h: HealthReport }) {
+ const v = h.score;
+ const delta = v != null && h.prevScore != null ? Math.round((v - h.prevScore) * 10) / 10 : null;
+ const C = 2 * Math.PI * 52;
+ return (
+ <Panel title="Run health" term="runHealth" className="flex-[4_1_320px]">
+ <div className="flex items-center gap-5">
+ <div className="relative size-32 shrink-0" role="img" aria-label={v == null ? 'Not enough sessions to score' : `Run health ${Math.round(v)} out of 100`}>
+ <svg viewBox="0 0 120 120" className="size-32" aria-hidden>
+ <circle cx="60" cy="60" r="52" fill="none" stroke="var(--primitive-gray-100)" strokeWidth="12" />
+ {v != null ? (
+ <circle
+ cx="60"
+ cy="60"
+ r="52"
+ fill="none"
+ stroke="var(--ds-series-1)"
+ strokeWidth="12"
+ strokeLinecap="round"
+ strokeDasharray={`${(v / 100) * C} ${C}`}
+ transform="rotate(-90 60 60)"
+ />
+ ) : null}
+ </svg>
+ <div className="absolute inset-0 flex flex-col items-center justify-center">
+ <span className="text-4xl font-semibold tracking-tight text-ds-text-darker">{v == null ? '–' : Math.round(v)}</span>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">of 100</span>
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ {delta != null ? (
+ <Badge variant={delta >= 0 ? 'success' : 'warning'} className="self-start">
+ {delta >= 0 ? '+' : ''}
+ {delta} vs previous window
+ </Badge>
+ ) : null}
+ <p className="ds-text-body-xs-medium text-ds-text-default">
+ {v == null
+ ? `Needs ${h.minSessions} sessions in the window to score; ${h.sessions} so far. The parts below still show.`
+ : 'How well your agents are set up and run, not how hard the work was. Every input is something you can change.'}
+ </p>
+ </div>
+ </div>
+ <p className="border-t border-ds-border-subtlest pt-2 ds-text-body-xs-medium text-ds-text-subtle">
+ {h.sessions} root sessions in this window. Cursor sessions count without cost or cache data.
+ </p>
+ </Panel>
+ );
+}
+
+function Components({ h }: { h: HealthReport }) {
+ const [sel, setSel] = useState(h.components[1]?.key ?? h.components[0]?.key);
+ const open = useOpenSession();
+ const c = h.components.find((x) => x.key === sel) ?? h.components[0];
+ const when: Record<string, string> = {
+ shipping: 'Sessions that edit code and open a PR',
+ verification: 'Edits followed by a passing test, build or lint',
+ efficiency: 'Low failure and retry rate; high cache reuse',
+ context: 'Few context compactions and re-reads',
+ environment: 'Few permission, configuration and integration errors',
+ };
+ return (
+ <Panel title="Components" term="components" question="20 points each" className="flex-[7_1_520px]">
+ <div className="flex flex-col gap-1" role="listbox" aria-label="Run health components">
+ {h.components.map((x) => (
+ <ComponentRow key={x.key} c={x} when={when[x.key] ?? ''} selected={x.key === c?.key} onSelect={() => setSel(x.key)} />
+ ))}
+ </div>
+ {c ? (
+ <div className="flex flex-col gap-2 rounded-lg border border-ds-border-subtlest bg-ds-gray-subtlest p-3">
+ <div className="ds-text-body-xs-semibold text-ds-text-darker">
+ {c.name} · {c.points == null ? '–' : c.points.toFixed(1)} / 20
+ </div>
+ <dl className="grid grid-cols-[repeat(auto-fit,minmax(140px,1fr))] gap-2">
+ {c.inputs.map(([k, v]) => (
+ <div key={k} className="rounded-md border border-ds-border-subtlest bg-ds-surface-white px-2 py-1.5">
+ <dt className="ds-text-body-xs-medium text-ds-text-subtle">{k}</dt>
+ <dd className="ds-text-body-sm-semibold text-ds-text-darker">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ {c.worst.length ? (
+ <>
+ <div className="ds-text-body-xs-semibold text-ds-text-default">Sessions that cost the most points</div>
+ <ul className="flex flex-col gap-1">
+ {c.worst.map((w) => (
+ <li key={w.sessionId}>
+ <button
+ type="button"
+ onClick={() => open(w.sessionId)}
+ className="flex w-full items-center gap-2 text-left ds-text-body-xs-medium text-ds-text-default hover:underline"
+ >
+ <span className="min-w-0 flex-1 truncate">{h.titles[w.sessionId] ?? w.sessionId}</span>
+ <span className="text-ds-text-subtle">{w.why}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </>
+ ) : null}
+ </div>
+ ) : null}
+ </Panel>
+ );
+}
+
+function ComponentRow({ c, when, selected, onSelect }: { c: HealthComponent; when: string; selected: boolean; onSelect: () => void }) {
+ const delta = c.points != null && c.prevPoints != null ? Math.round((c.points - c.prevPoints) * 10) / 10 : null;
+ return (
+ <button
+ type="button"
+ role="option"
+ aria-selected={selected}
+ onClick={onSelect}
+ className={cn(
+ 'flex items-center gap-4 rounded-lg px-3 py-2 text-left',
+ selected ? 'bg-ds-brand-lightest ring-1 ring-ds-brand-subtlest' : 'hover:bg-ds-gray-subtlest'
+ )}
+ >
+ <span className="w-60 shrink-0">
+ <span className="block ds-text-body-sm-semibold text-ds-text-darker">{c.name}</span>
+ <span className="block ds-text-body-xs-medium text-ds-text-subtle">{when}</span>
+ </span>
+ <span className="h-2.5 min-w-0 flex-1 overflow-hidden rounded-full bg-ds-gray-subtlest">
+ <span
+ className="block h-full rounded-full"
+ style={{ width: `${((c.points ?? 0) / 20) * 100}%`, background: (c.points ?? 20) < 13 ? 'var(--ds-series-5)' : 'var(--ds-series-1)' }}
+ />
+ </span>
+ <span className="w-16 shrink-0 text-right">
+ <span className="text-lg font-semibold text-ds-text-darker">{c.points == null ? '–' : c.points.toFixed(1)}</span>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle"> /20</span>
+ </span>
+ <span className={cn('w-10 shrink-0 text-right ds-text-body-xs-semibold', delta == null ? 'text-ds-text-subtle' : delta >= 0 ? 'text-ds-success-darker' : 'text-ds-warning-darker')}>
+ {delta == null ? '' : `${delta >= 0 ? '+' : ''}${delta}`}
+ </span>
+ </button>
+ );
+}
+
+// ------------------------------------------------------------------ fixes
+
+const COMPONENT_LABEL: Record<string, string> = {
+ shipping: 'Shipping',
+ verification: 'Verification',
+ efficiency: 'Efficiency',
+ context: 'Context',
+ environment: 'Environment',
+};
+
+function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {
+ const write = useWrite();
+ const [showAll, setShowAll] = useState(false);
+ const applied = new Map(h.applied.map((a) => [a.fixId, a]));
+ const repos = new Map(h.repos.map((r) => [r.name, r]));
+ const fixes = showAll ? h.fixes : h.fixes.slice(0, 5);
+ const pending = h.fixes.filter((f) => !applied.has(f.id) && f.actions.length && repos.get(f.repo)?.granted);
+ const gain = h.fixes.filter((f) => !applied.has(f.id)).reduce((s, f) => s + f.points, 0);
+ return (
+ <Panel
+ title="Points on the table"
+ term="pointsOnTable"
+ question="Specific fixes, ranked by the points each would recover. Each names the command, tool or server behind it."
+ action={
+ pending.length ? (
+ <Button
+ size="sm"
+ disabled={write.isPending}
+ onClick={() => {
+ for (const f of pending) {
+ write.mutate({ path: '/api/fix', body: { action: 'apply', fix: f.id, i: 0, ...range } });
+ }
+ }}
+ >
+ Apply {pending.length} {pending.length === 1 ? 'fix' : 'fixes'}
+ </Button>
+ ) : null
+ }
+ >
+ {write.isError ? (
+ <p role="alert" className="rounded-md bg-ds-danger-subtlest px-3 py-2 ds-text-body-xs-medium text-ds-danger-darkest">
+ {(write.error as Error).message}
+ </p>
+ ) : null}
+ {h.fixes.length ? (
+ <>
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">
+ Up to +{gain.toFixed(1)} points if every open fix works. Overlapping fixes are not double counted in the score itself.
+ </p>
+ <ol className="flex flex-col gap-2">
+ {fixes.map((f, n) => (
+ <FixCard
+ key={f.id}
+ fix={f}
+ n={h.fixes.indexOf(f) + 1 || n + 1}
+ applied={applied.get(f.id)}
+ repo={repos.get(f.repo)}
+ range={range}
+ titles={h.titles}
+ />
+ ))}
+ </ol>
+ {h.fixes.length > 5 ? (
+ <Button variant="ghost" size="sm" className="self-start" onClick={() => setShowAll((v) => !v)}>
+ {showAll ? 'Show top 5' : `Show all ${h.fixes.length}`}
+ </Button>
+ ) : null}
+ </>
+ ) : (
+ <p className="py-6 text-center ds-text-body-xs-medium text-ds-text-subtle">
+ Nothing specific stands out in this window. Fixes appear when a pattern can be traced to a named command, tool or server.
+ </p>
+ )}
+ </Panel>
+ );
+}
+
+function FixCard({
+ fix,
+ n,
+ applied,
+ repo,
+ range,
+ titles,
+}: {
+ fix: Fix;
+ n: number;
+ applied?: { id: string; file: string };
+ repo?: { name: string; root: string | null; granted: boolean };
+ range: Range;
+ titles: Record<string, string | null>;
+}) {
+ const write = useWrite();
+ const source = useSessionMapSource();
+ const open = useOpenSession();
+ const [preview, setPreview] = useState<{ i: number; p: FixPreview } | null>(null);
+ const [copied, setCopied] = useState(false);
+ const showPreview = async (i: number) => {
+ if (preview?.i === i) return setPreview(null);
+ if (!source.fixPreview) return;
+ try {
+ setPreview({ i, p: await source.fixPreview({ fix: fix.id, i, ...range }) });
+ } catch {
+ setPreview(null);
+ }
+ };
+ return (
+ <li className={cn('flex flex-col gap-2 rounded-lg border p-3', applied ? 'border-ds-brand-subtlest bg-ds-brand-lightest' : 'border-ds-border-subtlest')}>
+ <div className="flex gap-3">
+ <span
+ className={cn(
+ 'flex size-12 shrink-0 flex-col items-center justify-center rounded-lg border',
+ applied ? 'border-transparent bg-ds-brand-default text-ds-brand-subtlest' : 'border-ds-brand-subtlest bg-ds-brand-lightest text-ds-success-darker'
+ )}
+ >
+ <span className="text-base font-semibold">{fix.points ? `+${fix.points.toFixed(1)}` : '–'}</span>
+ <span className="text-[10px]">pts</span>
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="ds-text-body-sm-semibold text-ds-text-darker">{fix.title}</span>
+ <Badge variant="secondary">{COMPONENT_LABEL[fix.component] ?? fix.component}</Badge>
+ {fix.repo ? <Badge variant="outline">{fix.repo}</Badge> : null}
+ </div>
+ <p className="ds-text-body-xs-medium text-ds-text-default">{fix.pattern}</p>
+ <p className="ds-text-body-xs-medium text-ds-text-subtle">Expected: {fix.effect}</p>
+ {fix.sessions.length ? (
+ <button
+ type="button"
+ onClick={() => open(fix.sessions[0])}
+ className="self-start ds-text-body-xs-medium text-ds-text-default underline-offset-2 hover:underline"
+ title={titles[fix.sessions[0]] ?? undefined}
+ >
+ {fix.sessions.length} {fix.sessions.length === 1 ? 'session' : 'sessions'} →
+ </button>
+ ) : null}
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ {applied ? (
+ <>
+ <span className="inline-flex items-center gap-1.5 ds-text-body-xs-semibold text-ds-success-darker">
+ <Check size={14} aria-hidden /> Added to {applied.file}
+ </span>
+ <Button
+ variant="link"
+ size="sm"
+ className="h-7 px-1"
+ disabled={write.isPending}
+ onClick={() => write.mutate({ path: '/api/fix', body: { action: 'undo', entry: applied.id } })}
+ >
+ Undo
+ </Button>
+ </>
+ ) : !fix.actions.length ? (
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">Nothing to write: this names an integration to fix by hand.</span>
+ ) : repo?.granted ? (
+ <>
+ {fix.actions.map((a, i) => (
+ <ActionButton
+ key={a.label}
+ a={a}
+ primary={i === 0}
+ disabled={write.isPending}
+ onClick={() =>
+ write.mutate({
+ path: '/api/fix',
+ body: { action: 'apply', fix: fix.id, i, hash: preview?.i === i ? preview.p.hash : undefined, ...range },
+ })
+ }
+ />
+ ))}
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => void showPreview(0)}>
+ {preview ? 'Hide change' : 'Preview change'}
+ </Button>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">
+ or run <code className="rounded bg-ds-gray-subtlest px-1.5 py-0.5 font-mono text-ds-text-darker">agentplay fix apply {n}</code>
+ </span>
+ </>
+ ) : repo?.root ? (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 text-xs"
+ disabled={write.isPending}
+ onClick={() => write.mutate({ path: '/api/repos', body: { action: 'grant', repo: fix.repo } })}
+ >
+ Allow writes to {fix.repo}
+ </Button>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">agentplay writes only to the four agent files, and every change can be undone.</span>
+ </>
+ ) : (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1 text-xs"
+ onClick={() => {
+ void navigator.clipboard?.writeText(actionText(fix.actions[0]));
+ setCopied(true);
+ }}
+ >
+ <Copy size={12} aria-hidden /> {copied ? 'Copied' : 'Copy'}
+ </Button>
+ <span className="ds-text-body-xs-medium text-ds-text-subtle">No checkout of {fix.repo || 'this repo'} on this machine, so agentplay can&rsquo;t write it.</span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ {preview ? (
+ <div className="ml-[3.75rem] overflow-hidden rounded-md border border-ds-border-subtlest">
+ <div className="flex justify-between bg-ds-gray-subtlest px-3 py-1 font-mono text-xs text-ds-text-default">
+ <span>{preview.p.file}</span>
+ </div>
+ <pre className="max-h-64 overflow-auto py-1 font-mono text-xs leading-relaxed">
+ {addedLines(preview.p.before, preview.p.after).map((l, i) => (
+ <div key={i} className={cn('whitespace-pre-wrap px-3', l.added ? 'bg-ds-success-subtlest text-ds-success-darker' : 'text-ds-text-subtle')}>
+ {l.added ? '+ ' : ' '}
+ {l.text}
+ </div>
+ ))}
+ </pre>
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
+function ActionButton({ a, primary, disabled, onClick }: { a: FixAction; primary: boolean; disabled: boolean; onClick: () => void }) {
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={onClick}
+ className={cn('h-7 gap-1 px-2.5 text-xs', primary ? 'border-ds-brand-subtler text-ds-text-darker' : 'text-ds-text-default')}
+ >
+ {primary ? <Plus size={12} aria-hidden /> : null}
+ {a.label}
+ </Button>
+ );
+}
+
diff --git a/viewer/src/insights/glossary.ts b/viewer/src/insights/glossary.ts
index 4b63293..d901031 100644
--- a/viewer/src/insights/glossary.ts
+++ b/viewer/src/insights/glossary.ts
@@ -122,6 +122,52 @@ export const GLOSSARY = {
['Re-reads after compaction', 'Files read again after a compaction with no change to them in between.'],
],
},
+ runHealth: {
+ title: 'Run health',
+ paras: [
+ 'A 0–100 score for how well your agents are set up and run, not how hard the work was. It adds five parts worth 20 points each.',
+ `It compares you only with your own previous window of the same length. No total is shown until the window has ${MIN_SAMPLE} sessions.`,
+ ],
+ },
+ components: {
+ title: 'Run health components',
+ paras: ['Each part scores 0–20 from a formula over your sessions in the window. Select one to see its inputs and the sessions that cost the most points.'],
+ rows: [
+ ['Shipping', 'Sessions that opened a PR ÷ sessions that edited code.'],
+ ['Verification', 'Sessions where tests, a build or a linter passed after the last edit ÷ sessions that edited code.'],
+ ['Efficiency', 'Half how few calls failed or were retried, half the share of input read from the prompt cache.'],
+ ['Context hygiene', 'How rarely sessions reach the context limit, and how few files are re-read after they do.'],
+ ['Environment health', 'How rarely calls fail on configuration: permissions, blocked or missing commands, hooks and MCP servers.'],
+ ],
+ },
+ pointsOnTable: {
+ title: 'Points on the table',
+ paras: [
+ 'Patterns in your sessions that cost Run health points, each with a fix. A fix only appears when it can name the command, tool or server behind it.',
+ 'Points are what the score would gain if the pattern stopped: the component recomputed without the failures, or with the rate raised to a target. They are estimates; Autotune checks them against what happens next.',
+ ],
+ },
+ autotune: {
+ title: 'Autotune',
+ paras: [
+ 'Once a day agentplay reruns the Run health rules on your last 30 days, writes the fixes it is allowed to, and removes earlier ones that stopped helping.',
+ 'Anything that grants an agent access or runs code (permissions, hooks) waits here for your OK.',
+ ],
+ },
+ scopeFiles: {
+ title: 'The files it can change',
+ paras: ['Agents read these files at the start of each session:'],
+ rows: [
+ ['CLAUDE.local.md', 'Personal instructions, git-ignored. Autotune writes here by default.'],
+ ['CLAUDE.md', 'Shared instructions, committed with the repo. Only when you allow it for that repo.'],
+ ['.claude/settings.local.json', 'Commands the agent may run without asking. Always asks you first.'],
+ ['.claude/settings.json hooks', 'Scripts that run automatically, e.g. tests before the agent stops. Always asks you first.'],
+ ],
+ },
+ managedBlock: {
+ title: 'The managed block',
+ paras: ['agentplay only writes between <!-- agentplay:start --> and <!-- agentplay:end --> markers. Anything outside them is yours and never touched. Each line carries a marker, so Undo removes exactly what was added.'],
+ },
} satisfies Record<string, Term>;
export type TermKey = keyof typeof GLOSSARY;