Unified workbench: a status band for subagents and mmrun reviews, plus a seven-page pane (Overview / Agents / Reviews / GPU / Timeline / Usage / Progress…

Under active development. This repo is updated continuously, and interfaces, names and defaults can change between versions. Star or watch the repo to follow the changes.
Five Claude Code plugins built on mods (function hooks), plus two agent templates.
| Plugin | What it does |
|---|---|
dashboard | A status band above the prompt for running subagents and mmrun reviews, a line under the prompt with context use and the tightest rate-limit window, and a seven-page workbench (Overview / Agents / Reviews / GPU / Timeline / Usage / Progress) opened with /dashboard, /subagents, /mmrun, /gpu, /timeline. The Reviews, GPU and Progress tabs show once they have data: an ~/.claude/mmruns folder, a GPU host, a progress board. The Timeline page draws the main loop's turns as a waterfall of model requests and tool calls, with a hotspot view of the slowest tools and turns. Renders subagent cards, test summaries and blocked-command notices in the transcript. |
harness | Skills: ai-code-cleanup, interrogate, shape-task, verify-change, setup. Guards: refuse subagents on blocked models, refuse git commands that discard uncommitted work in the shared main worktree, refuse tool calls that would print API-key config files (~/.claude.json and its backups, Claude settings, Codex config and auth, grok auth, OpenViking config) or an environment dump (env, printenv, export -p, set, …) into the transcript, run /compact when the main thread idles until the prompt cache is about to expire. |
mm | Cross-model code review and delegation: /mm:review runs codex / grok / agy in parallel as read-only reviewers, /mm:run hands a task to another model in its own worktree. Ships the mmrun CLI. A guard refuses reading mmrun's *.raw event streams (except a lone tail of 50 lines or fewer) and moves a foreground mmrun wait to the background. |
next-prompt | Predicts your next message. After each main-thread turn, one fork of the session's own model (reusing its prompt cache, no tools, nothing written to the transcript) writes the message you are likely to send next; it shows as the prompt box's dim suggestion, Tab to take. A reply of NONE shows nothing. /prediction-stats prints how many were taken or near-taken, the characters kept, the abstentions, the median fork time and the cache share. Hides Claude Code's own suggestion in the terminal; in the desktop app set "promptSuggestionEnabled": false. One fork per turn, billed to your session. |
progress | A per-project progress board. After each turn you typed that changed files or made a commit, the plugin asks Sonnet to record the work as 1–3 nodes (title, summary, status, kind, links to earlier nodes); the main model spends no tokens on it. The board is kept under ~/.claude/progress/ or committed with the project, as you choose once per project. The plugin mirrors the board to an optional Artifact canvas. Works without dashboard; with it, the workbench's Progress page lists the board. |
agents/ | worker and researcher subagent templates to copy into ~/.claude/agents/. |
The status band above the prompt while a worker subagent runs, with the transcript cards for the dispatched agent and the test summary. Context use and the rate-limit window show only in the line under the prompt:

The workbench's Timeline page: each model request of the last turn, its tool calls and the critical path.

Both screenshots come from a real terminal session with language set to English. With zh-CN, the same UI is drawn in Chinese; see 简体中文.
claude -p run the hooks without drawing.harness: python3.mm: at least one of the codex, grok or agy CLIs, plus bash, git, jq, python3. The grok and agy read-only fence uses sandbox-exec, so it is macOS only; codex uses its own sandbox.dashboard GPU page: key-based ssh to the hosts and nvidia-smi (or tegrastats) on them./mm:run suggests the /impeccable skill for frontend tasks, and verify-change suggests the codegraph_impact MCP tool. Neither ships here; they are used when installed, and the plugins work without them.Let Claude do it: paste this into a Claude Code session.
Fetch and follow the instructions in https://raw.githubusercontent.com/Paradox07127/claude-utopia/main/INSTALL.md
Or by hand:
claude plugin marketplace add Paradox07127/claude-utopia
claude plugin install dashboard@claude-utopia
claude plugin install harness@claude-utopia
claude plugin install mm@claude-utopia
claude plugin install next-prompt@claude-utopia
claude plugin install progress@claude-utopia
Then start a new Claude Code session. Run the setup skill (/harness:setup) at any time to review and change the options below.
Set with /plugin configure <plugin>@claude-utopia, or claude plugin configure <plugin>@claude-utopia --values-stdin with a JSON object of strings. Changes take effect in the next session.
| Plugin | Key | Default | Meaning |
|---|---|---|---|
| dashboard | language | auto | UI language: auto, zh-CN or en. auto follows the settings language, then LC_ALL / LANG, else English. |
| dashboard | gpuHosts | empty | Comma-separated ssh hosts; ssh <host> … in Bash opens that host's GPU page. |
| dashboard | cacheTtlMinutes | 60 | The fallback prompt cache TTL: after this many idle minutes the band warns that the next message rewrites the prompt cache. Used only until the real TTL is known; a TTL read from the transcript or reported by a model switch overrides it. |
| dashboard | toastPeerAsks | true | Toast when another Claude Code session asks a permission or its turn fails. Other sessions' toasts show only in the session you typed in last within two minutes, or in every session when you typed in none. |
| dashboard | toastPeerReplies | true | Toast when another session replies after a turn of two minutes or more. Shown by the same rule. |
| dashboard | askSound | false | Play a short chime with the toast of another session asking a permission or failing. Needs toastPeerAsks. |
| dashboard | toastRuns | true | Toast when an mmrun model returns, fails or goes stale. |
| harness | language | auto | Same as above, for the harness toast. |
| harness | blockedSubagentModels | empty | Comma-separated; a subagent whose model name contains any entry is refused. Empty allows all. |
| harness | sharedTreeGitGuard | true | In the main worktree, refuse git commands that discard uncommitted changes or rewrite HEAD: checkout <path>, checkout --force / -f, restore (except --staged alone), stash (except list, show, create), clean (except -n / --dry-run), switch --discard-changes / --force / -f, reset --hard, commit --amend. Linked worktrees are exempt. |
| harness | idleCompact | true | When the main thread sits idle until just before the prompt cache expires, run /compact automatically: with a 1h cache 10 minutes before, at 100k tokens or more; with a 5m cache 1 minute before, at 200k or more. The TTL is read from the transcript. |
| mm | reviewModels | codex,grok | Models /mm:review uses when no --models is given. |
next-prompt and progress have no options.
Skills, command docs and every instruction the plugins send to the model are in English; skill descriptions also carry Chinese trigger words so Chinese prompts match them. Claude replies in your language. Only the drawn UI follows language.
Mods run in-process with your user permissions, like any plugin hook. mm sends the code under review to the external model CLIs you have installed, under their own accounts and terms. Nothing here phones home.
harness hides the built-in general-purpose agent when worker.md or researcher.md exists in ~/.claude/agents/ or the project's .claude/agents/.
hooks/index.ts 11 lines1import type { Register } from 'claude-code'
2
3import { register as registerEvents } from './events-hooks'
4import { register as registerWorkbench } from './register'
5
6// The source tree's entry, as the engine loads one module per plugin; a release ships each half as a plugin of its own.
7export const register: Register = (on, options) => {
8 registerWorkbench(on, options)
9 registerEvents(on, options)
10}
11hooks/events-hooks.ts 179 lines1import type { EngineInterface, HookFailure, Register } from 'claude-code'
2
3import type { AgentRun, MmSnapshot } from '../types'
4import { agentEvents, bashText, capped, eventLine, eventsDir, eventsPath, gateEvent, runEvents, serially, staleDays } from './events'
5import type { LedgerEvent } from './events'
6import { failureLine } from './failures'
7import { summarizeTests } from './summarize-tests'
8import { dayOf, projectKey } from './usage'
9
10// The event ledger's writer: each session rewrites only its own <project>/<day>/<session>.jsonl, whole, on one chain.
11
12// The lines of the file last written; null until the first write of this load.
13let kept: { path: string; lines: string[] } | null = null
14const onChain = serially()
15
16/** The repository's main worktree root, so a linked worktree's session shares its project; else the session root. */
17async function ledgerRoot($: EngineInterface): Promise<string> {
18 return (await $.session.repo().catch(() => null))?.root ?? (await $.session.root())
19}
20
21/** Adds `events` to this session's file of today. The ledger only watches: its failure is never the event's. */
22async function emit($: EngineInterface, events: readonly LedgerEvent[]): Promise<void> {
23 if (events.length === 0) {
24 return
25 }
26
27 try {
28 const at = await $.clock.now()
29 const session = await $.session.id()
30 const path = eventsPath((await $.env.get('HOME')) ?? '', projectKey(await ledgerRoot($)), dayOf(at), session)
31 const added = events.map(one => eventLine(at, session, one))
32
33 await onChain(async () => {
34 // After a reload, or into another file, what the file holds already comes first.
35 // Only a missing file reads as empty: one that exists but will not read throws, so it is never written over.
36 const lines = kept?.path === path ? kept.lines : (await $.fs.exists(path)) ? String(await $.fs.read(path)).split('\n').filter(line => line !== '') : []
37
38 // Kept before the write: a write that fails is made again by the next.
39 kept = { path, lines: capped([...lines, ...added]) }
40 await $.fs.write(path, `${kept.lines.join('\n')}\n`)
41 })
42 } catch {
43 // Dropped: a missing line beats a broken event.
44 }
45}
46
47/** Removes the project's date directories past the retention. */
48async function prune($: EngineInterface): Promise<void> {
49 const dir = eventsDir((await $.env.get('HOME')) ?? '', projectKey(await ledgerRoot($)))
50 const names = (await $.fs.list(dir).catch(() => [])).filter(entry => entry.kind === 'dir').map(entry => entry.name)
51
52 for (const name of staleDays(names, await $.clock.now())) {
53 await $.process.run(['rm', '-rf', `${dir}/${name}`], { timeoutMs: 10_000 }).catch(() => null)
54 }
55}
56
57/** A Bash call's test run, if it was one. */
58async function noteGate($: EngineInterface, input: unknown, text: string | null, isFailure: boolean): Promise<void> {
59 const command = typeof input === 'object' && input !== null ? (input as { command?: unknown }).command : undefined
60 const summary = text === null ? null : summarizeTests(text)
61
62 if (typeof command === 'string' && summary !== null) {
63 await emit($, [gateEvent(command, summary, isFailure)])
64 }
65}
66
67/** A hook's `.catch`: its failure to the debug log, once per hook this load. Declared per file: validate follows $ into this file's functions only. */
68function hookFailed($: EngineInterface, name: string, error: HookFailure): void {
69 const line = failureLine(name, error)
70
71 if (line !== undefined) {
72 $.ui.log(line, { to: 'debug' })
73 }
74}
75
76export const register: Register = on => {
77 // Every hook below has a matcher: another module holds the matcher-less one on each of these events, and the engine refuses a second.
78 on('session.start', { isInteractive: [true, false] }, async ($, e, next) => {
79 await emit($, [{ name: 'session.start', severity: 'INFO', attributes: {} }])
80 // Not awaited: removing old days must not hold the session's start.
81 void prune($).catch(() => undefined)
82
83 return next(e)
84 }).catch(($, e, next) => {
85 hookFailed($, 'session.start (events)', next.error)
86
87 return next(e)
88 })
89
90 // Written before the process may exit.
91 on('session.end', { reason: /^/ }, async ($, e, next) => {
92 await emit($, [{ name: 'session.end', severity: 'INFO', attributes: { reason: e.reason } }])
93
94 return next(e)
95 }).catch(($, e, next) => {
96 hookFailed($, 'session.end (events)', next.error)
97
98 return next(e)
99 })
100
101 // Classic, never `tool.call`: a mod hooking Bash there denies every Bash call of a worktree subagent (claude-code#92533).
102 on('classic.PostToolUse', { tool_name: /^Bash$/ }, async ($, e, next) => {
103 await noteGate($, e.tool_input, bashText(e.tool_response), false)
104
105 return next(e)
106 }).catch(($, e, next) => {
107 hookFailed($, 'classic.PostToolUse Bash (events)', next.error)
108
109 return next(e)
110 })
111
112 // A nonzero exit, a failing test run among them, ends here instead of PostToolUse.
113 on('classic.PostToolUseFailure', { tool_name: /^Bash$/ }, async ($, e, next) => {
114 await noteGate($, e.tool_input, e.error, true)
115
116 return next(e)
117 }).catch(($, e, next) => {
118 hookFailed($, 'classic.PostToolUseFailure Bash (events)', next.error)
119
120 return next(e)
121 })
122
123 // A precompute installs nothing and a skip leaves the transcript: neither is a compaction.
124 on('session.compact', { trigger: /^(?:manual|auto|plugin)$/ }, async ($, e, next) => {
125 const r = await next(e)
126
127 if (r.skip === undefined) {
128 const attributes = { trigger: e.trigger, tokens_before: r.tokensBefore ?? null, tokens_after: r.tokensAfter ?? null, ...(e.agentId !== undefined && { 'agent.id': e.agentId }) }
129
130 await emit($, [{ name: 'session.compact', severity: 'INFO', attributes }])
131 }
132
133 return r
134 }).catch(($, e, next) => {
135 hookFailed($, 'session.compact (events)', next.error)
136
137 return next(e)
138 })
139
140 // The workbench's own record of the agents: an end its list found (a killed agent has no turn.complete) counts as one too.
141 on('state.set', { plugin: 'dashboard', key: 'agents' }, async ($, e, next) => {
142 const r = await next(e)
143
144 if (r.value?.isSet === true) {
145 const before = (e.previous as { value?: AgentRun[] } | undefined)?.value ?? []
146 const after = (e.value as { value?: AgentRun[] } | undefined)?.value ?? []
147
148 await emit($, agentEvents(before, after))
149 }
150
151 return r
152 }).catch(($, e, next) => {
153 hookFailed($, 'state.set agents (events)', next.error)
154
155 return next(e)
156 })
157
158 // The mmrun runs the workbench polls, those of this project alone: ~/.claude/mmruns holds every project's.
159 on('state.set', { plugin: 'dashboard', key: 'runs' }, async ($, e, next) => {
160 const r = await next(e)
161
162 if (r.value?.isSet === true) {
163 const before = (e.previous as { value?: MmSnapshot | null } | undefined)?.value ?? null
164 const after = (e.value as { value?: MmSnapshot | null } | undefined)?.value ?? null
165 const root = await ledgerRoot($).catch(() => null)
166
167 if (root !== null) {
168 await emit($, runEvents(before, after, run => run.workdir === root || run.workdir.startsWith(`${root}/`)))
169 }
170 }
171
172 return r
173 }).catch(($, e, next) => {
174 hookFailed($, 'state.set runs (events)', next.error)
175
176 return next(e)
177 })
178}
179hooks/register.tsx 3873 lines1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, HookFailure, HookStream, ProcessSpawnChunk, ProcessSpawnResult, Register, RenderChildren, RenderSurface, Timer } from 'claude-code'
3
4import type {
5 AgentPeek,
6 AgentRun,
7 BoardEvent,
8 BoardRead,
9 BoardRequest,
10 DashCache,
11 DashConversation,
12 DashDetail,
13 DashPage,
14 DashReport,
15 DashSeen,
16 DashTimelinePage,
17 DashTimelineView,
18 DashUsage,
19 GateRun,
20 GpuSample,
21 GpuWatch,
22 GuardLog,
23 MmModel,
24 MmRun,
25 MmSnapshot,
26 RequestFields,
27 SessionPresence,
28 SessionPresenceState,
29 TimelineTurn,
30 UsageLedger,
31 UsageRead,
32 WorktreeInfo,
33} from '../types'
34import { elapsedOf, fit, fmtAge, fmtDuration, fmtTokens, MAX_AGENTS, noteDenied, noteDone, noteListed, noteResumed, noteSpawn, noteTool, peekOf, toolLabel, widthOf } from './agent-model'
35import { registerAskRecommended } from './ask-recommended'
36import {
37 agentFold,
38 agentTable,
39 alignRight,
40 bandLines,
41 boardOf,
42 CACHE_GROUP,
43 endedText,
44 fitLine,
45 flightText,
46 foldText,
47 FRESH_MS,
48 GATE_COMMAND_COLUMNS,
49 gateCounts,
50 HOTKEY_COLUMNS,
51 idleLine,
52 isFailedGate,
53 isStalled,
54 limitText,
55 MAX_BAND_ROWS,
56 nextBandChange,
57 nextOverviewChange,
58 OVERVIEW_GATES,
59 OVERVIEW_TREES,
60 overviewCounts,
61 overviewOf,
62 padTo,
63 peerToasts,
64 pendingGateLine,
65 pendingLine,
66 progressLines,
67 recentGates,
68 runningLine,
69 runTable,
70 sessionLine,
71 splitRow,
72 usageLines,
73 usageText,
74} from './board'
75import type { Board, ButtonRow, ColdCache, Line, OverviewItem, Seg } from './board'
76import { drawDesktopBand, drawDesktopPane, drawDesktopPaneError, posixQuote } from './desktop'
77import type { GpuFill } from './desktop/gpu'
78import type { TimelinePaneData } from './desktop/timeline'
79import type { BandRow } from './desktop/band'
80import { gauge } from './desktop/kit'
81import type { El } from './desktop/kit'
82import { scaleOf, TONE_KEYS } from './desktop-svg'
83import type { Tone } from './desktop-svg'
84import { attentionChime } from './chime'
85import { CI_GROUP, CI_POLL_MS, CI_RETRY_MS, ciEvents, ciLine, isNoAuth, isNoPr, isNotFound, nextCi, parseChecks, parsePr, PR_CHECKS, PR_VIEW } from './ci'
86import type { CiStatus } from './ci'
87import { conversationOf } from './conversation'
88import { capped, eventLine, eventsDir as eventLedgerDir, groupEvents, parseLedger, serially, sessionOfFile } from './events'
89import type { EventsRead, LedgerEvent, LedgerRecord } from './events'
90import { failureLine, isFirstTime } from './failures'
91import { bar, hostsOf, isHostName, sshArgv, sshHostOf, takeSamples } from './gpu-probe'
92import { pickLang, setLang, t } from './i18n'
93import type { Lang } from './i18n'
94import { isExpired, mainMoved, newestNotice, NOTICE_TTL_MS, noticeOf, NOTICES_MS, noticesDir, noticeText, parseNotice, shaOf } from './notices'
95import type { Notice } from './notices'
96import { boardDir, canvasBatches, canvasPath, canvasProject, canvasWrites, closeEvents, eventsDir, foldBoard, foldLines, foldRequests, NO_CHECKS, parseBoardEvents, parseStorage } from './progress'
97import type { BoardStorage } from './progress'
98import { onRecording } from './progress-hooks'
99import { endToast, parseKv, reportOf, reviewOf, runLabel, RUNID } from './runs'
100import { SHAPE } from './shapes'
101import { summarizeTests } from './summarize-tests'
102import { applyEvents, runSession } from './tasks'
103import { toolsInFlight } from './timeline'
104import type { Flight } from './timeline'
105import { registerTimeline } from './timeline-hooks'
106import { eventLines, EVENTS_VIEW, hotspotLines, latestMainTurnId, timelineLines } from './timeline-view'
107import { bashText, registerTranscript } from './transcript'
108import { dayOf, daySum, daysOf, emptyDay, lastDays, ledgerDir, parseUsageDay, projectKey, weekOf } from './usage'
109import type { UsageWeek } from './usage'
110import { GUARD_COLORS, guardText, parseGuards, parseWorktrees, treeMarks, treeOf } from './workspace'
111import type { Mark, PorcelainTree } from './workspace'
112
113const PANE_ID = 'dashboard'
114const pages = () =>
115 [
116 { page: 'overview', label: t().pageOverview },
117 { page: 'agents', label: 'Agents' },
118 { page: 'mmrun', label: t().pageMmrun },
119 { page: 'gpu', label: 'GPU' },
120 { page: 'timeline', label: t().pageTimeline },
121 { page: 'usage', label: t().pageUsage },
122 { page: 'progress', label: t().pageProgress },
123 ] as const
124// Tabs drawn only while their data exists (tabsWithData), or while their page is open.
125const ON_DEMAND: readonly DashPage[] = ['mmrun', 'gpu', 'progress']
126// The progress page reads the board again this often while it is the current page: recordings land there from any session.
127const PROGRESS_READ_MS = 5_000
128// Each only opens a page or posts a notice, so each runs mid-turn instead of waiting for the turn to end.
129const COMMANDS = [
130 { name: 'dashboard', description: 'Open the workbench on its last page: subagents, reviews, GPU', immediate: true },
131 // Not `agents`: the engine refuses a built-in's name, and /agents is one.
132 { name: 'subagents', description: "Open the workbench's Agents page: this session's subagents", immediate: true },
133 { name: 'mmrun', description: "Open the workbench's Reviews page: recent mmrun runs and their status", immediate: true },
134 { name: 'gpu', description: "Open the workbench's GPU page to watch an ssh host's GPUs", argumentHint: '<host>', immediate: true },
135 { name: 'timeline', description: "Open the workbench's Timeline page: the main loop's turns as a waterfall of requests and tools", immediate: true },
136 { name: 'progress', description: "Open the workbench's Progress page: this project's progress board", immediate: true },
137 { name: 'notice', description: 'Post a notice to every session of this repository; /notice clear hides the current ones in this session', argumentHint: '<text> | clear', immediate: true },
138] as const
139const OPEN_PROGRESS = {
140 name: 'open_progress',
141 description:
142 "Open the workbench's Progress page (this project's progress board) for the person, and show a button in the transcript that opens it again. Call it when the person asks to see progress or the board.",
143 inputSchema: { type: 'object', properties: {} },
144}
145const OPEN_PROGRESS_TOOL = 'mcp__dashboard__open_progress'
146// The GPU ssh sends a pass this often (gpu-probe.ts); a dropped one is retried after it, doubling up to GPU_RETRY_MAX_MS.
147const GPU_POLL_MS = 3000
148const GPU_RETRY_MAX_MS = 60_000
149const DAY_MS = 86_400_000
150// cmd_status in plugins/mm/bin/mmrun gives a RUNNING model without a pid file this long before calling it STALE.
151const PID_GRACE_MS = 30_000
152// Every 3 s while a model runs; with none running, a 15 s cadence is enough to notice a new run.
153const RUNS_BUSY_MS = 3000
154const RUNS_IDLE_MS = 15_000
155const MAX_RUNS = 20
156const MODEL_NAME = /^[A-Za-z0-9_-]+$/
157const PANE_RUNS = 10
158// "[ <label> ]" plus the space before it.
159const buttonColumns = () => widthOf(t().workbench) + 5
160const copyColumns = () => widthOf(t().copyResume) + 5
161const cdColumns = () => widthOf(t().copyCd) + 5
162// Band running rows: the title at most this wide and not cut below the least, the step label at most this wide, the text bar this many cells.
163const BAND_TITLE_COLUMNS = 24
164const BAND_MIN_TITLE_COLUMNS = 8
165const BAND_STEP_COLUMNS = 16
166const BAND_BAR_CELLS = 10
167// A session asking a permission as a card on the terminal: its frame, head, two kv rows and buttons.
168const ASK_CARD_ROWS = 6
169// Below this many columns SessionMode draws each window's ring and percent without its label.
170const MODE_LABEL_COLUMNS = 90
171const MODE_RING_PX = 18
172const WINDOW_NAMES: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
173// Below this many columns a GPU row draws its utilization without the bar.
174const GPU_BAR_COLUMNS = 64
175const MAX_GATES = 30
176const GATE_COMMAND_CHARS = 120
177const WORKTREE_DIR = /\/\.claude\/worktrees\/([^/\s'"]+)/
178const CD_DIR = /\bcd\s+(?:'([^']*)'|"([^"]*)"|(\S+))\s*&&/
179const WORKSPACE_MS = 15_000
180const GIT_TIMEOUT_MS = 10_000
181// The overview lists this many of guard.jsonl's newest blocks, from at most its last 64 KB.
182const GUARD_ROWS = 5
183const GUARD_TAIL_BYTES = 65_536
184const GIT_CHANGE = /\bgit (merge|worktree|commit|checkout|switch|rebase)\b/
185// A Bash call of this session that may move main: the new sha is its own, no notice.
186const MAIN_CHANGE = /\bgit\b[^|;&]*\b(merge|commit|rebase|pull|cherry-pick|reset)\b/
187// A Bash call that writes files is not seen: only these tools' successes make a tree's gates stale.
188const EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
189const PEERS_MS = 5000
190const HEARTBEAT_MS = 30_000
191// While a running agent is quiet, how often `$.agent.list()` is asked whether it ended unreported.
192const AGENT_LIST_MS = 15_000
193// Three missed heartbeats: the session is taken as closed.
194const PEER_SILENT_MS = 90_000
195const DETAIL_CHARS = 40
196const PROMPT_TITLE_COLUMNS = 40
197const REPLY_COLUMNS = 60
198const PRESENCE_STATES: SessionPresenceState[] = ['working', 'permission', 'replied', 'failed', 'idle', 'ended']
199const MINUTE_MS = 60_000
200// Typing rewrites the presence file at most this often; the heartbeat carries a later key between.
201const INPUT_WRITE_MS = 15_000
202// A session typed in within this long counts as the one the person is at.
203const INPUT_RECENT_MS = 2 * MINUTE_MS
204const CACHE_TTL_MS = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS } as const
205// The last main-thread reply sits within this tail; $.fs.read refuses files over 4 MiB and transcripts grow past that.
206const TRANSCRIPT_TAIL_BYTES = 256 * 1024
207// The newest task_progress lines: each stays under 1 KB, its tool name cut to 80 characters and its summary to 200.
208const EVENTS_TAIL_BYTES = 4096
209const MARK_STYLES: Record<Mark['tone'], Omit<Seg, 'text'>> = {
210 stale: { color: 'warning' },
211 done: { color: 'success' },
212 failed: { color: 'error' },
213 running: { color: 'permission' },
214 plain: {},
215 dim: { dim: true },
216}
217
218const agents = atom({ plugin: 'dashboard', key: 'agents' } as const, [] as AgentRun[], { shape: SHAPE })
219const gpu = atom({ plugin: 'dashboard', key: 'gpu' } as const, null as GpuWatch | null, { shape: SHAPE })
220const runs = atom({ plugin: 'dashboard', key: 'runs' } as const, null as MmSnapshot | null, { shape: SHAPE })
221const page = atom({ plugin: 'dashboard', key: 'page' } as const, null as DashPage | null)
222const seen = atom({ plugin: 'dashboard', key: 'seen' } as const, { agents: 0, runs: 0 } as DashSeen, { shape: SHAPE })
223const noAutoOpen = atom({ plugin: 'dashboard', key: 'noAutoOpen' } as const, false)
224const detail = atom({ plugin: 'dashboard', key: 'detail' } as const, null as DashDetail | null, { shape: SHAPE })
225const reports = atom({ plugin: 'dashboard', key: 'reports' } as const, {} as Record<string, DashReport>, { shape: SHAPE })
226const conversation = atom({ plugin: 'dashboard', key: 'conversation' } as const, null as DashConversation | null, { shape: SHAPE })
227const gates = atom({ plugin: 'dashboard', key: 'gates' } as const, [] as GateRun[], { shape: SHAPE })
228const trees = atom({ plugin: 'dashboard', key: 'trees' } as const, null as WorktreeInfo[] | null, { shape: SHAPE })
229const guards = atom({ plugin: 'dashboard', key: 'guards' } as const, null as GuardLog | null, { shape: SHAPE })
230const peers = atom({ plugin: 'dashboard', key: 'peers' } as const, null as SessionPresence[] | null, { shape: SHAPE })
231const toasted = atom({ plugin: 'dashboard', key: 'toasted' } as const, [] as string[], { shape: SHAPE })
232const ownPresence = atom({ plugin: 'dashboard', key: 'presence' } as const, null as SessionPresence | null, { shape: SHAPE })
233const cache = atom({ plugin: 'dashboard', key: 'cache' } as const, { lastReplyAt: null, resumeTokens: null, ttlMs: null } as DashCache, { shape: SHAPE })
234const measured = atom({ plugin: 'dashboard', key: 'usage' } as const, { context: null, rateLimits: [], cost: null } as DashUsage, { shape: SHAPE })
235const timeline = atom({ plugin: 'dashboard', key: 'timeline' } as const, [] as TimelineTurn[], { shape: SHAPE })
236const timelineTurn = atom({ plugin: 'dashboard', key: 'timelineTurn' } as const, null as string | null)
237const timelineView = atom({ plugin: 'dashboard', key: 'timelineView' } as const, 'turn' as DashTimelineView)
238const timelinePage = atom({ plugin: 'dashboard', key: 'timelinePage' } as const, null as DashTimelinePage | null, { shape: SHAPE })
239const tick = atom({ plugin: 'dashboard', key: 'tick' } as const, 0)
240const paneWake = atom({ plugin: 'dashboard', key: 'paneWake' } as const, 0)
241const peek = atom({ plugin: 'dashboard', key: 'peek' } as const, null as AgentPeek | null, { shape: SHAPE })
242const agentsFoldOpen = atom({ plugin: 'dashboard', key: 'agentsFoldOpen' } as const, false)
243const runsFoldOpen = atom({ plugin: 'dashboard', key: 'runsFoldOpen' } as const, false)
244const agentsSeenBefore = atom({ plugin: 'dashboard', key: 'agentsSeenBefore' } as const, 0)
245const ledger = atom({ plugin: 'dashboard', key: 'ledger' } as const, null as UsageLedger | null, { shape: SHAPE })
246const usageRead = atom({ plugin: 'dashboard', key: 'usageRead' } as const, null as UsageRead | null, { shape: SHAPE })
247const progress = atom({ plugin: 'dashboard', key: 'progress' } as const, null as BoardRead | null, { shape: SHAPE })
248const SHAPED_KEYS = new Set([agents, gpu, runs, seen, detail, reports, conversation, gates, trees, guards, peers, toasted, ownPresence, cache, measured, timeline, timelinePage, peek, ledger, usageRead, progress].map(one => one.ref.key))
249
250// Module timers die with the module on reload; session.start, or the first band drawing of a reload that raised none, restarts them.
251let ticker: Timer | null = null
252let progressReadAt = 0
253// The loops of an interactive session are running; started once per module.
254let isStarted = false
255// session.start's isInteractive: a -p or SDK session writes no presence file.
256let isInteractive = true
257// When `$.agent.list()` was last asked; 0 before the first time.
258let agentsListedAt = 0
259let runsPoll: Poll | null = null
260// The GPU page's ssh while one is wanted.
261let gpuLink: GpuLink | null = null
262// When the runs were last polled; the snapshot's polledAt lags it while an unchanged poll is not written.
263let runsPolledAt = 0
264// mm wrote its watches since the runs were last read: the next poll reads them past the idle wait.
265let isRunsAsked = false
266let isCollecting = false
267// What this session last wrote to its own presence file; null before the first write.
268let presence: SessionPresence | null = null
269// The subagent whose ask put the presence in `permission`; undefined for the main thread.
270let askedBy: string | undefined
271// What the main thread's last Stop said of background work in flight; the main turn.complete reads and clears it.
272let isAwaitingTasks = false
273// What the main turn.complete wrote for a turn ended by Esc or a failure, which a later Stop leaves; prompt.submit clears it.
274let turnEnd: 'idle' | 'failed' | undefined
275// The first line of the main thread's last Stop message, the detail of `replied`; prompt.submit clears it.
276let replyLine: string | undefined
277// Other sessions' files as last read, by file name: a file whose mtime did not move is not read again.
278let peerFiles = new Map<string, { mtimeMs: number; peer: SessionPresence | null }>()
279// The results the person marked read on the band (resultKey), the last MAX_AGENTS.
280let bandDismissed: string[] = []
281// A clock Client failed: the workbench draws its times as static text from then on.
282let isClockFailed = false
283// The last band drawing's viewport.isFullscreen: whether a pane opened unasked docks beside the transcript.
284let docksPanes: boolean | undefined
285let sessionTitle: string | undefined
286// The cacheTtlMinutes option; the TTL in `cache`, from the transcript or a PostModelSwitch, overrides it.
287let optionTtlMs = 60 * MINUTE_MS
288// A resume the engine judged prompt_cache_likely_expired: cold whatever the TTL, until the next main reply or a /clear.
289let isResumeExpired = false
290// Fires when the cache turns cold, then each minute while it stays cold.
291let coldTimer: Timer | null = null
292let coldMinute: Timer | null = null
293// Fires when a pending gate on the band expires or a limit countdown turns a minute: neither keeps the ticker going.
294let bandWake: Timer | null = null
295let bandWakeAt: number | null = null
296// Fires when the overview next changes with time alone (nextOverviewChange): it reads no tick, its times moving by themselves.
297let overviewWake: Timer | null = null
298let overviewWakeAt: number | null = null
299// When the person last typed or sent a prompt in this session; undefined before the first.
300let inputAt: number | undefined
301// What `$.ui.status` was last set to.
302let statusText: string | undefined
303// The askSound and toast* options.
304let toastOptions = { askSound: false, peerAsks: true, peerReplies: true, runs: true }
305// Whether the gpuHosts option names a host.
306let hasGpuHosts = false
307// The on-demand tabs whose data existed when the workbench last opened; null before the first check this load.
308let shownTabs: ReadonlySet<DashPage> | null = null
309// The progress page's re-read of the board; null while another page is current or the pane is closed.
310let progressRead: Timer | null = null
311// The branch PR's checks as last polled; null without a PR that has checks.
312let ciStatus: CiStatus | null = null
313// `gh` missing or not logged in: no `gh` is run before this time.
314let ghBlockedUntil = 0
315// The lines of this session's CI file last written; null until the first write of this load.
316let ciKept: { path: string; lines: string[] } | null = null
317const ciChain = serially()
318// The events view's last read of each ledger file of the day: one whose size and mtime did not change is not read again.
319let ledgerFiles = new Map<string, { size: number; mtimeMs: number; records: LedgerRecord[] }>()
320// The repository's notice files, this session's main-advanced notice, main's sha last read and the root it was read in, and when /notice clear ran.
321let noticeBoard: { list: Notice[]; auto: Notice | null; mainSha: string | null; mainRoot: string | null; clearedAt: number } = { list: [], auto: null, mainSha: null, mainRoot: null, clearedAt: 0 }
322// The notice files as last read, by file name: a name read as a notice is not read again.
323let noticeFiles = new Map<string, Notice | null>()
324// Runs whose report the Reviews list is reading for its legend.
325const listLoads = new Set<string>()
326
327// Ephemeral desktop command disclosure states: which command boxes are open.
328export const openDisclosures = new Set<string>()
329
330export function toggleDisclosure($: EngineInterface, key: string): void {
331 if (openDisclosures.has(key)) {
332 openDisclosures.delete(key)
333 } else {
334 openDisclosures.add(key)
335 }
336 void update($, paneWake, was => was + 1)
337}
338
339// Lives here, not in i18n.ts: validate only follows $ into functions declared in the same file.
340async function resolveLang($: EngineInterface, option: unknown): Promise<Lang> {
341 const settings = await $.settings.read()
342 return pickLang(option, settings.language, (await $.env.get('LC_ALL')) || (await $.env.get('LANG')))
343}
344
345/** A loop `poll` started: `now()` runs it at once, or once more as a run in flight ends; `cancel()` arms no further run. */
346export type Poll = { now: () => Promise<void>; cancel: () => void }
347
348/**
349 * Runs `fn` `ms` after the last run ended, one run at a time.
350 * A run that throws goes to the debug log; what it last wrote stands.
351 */
352export function poll($: EngineInterface, name: string, ms: number, fn: () => Promise<void>): Poll {
353 let isPolling = false
354 let isCancelled = false
355 // A now() that came while a run was in flight: the run that ended may have read too early.
356 let isAsked = false
357 let timer: Timer | null = null
358 const run = async () => {
359 if (isPolling) {
360 return
361 }
362
363 isPolling = true
364
365 try {
366 do {
367 isAsked = false
368
369 try {
370 await fn()
371 } catch (error) {
372 $.ui.log(`dashboard: the ${name} poll failed: ${errorText(error)}`, { to: 'debug' })
373 }
374 } while (isAsked && !isCancelled)
375 } finally {
376 isPolling = false
377 }
378 }
379 const arm = () => {
380 timer = $.clock.after(ms, () => {
381 void run()
382 .then(() => {
383 if (!isCancelled) {
384 arm()
385 }
386 })
387 .catch(() => undefined)
388 })
389 }
390
391 arm()
392
393 return {
394 now: () => {
395 isAsked = true
396
397 return run()
398 },
399 cancel: () => {
400 isCancelled = true
401 timer?.cancel()
402 },
403 }
404}
405
406/** The main thread idle past the TTL since its last request; null while it works. */
407async function coldNow($: EngineInterface, now: number): Promise<ColdCache | null> {
408 const { lastReplyAt, resumeTokens, ttlMs } = await read($, cache)
409 const isWorking = presence?.state === 'working' || presence?.state === 'permission'
410
411 if (lastReplyAt === null || isWorking || (!isResumeExpired && now - lastReplyAt < (ttlMs ?? optionTtlMs))) {
412 return null
413 }
414
415 return { idleMs: now - lastReplyAt, tokens: (await read($, measured)).context?.tokens ?? resumeTokens ?? null }
416}
417
418function stopCold(): void {
419 coldTimer?.cancel()
420 coldTimer = null
421 coldMinute?.cancel()
422 coldMinute = null
423}
424
425function stopBandWake(): void {
426 bandWake?.cancel()
427 bandWake = null
428 bandWakeAt = null
429}
430
431/** Sets the band's one wake timer for `at`, unless it is set for that time already; none for null. */
432function armBandWake($: EngineInterface, at: number | null, now: number): void {
433 if (at === bandWakeAt) {
434 return
435 }
436
437 stopBandWake()
438
439 if (at !== null) {
440 bandWakeAt = at
441 bandWake = $.clock.after(at - now, () => {
442 bandWake = null
443 bandWakeAt = null
444 void redraw($)
445 })
446 }
447}
448
449function armOverviewWake($: EngineInterface, at: number | null, now: number): void {
450 if (at === overviewWakeAt) {
451 return
452 }
453
454 overviewWake?.cancel()
455 overviewWake = null
456 overviewWakeAt = at
457
458 if (at !== null) {
459 overviewWake = $.clock.after(Math.max(0, at - now), () => {
460 overviewWake = null
461 overviewWakeAt = null
462 void update($, paneWake, was => was + 1)
463 })
464 }
465}
466
467/** Redraws the band, the prompt hint and the workbench, which read `tick`; a transcript row does not, so it is left alone. */
468async function redraw($: EngineInterface): Promise<void> {
469 const now = await $.clock.now()
470
471 await update($, tick, () => now)
472 await syncStatus($)
473}
474
475/** While the workbench is not on screen, the status line counts running subagents and the sessions, this one too, asking or failed; set only on a change. */
476async function syncStatus($: EngineInterface): Promise<void> {
477 const isShown = (await $.ui.panes()).find(one => one.id === PANE_ID)?.isShown === true
478 const running = (await read($, agents)).filter(one => one.state === 'running').length
479 const isWaiting = (one: SessionPresence | null) => one?.state === 'permission' || one?.state === 'failed'
480 const waiting = ((await read($, peers)) ?? []).filter(isWaiting).length + (isWaiting(presence) ? 1 : 0)
481 const parts = [running > 0 ? t().statusRunning(running) : '', waiting > 0 ? t().statusWaiting(waiting) : ''].filter(part => part !== '')
482 const text = isShown || parts.length === 0 ? undefined : parts.join(' · ')
483
484 if (text !== statusText) {
485 statusText = text
486 $.ui.status(text)
487 }
488}
489
490/** Redraws the band; keeps a minute timer for the idle time while the cache is cold, drops it once not. */
491async function tickCold($: EngineInterface): Promise<void> {
492 await redraw($)
493
494 if ((await coldNow($, await $.clock.now())) === null) {
495 stopCold()
496 } else {
497 coldMinute ??= $.clock.every(MINUTE_MS, () => void tickCold($))
498 }
499}
500
501/** Sets the timer for the moment the cache turns cold, from the last request and the TTL. */
502async function armCold($: EngineInterface): Promise<void> {
503 stopCold()
504
505 const { lastReplyAt, ttlMs } = await read($, cache)
506
507 if (lastReplyAt === null) {
508 return
509 }
510
511 const left = lastReplyAt + (ttlMs ?? optionTtlMs) - (await $.clock.now())
512
513 if (left > 0 && !isResumeExpired) {
514 coldTimer = $.clock.after(left, () => void tickCold($))
515 } else {
516 await tickCold($)
517 }
518}
519
520type TranscriptLine = {
521 type?: string
522 isSidechain?: boolean
523 message?: { usage?: { cache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number } } }
524}
525
526/** The TTL the last main-thread reply of a transcript tail wrote the cache at; null when the tail holds none. */
527function transcriptTtl(tail: string): keyof typeof CACHE_TTL_MS | null {
528 for (const text of tail.split('\n').reverse()) {
529 let line: TranscriptLine | null
530
531 try {
532 line = JSON.parse(text) as TranscriptLine | null
533 } catch {
534 // A `tail -c` read's first line is usually cut, its last may still be being written.
535 continue
536 }
537
538 const written = line?.type === 'assistant' && line.isSidechain !== true ? line.message?.usage?.cache_creation : undefined
539
540 if ((written?.ephemeral_1h_input_tokens ?? 0) > 0) {
541 return '1h'
542 }
543
544 if ((written?.ephemeral_5m_input_tokens ?? 0) > 0) {
545 return '5m'
546 }
547 }
548
549 return null
550}
551
552/** When the main turn `turnId` sent its last request; undefined when the timeline kept none. */
553function lastSentAt(turns: readonly TimelineTurn[], turnId: string): number | undefined {
554 return turns.find(one => one.turnId === turnId && one.agentId === undefined)?.steps.at(-1)?.sentAt
555}
556
557/** The subagents' calls still running; none when the timeline cannot be read, so its failure stays on the timeline page. */
558async function flightsNow($: EngineInterface): Promise<Map<string, Flight>> {
559 return read($, timeline).then(toolsInFlight, () => new Map<string, Flight>())
560}
561
562/** The board of the band; a result the person marked read on it counts neither on the band nor as unread. */
563async function boardNow($: EngineInterface) {
564 const now = await $.clock.now()
565 const marked = await read($, seen)
566 const board = boardOf(
567 (await read($, agents)).filter(one => one.state === 'running' || !bandDismissed.includes(resultKey(one))),
568 await read($, runs),
569 marked,
570 now,
571 await read($, gates),
572 (await read($, peers)) ?? [],
573 await coldNow($, now),
574 await flightsNow($),
575 await read($, trees),
576 )
577 return ciStatus === null ? board : withCi(board, ciStatus, marked.ci ?? 0)
578}
579
580/** The board with the CI row: a failure at P1, running checks at P3, a pass at P2 for FRESH_MS and unread until the workbench is opened after it. */
581function withCi(board: Board, status: CiStatus, seenAt: number): Board {
582 const tier = status.outcome === 'fail' ? 1 : status.outcome === 'pending' ? 3 : board.now - status.changedAt < FRESH_MS ? 2 : null
583 const counts = { ...board.counts }
584
585 if (status.outcome === 'fail') {
586 counts.pending += 1
587 } else if (status.outcome === 'pending') {
588 counts.running += 1
589 } else if (status.changedAt > seenAt) {
590 counts.unread += 1
591 }
592
593 if (tier === null) {
594 return { ...board, counts }
595 }
596
597 const line = ciLine(status, board.now)
598 const entry: BandEntry = { tier, startedAt: status.changedAt, group: CI_GROUP, full: line, compact: line, counts: { 1: tier === 1 ? 1 : 0, 2: tier === 2 ? 1 : 0, 3: tier === 3 ? 1 : 0, aborted: 0, failed: 0 } }
599 // The cold cache stays last, as boardOf puts it.
600 const work = [...board.entries.filter(one => one.group !== CACHE_GROUP), entry].sort((a, b) => a.tier - b.tier || a.startedAt - b.startedAt)
601
602 return { ...board, counts, entries: [...work, ...board.entries.filter(one => one.group === CACHE_GROUP)] }
603}
604
605/** The main-loop turn the timeline page shows: the one picked while it is still kept, else the latest. */
606function shownTurnId(turns: readonly TimelineTurn[], picked: string | null): string | undefined {
607 return turns.some(one => one.turnId === picked && one.agentId === undefined) ? (picked ?? undefined) : latestMainTurnId(turns)
608}
609
610/** The band's idle line: the last item that ended and the last gate. */
611async function idleNow($: EngineInterface): Promise<Line> {
612 const now = await $.clock.now()
613 const all = await read($, gates)
614 const recent = overviewOf(await read($, agents), await read($, runs), await read($, seen), now, (await read($, peers)) ?? [], all).recent[0]
615
616 return idleLine(recent, all.at(-1), now)
617}
618
619type BandEntry = Board['entries'][number]
620type RunningRow = Extract<BandRow, { kind: 'running' }>
621type AskRow = Extract<BandRow, { kind: 'ask' }>
622type NoticeRow = Extract<BandRow, { kind: 'notice' }>
623type PlanRow = Extract<BandRow, { kind: 'plan' }>
624
625/** The entries bandLines draws one per line, in its order: all of them when they fit whole, else the failures it keeps apart. */
626function entriesShown(board: Board, rows: number): BandEntry[] {
627 const { entries } = board
628
629 if (entries.length <= Math.min(rows, 3)) {
630 return entries
631 }
632
633 return rows <= 1 ? [] : entries.filter(entry => entry.tier === 1).slice(0, rows - 1)
634}
635
636/** The tone of a line's first colored segment; `idle` when none is colored. */
637function toneOfLine(line: Line): Tone {
638 const color = line.find(seg => seg.color !== undefined)?.color
639
640 return (Object.keys(TONE_KEYS) as Tone[]).find(tone => TONE_KEYS[tone] === color) ?? 'idle'
641}
642
643/**
644 * The band's rows from bandLines' `lines`: a running agent with its elapsed time on the shared scale, a fresh agent result the person may mark read,
645 * the first session asking a permission as a card while `maxRows` has room for it; any other line as given.
646 */
647function bandRowsOf(board: Board, lines: readonly Line[], rows: number, sessions: readonly SessionPresence[], maxRows: number): BandRow[] {
648 const shown = entriesShown(board, rows)
649 const running = shown.flatMap(entry => (entry.tier === 3 && entry.run?.state === 'running' ? [entry.run] : []))
650 const scale = scaleOf(Math.max(0, ...running.map(run => elapsedOf(run, board.now) / 1000)))
651 const asking = sessions.filter(one => one.state === 'permission')
652 let hasCardRoom = maxRows - lines.length >= ASK_CARD_ROWS - 1
653
654 return lines.map((line, index): BandRow => {
655 const entry = shown[index]
656 const run = entry?.run
657
658 if (entry !== undefined && run !== undefined && entry.tier === 3 && run.state === 'running') {
659 const ms = elapsedOf(run, board.now)
660 const time = fmtDuration(ms)
661 const denied: Line = (run.denied ?? 0) > 0 ? [{ text: ' ' }, { text: t().denied(run.denied ?? 0), color: 'error' }] : []
662 const quiet: Line = isStalled(run, board.now, entry.flight) ? [{ text: ' ' }, { text: t().quiet(fmtDuration(board.now - run.lastActivityAt)), color: 'warning' }] : []
663 const step = entry.flight === undefined ? run.lastTool : flightText(entry.flight, board.now)
664
665 return { kind: 'running', title: run.description, step, time, frac: ms / 1000 / scale.secs, alt: t().elapsedAlt(time, scale.label), tail: [...denied, ...quiet] }
666 }
667
668 if (entry !== undefined && run !== undefined && entry.tier === 2) {
669 return { kind: 'result', line, tone: toneOfLine(line), agentId: run.agentId }
670 }
671
672 // A failed session is a tier 1 sessions entry too: only one counted as no failure asks.
673 const at = entry?.tier === 1 && entry.group === 'sessions' && entry.counts.failed === 0 ? asking.findIndex(one => one.since === entry.startedAt) : -1
674 const peer = at < 0 ? undefined : asking.splice(at, 1)[0]
675
676 if (peer !== undefined && hasCardRoom) {
677 hasCardRoom = false
678
679 return { kind: 'ask', id: peer.id, head: `${peer.name} ${t().peerWords.permission}`, waited: t().askWaited(fmtDuration(board.now - peer.since)), task: peer.title ?? peer.name, request: peer.detail ?? '—' }
680 }
681
682 return { kind: 'line', line, tone: toneOfLine(line) }
683 })
684}
685
686/** This session's current request while open with a piece not done: its pieces not dropped, in board order; else null. */
687function planRowOf(board: BoardRead | null): PlanRow | null {
688 const request = board?.requests.find(one => one.id === board.current && one.status === 'open')
689
690 if (board === null || request === undefined) {
691 return null
692 }
693
694 const statuses = board.nodes.filter(node => node.request === request.id && node.status !== 'dropped').map(node => node.status)
695 const done = statuses.filter(status => status === 'done').length
696
697 if (statuses.length === 0 || done === statuses.length) {
698 return null
699 }
700
701 return { kind: 'plan', title: request.title, statuses, done, total: statuses.length, alt: t().planAlt(done, statuses.length, request.title) }
702}
703
704/** The plan row on the terminal: the title bold, a text bar of its done pieces, `done/total` subtle. */
705function planText(row: PlanRow): Line {
706 const done = Math.round((row.done / row.total) * BAND_BAR_CELLS)
707
708 return [
709 { text: fit(row.title, BAND_TITLE_COLUMNS), bold: true },
710 { text: ' ' },
711 { text: '▰'.repeat(done), color: 'success' },
712 { text: '▱'.repeat(BAND_BAR_CELLS - done), color: 'inactive' },
713 { text: ' ' },
714 { text: `${row.done}/${row.total}`, color: 'subtle' },
715 ]
716}
717
718/** `rows` less trailing idle, line, result and notice rows, then the plan row, until at most `count` rows weigh at most `maxRows`, an ask card ASK_CARD_ROWS. */
719function withinBand(rows: readonly BandRow[], count: number, maxRows: number): BandRow[] {
720 const kept = [...rows]
721 const weight = () => kept.reduce((sum, row) => sum + (row.kind === 'ask' ? ASK_CARD_ROWS : 1), 0)
722
723 while (kept.length > count || weight() > maxRows) {
724 const trailing = kept.findLastIndex(row => row.kind === 'idle' || row.kind === 'line' || row.kind === 'result' || row.kind === 'notice')
725 const at = trailing >= 0 ? trailing : kept.findIndex(row => row.kind === 'plan')
726
727 if (at < 0) {
728 break
729 }
730
731 kept.splice(at, 1)
732 }
733
734 return kept
735}
736
737/** The idle line on the terminal: `✓ 空闲` in success, the rest subtle, its glyphs keeping their own colors. */
738function idleText(line: Line): Line {
739 const [word, ...rest] = line
740
741 return [{ text: '✓', color: 'success' }, { text: ' ' }, { text: word?.text ?? t().idleBand, color: 'success', bold: true }, ...rest.map(seg => ({ text: seg.text, color: seg.color ?? 'subtle' }))]
742}
743
744/** A running row on the terminal: its glyph, the title `titleColumns` wide, a text bar, the step bold, the time dim. */
745function runningText(row: RunningRow, titleColumns: number): Line {
746 const done = Math.round(Math.min(1, Math.max(0, row.frac)) * BAND_BAR_CELLS)
747
748 return [
749 { text: '●', color: 'permission' },
750 { text: ` ${padTo(fit(row.title, titleColumns), titleColumns)} ` },
751 { text: '▰'.repeat(done), color: 'permission' },
752 { text: '▱'.repeat(BAND_BAR_CELLS - done), color: 'inactive' },
753 { text: ' ' },
754 ...(row.step === '' ? [] : [{ text: fit(row.step, BAND_STEP_COLUMNS), bold: true }, { text: ' ' }]),
755 { text: row.time, dim: true },
756 ...row.tail,
757 ]
758}
759
760/** One title width for every running row: the widest title up to BAND_TITLE_COLUMNS, less what `columns` cannot hold beside the rest. */
761function runningTitleColumns(rows: readonly BandRow[], columns: number): number {
762 const running = rows.filter((row): row is RunningRow => row.kind === 'running')
763 const rest = Math.max(0, ...running.map(row => widthOf(runningText(row, 0).map(seg => seg.text).join(''))))
764 const widest = Math.min(BAND_TITLE_COLUMNS, Math.max(0, ...running.map(row => widthOf(row.title))))
765
766 return Math.max(Math.min(widest, BAND_MIN_TITLE_COLUMNS), Math.min(widest, columns - rest))
767}
768
769/**
770 * A session asking a permission on the terminal: a `╭─ 需要你 ─╮` frame in warning `width` wide, the head, the task and the request,
771 * then the button, and 工作台 after it when `onOpen` is given.
772 */
773function askCard(el: ElementTable, row: AskRow, width: number, onAsk: () => void, onOpen?: () => void) {
774 const { Box, Button, Text } = el
775 const inner = Math.max(0, width - 4)
776 const title = ` ${t().needsYou} `
777 const labelColumns = Math.max(widthOf(t().askTask), widthOf(t().askRequest)) + 2
778 const framed = (body: RenderChildren, used: number) => (
779 <Text wrap="truncate">
780 <Text color="warning">{'│ '}</Text>
781 {body}
782 {' '.repeat(Math.max(0, inner - used))}
783 <Text color="warning">{' │'}</Text>
784 </Text>
785 )
786 const lineRow = (line: Line) => {
787 const fitted = fitLine(line, inner)
788
789 return framed(
790 fitted.map(seg => (
791 <Text {...(seg.color !== undefined && { color: seg.color })} {...(seg.bold === true && { bold: true })} {...(seg.dim === true && { dimColor: true })}>
792 {seg.text}
793 </Text>
794 )),
795 widthOf(fitted.map(seg => seg.text).join('')),
796 )
797 }
798 const kvRow = (label: string, value: string): Line => [{ text: padTo(label, labelColumns), color: 'subtle' }, { text: value, bold: true }]
799
800 return (
801 <Box flexDirection="column">
802 <Text wrap="truncate">
803 <Text color="warning">{'╭─'}</Text>
804 <Text color="warning" bold>
805 {title}
806 </Text>
807 <Text color="warning">{`${'─'.repeat(Math.max(0, width - 3 - widthOf(title)))}╮`}</Text>
808 </Text>
809 {lineRow([{ text: '!', color: 'warning' }, { text: ` ${row.head}`, bold: true }, { text: ` · ${row.waited}`, dim: true }])}
810 {lineRow(kvRow(t().askTask, row.task))}
811 {lineRow(kvRow(t().askRequest, row.request))}
812 <Box>
813 <Text color="warning">{'│ '}</Text>
814 <Button key={`ask-${row.id}`} label={t().askHandle} onPress={onAsk} />
815 {onOpen === undefined ? null : <Text> </Text>}
816 {onOpen === undefined ? null : <Button key="dash-open" label={t().workbench} onPress={onOpen} />}
817 <Text>{' '.repeat(Math.max(0, inner - widthOf(t().askHandle) - 4 - (onOpen === undefined ? 0 : buttonColumns())))}</Text>
818 <Text color="warning">{' │'}</Text>
819 </Box>
820 <Text color="warning" wrap="truncate">{`╰${'─'.repeat(Math.max(0, width - 2))}╯`}</Text>
821 </Box>
822 )
823}
824
825/** One result of an agent: an agent sent on ends again under the same id. */
826const resultKey = (run: AgentRun) => `${run.agentId}@${run.endedAt ?? ''}`
827
828/** Marks an agent's new result read: off the band and out of its unread count; the agents that ended before it stay as they were. */
829async function dismissResult($: EngineInterface, agentId: string): Promise<void> {
830 const run = (await read($, agents)).find(one => one.agentId === agentId)
831
832 if (run !== undefined) {
833 bandDismissed = [...bandDismissed.filter(key => key !== resultKey(run)), resultKey(run)].slice(-MAX_AGENTS)
834 }
835
836 await redraw($)
837}
838
839/** A usage gauge's tone: normal under 80%, a warning to 95%, an error from there. */
840const usageTone = (percent: number): Tone => (percent < 80 ? 'running' : percent < 95 ? 'stale' : 'failed')
841
842/** The time to a reset: `42m`, `1h05`, `3d4h` past a day. */
843function countdown(ms: number): string {
844 if (ms < 3_600_000) {
845 return ms < 60_000 ? '<1m' : `${Math.floor(ms / 60_000)}m`
846 }
847
848 return ms < DAY_MS ? `${Math.floor(ms / 3_600_000)}h${String(Math.floor((ms % 3_600_000) / 60_000)).padStart(2, '0')}` : `${Math.floor(ms / DAY_MS)}d${Math.floor((ms % DAY_MS) / 3_600_000)}h`
849}
850
851/** The element table with each Client, the pane's only ones being lineText's clocks, drawn as the static time the clock would show first. */
852export function staticClocks(el: El): El {
853 const { Text } = el
854
855 return {
856 ...el,
857 Client: props => {
858 const clock = props.props as { from: number; now: number; format: 'duration' | 'age'; color: string; bold: boolean }
859
860 return (
861 <Text color={clock.color} bold={clock.bold}>
862 {(clock.format === 'age' ? fmtAge : fmtDuration)(clock.now - clock.from)}
863 </Text>
864 )
865 },
866 }
867}
868
869/** The timeline page is on screen with a turn that has not ended: its running times move. */
870async function isTimelineLive($: EngineInterface): Promise<boolean> {
871 if ((await read($, page)) !== 'timeline' || (await $.ui.panes()).find(one => one.id === PANE_ID)?.isShown !== true) {
872 return false
873 }
874
875 const turns = await read($, timeline)
876 const id = shownTurnId(turns, await read($, timelineTurn))
877
878 return turns.some(one => one.turnId === id && one.endedAt === undefined)
879}
880
881/**
882 * Something moves with time: on the band a running agent or model, or a result still inside its 20 s; or the timeline page's open turn.
883 * The cold cache has its own minute timer.
884 */
885async function isLive($: EngineInterface): Promise<boolean> {
886 return (
887 (await read($, agents)).some(one => one.state === 'running') ||
888 // Running checks show no time.
889 (await boardNow($)).entries.some(entry => entry.tier !== 1 && entry.group !== CACHE_GROUP && !(entry.group === CI_GROUP && entry.tier === 3)) ||
890 (await isTimelineLive($))
891 )
892}
893
894/** Shows `turnId` on the timeline page from its newest steps; null, or the newest main turn, follows the latest. */
895async function pickTurn($: EngineInterface, turnId: string | null): Promise<void> {
896 const latest = latestMainTurnId(await read($, timeline))
897
898 await update($, timelineTurn, () => (turnId === latest ? null : turnId))
899 await update($, timelinePage, () => null)
900 await ensureTicker($)
901}
902
903/** Closes the agents the engine lists as ended (killed ones get no turn.complete), asking at most every AGENT_LIST_MS while one is quiet or idle. */
904async function reconcileAgents($: EngineInterface): Promise<void> {
905 const now = await $.clock.now()
906
907 // Quiet by its last tool end alone: a killed agent's call in flight never ends on the timeline.
908 if (now - agentsListedAt < AGENT_LIST_MS || !(await read($, agents)).some(one => one.state === 'idle' || isStalled(one, now))) {
909 return
910 }
911
912 agentsListedAt = now
913
914 // A list that cannot be read tells nothing: every agent stays as it was.
915 const listed = await $.agent.list().catch(() => null)
916
917 if (listed !== null) {
918 await update($, agents, list => noteListed(list, listed, now))
919 }
920}
921
922/** Redraws once a second while anything on the band is live, so elapsed times move and fresh results expire. */
923async function ensureTicker($: EngineInterface): Promise<void> {
924 if (ticker !== null || !(await isLive($))) {
925 return
926 }
927
928 // Another call may have started one while isLive was read.
929 ticker ??= $.clock.every(1000, () => {
930 void (async () => {
931 await redraw($)
932 await reconcileAgents($)
933
934 if (!(await isLive($)) && ticker !== null) {
935 ticker.cancel()
936 ticker = null
937 // An agent spawned while isLive was read found this timer still set and started none.
938 await ensureTicker($)
939 }
940 })()
941 })
942}
943
944/** Where a leading `cd <dir> &&` moves, a relative dir taken from `cwd` and an unquoted `~` from `home`; else `cwd`. */
945function dirOf(command: string, cwd: string, home: string): string {
946 const [, single, double, bare] = CD_DIR.exec(command) ?? []
947 const dir = single ?? double ?? (bare === '~' || bare?.startsWith('~/') ? `${home}${bare.slice(1)}` : bare)
948
949 if (dir === undefined) {
950 return cwd
951 }
952
953 const parts: string[] = []
954
955 for (const part of (dir.startsWith('/') || dir.startsWith('~') ? dir : `${cwd}/${dir}`).split('/')) {
956 if (part === '..') {
957 parts.pop()
958 } else if (part !== '.' && part !== '') {
959 parts.push(part)
960 }
961 }
962
963 return `/${parts.join('/')}`
964}
965
966/** The linked worktree `path` lies in: the deepest of `listed` holding it, else by its `.claude/worktrees/<name>` (one made since the last collection); null for none. */
967function treeAt(path: string, listed: readonly WorktreeInfo[] | null): string | null {
968 const holding = (listed ?? []).filter(tree => path === tree.path || path.startsWith(`${tree.path}/`))
969
970 return holding.sort((a, b) => b.path.length - a.path.length)[0]?.name ?? WORKTREE_DIR.exec(path)?.[1] ?? null
971}
972
973/** Records a Bash result that reads as a test run; `where` is the worktree the command ran in; `isFailure`: it ended in PostToolUseFailure. */
974async function noteGate($: EngineInterface, command: unknown, text: string | null, cwd: string, agentId: string | undefined, isFailure: boolean): Promise<void> {
975 const summary = text === null ? null : summarizeTests(text)
976
977 if (summary === null || typeof command !== 'string') {
978 return
979 }
980
981 const failed = summary.failed || isFailure
982 const gate: GateRun = {
983 // An edit in its tree after this time makes it stale.
984 at: await $.clock.now(),
985 command: command.trim().replace(/\s+/g, ' ').slice(0, GATE_COMMAND_CHARS),
986 key: command.trim(),
987 where: treeAt(dirOf(command, cwd, (await $.env.get('HOME')) ?? ''), await read($, trees)) ?? 'main',
988 ...(agentId !== undefined && { agentId }),
989 ...summary,
990 // An exit alone called it failed: how many failed is unknown, not 0.
991 fail: failed && summary.fail === 0 ? null : summary.fail,
992 failed,
993 }
994
995 await update($, gates, list => [...list, gate].slice(-MAX_GATES))
996}
997
998/** A file edited at `path`: the gates of its tree, a worktree or else the session root's, run before now go stale; a file outside both is no tree's. */
999async function noteEdit($: EngineInterface, path: unknown): Promise<void> {
1000 if (typeof path !== 'string') {
1001 return
1002 }
1003
1004 const where = treeAt(path, await read($, trees)) ?? (path.startsWith(`${await $.session.root()}/`) ? 'main' : null)
1005
1006 if (where === null) {
1007 return
1008 }
1009
1010 const now = await $.clock.now()
1011 const isTurning = (gate: GateRun) => gate.where === where && gate.at < now && gate.stale !== true
1012
1013 // Every edit lands here: the atom is written, and the band redrawn, only when a gate turns stale.
1014 if ((await read($, gates)).some(isTurning)) {
1015 await update($, gates, list => list.map(gate => (isTurning(gate) ? { ...gate, stale: true } : gate)))
1016 }
1017}
1018
1019// mmrun runs, read from ~/.claude/mmruns; never written.
1020
1021/** Equal by value; for the small polled arrays only. */
1022const isSame = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
1023
1024async function readText($: EngineInterface, path: string): Promise<string> {
1025 try {
1026 return String(await $.fs.read(path))
1027 } catch {
1028 return ''
1029 }
1030}
1031
1032/** This session's id, which mmrun writes into the runs it starts; null when the engine does not give it. */
1033async function sessionIdOf($: EngineInterface): Promise<string | null> {
1034 try {
1035 return await $.session.id()
1036 } catch {
1037 return null
1038 }
1039}
1040
1041/** The model with what <name>.events.jsonl says, its first line read only while the session it names is not known yet; a read that fails adds nothing. */
1042async function readModelEvents($: EngineInterface, dir: string, name: string, mtimes: Map<string, number>, old: MmModel | undefined, model: MmModel): Promise<MmModel> {
1043 if (!mtimes.has(`${name}.events.jsonl`)) {
1044 return model
1045 }
1046
1047 const path = `${dir}/${name}.events.jsonl`
1048 const head = old?.claudeSession === undefined ? await $.process.run(['head', '-n', '1', path], { timeoutMs: GIT_TIMEOUT_MS }).catch(() => null) : null
1049 const tail = await $.process.run(['tail', '-c', String(EVENTS_TAIL_BYTES), path], { timeoutMs: GIT_TIMEOUT_MS }).catch(() => null)
1050 const known = old?.claudeSession === undefined ? model : { ...model, claudeSession: old.claudeSession }
1051
1052 return applyEvents(known, [head, tail].map(read => (read?.exitCode === 0 ? read.stdout : '')).join('\n'))
1053}
1054
1055async function readModel($: EngineInterface, dir: string, name: string, mtimes: Map<string, number>, now: number, old: MmModel | undefined): Promise<MmModel> {
1056 return readModelEvents($, dir, name, mtimes, old, await readStatus($, dir, name, mtimes, now, old))
1057}
1058
1059async function readStatus($: EngineInterface, dir: string, name: string, mtimes: Map<string, number>, now: number, old: MmModel | undefined): Promise<MmModel> {
1060 const started = Number((await readText($, `${dir}/${name}.started`)).trim())
1061 const model: MmModel = {
1062 name,
1063 status: (await readText($, `${dir}/${name}.status`)).trim() || 'RUNNING',
1064 startedAt: Number.isFinite(started) && started > 0 ? started * 1000 : 0,
1065 }
1066
1067 if (model.status === 'RUNNING') {
1068 const raw = mtimes.has(`${name}.pid`) ? (await readText($, `${dir}/${name}.pid`)).trim() : ''
1069 const pid = /^\d+$/.test(raw) ? raw : ''
1070 const isAlive = pid !== '' ? (await $.process.run(['kill', '-0', pid])).exitCode === 0 : model.startedAt === 0 || now - model.startedAt <= PID_GRACE_MS
1071
1072 return isAlive ? model : { ...model, status: 'STALE', endedAt: old?.endedAt ?? mtimes.get(`${name}.raw`) ?? now }
1073 }
1074
1075 model.endedAt = mtimes.get(`${name}.status`) ?? now
1076
1077 // `mmrun status` rewrites a dead RUNNING as STALE whenever it runs, so the status file's time says nothing.
1078 if (model.status === 'STALE') {
1079 model.endedAt = mtimes.get(`${name}.raw`) ?? mtimes.get(`${name}.started`) ?? (model.startedAt || model.endedAt)
1080 }
1081
1082 if (mtimes.has(`${name}.meta`)) {
1083 const meta = parseKv(await readText($, `${dir}/${name}.meta`))
1084 const secs = Number(meta.secs)
1085
1086 if (meta.secs && Number.isFinite(secs)) {
1087 model.secs = secs
1088 }
1089
1090 try {
1091 const tokens = (JSON.parse(meta.usage ?? '') as { output_tokens?: unknown }).output_tokens
1092
1093 if (typeof tokens === 'number') {
1094 model.outputTokens = tokens
1095 }
1096 } catch {}
1097 }
1098
1099 return model
1100}
1101
1102const errorText = (error: unknown) => firstLine(error instanceof Error ? error.message : String(error))
1103
1104/** A listing refused for want of the directory: mmrun never ran here, which is no runs rather than a failed read. */
1105const isMissing = (error: unknown) => (typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT') || /\bENOENT\b/.test(errorText(error))
1106
1107/** A status no later poll can change; STALE can still turn DONE. */
1108const isFinal = (model: MmModel) => model.status === 'DONE' || model.status === 'CANCELLED' || model.status.startsWith('FAIL:') || model.status.startsWith('SKIP:')
1109
1110/** Reads the newest 20 runs from the last 24 hours; runs whose every model was final in `prev` are reused as they were. Rejects when a listing fails, a missing root aside. */
1111async function pollRuns($: EngineInterface, prev: MmSnapshot | null): Promise<MmSnapshot> {
1112 const now = await $.clock.now()
1113 const root = `${(await $.env.get('HOME')) ?? ''}/.claude/mmruns`
1114 let ids: string[]
1115
1116 try {
1117 ids = (await $.fs.list(root))
1118 .filter(entry => entry.kind === 'dir' && RUNID.test(entry.name))
1119 .map(entry => entry.name)
1120 .sort()
1121 .reverse()
1122 .slice(0, MAX_RUNS)
1123 } catch (error) {
1124 if (isMissing(error)) {
1125 return { polledAt: now, runs: [] }
1126 }
1127
1128 throw error
1129 }
1130
1131 const found: MmRun[] = []
1132
1133 for (const runid of ids) {
1134 const old = prev?.runs.find(run => run.runid === runid)
1135
1136 if (old !== undefined && old.models.length > 0 && old.models.every(isFinal)) {
1137 if (now - old.createdAt <= DAY_MS) {
1138 found.push(old)
1139 }
1140
1141 continue
1142 }
1143
1144 const dir = `${root}/${runid}`
1145 let createdAt: number
1146
1147 try {
1148 createdAt = (await $.fs.stat(`${dir}/run.meta`)).mtimeMs
1149 } catch {
1150 continue
1151 }
1152
1153 if (now - createdAt > DAY_MS) {
1154 continue
1155 }
1156
1157 const mtimes = new Map((await $.fs.list(dir)).map(entry => [entry.name, entry.mtimeMs]))
1158 const meta = parseKv(await readText($, `${dir}/run.meta`))
1159 const models: MmModel[] = []
1160
1161 // Model names become file names inside the run directory, so nothing that could step out of it.
1162 for (const name of (meta.models ?? '').split(',').filter(one => MODEL_NAME.test(one))) {
1163 models.push(await readModel($, dir, name, mtimes, now, old?.models.find(m => m.name === name)))
1164 }
1165
1166 found.push({ runid, tag: meta.tag ?? '', workdir: meta.workdir ?? '', mode: meta.mode ?? '', createdAt, models })
1167 }
1168
1169 return { polledAt: now, runs: found }
1170}
1171
1172/** Reads each model's <m>.json and <m>.out of a listed run into `reports`. */
1173async function loadReport($: EngineInterface, runid: string, showAll: boolean): Promise<void> {
1174 const run = (await read($, runs))?.runs.find(one => one.runid === runid)
1175
1176 if (run === undefined) {
1177 return
1178 }
1179
1180 const dir = `${(await $.env.get('HOME')) ?? ''}/.claude/mmruns/${runid}`
1181 const models: DashReport['models'] = []
1182
1183 for (const model of run.models) {
1184 let json: unknown = null
1185
1186 try {
1187 json = JSON.parse(String(await $.fs.read(`${dir}/${model.name}.json`)))
1188 } catch {}
1189
1190 const outPath = `${dir}/${model.name}.out`
1191 const review = reviewOf(json, run.mode, outPath)
1192
1193 models.push({ name: model.name, status: model.status, markdown: reportOf(json, await readText($, outPath), run.mode, showAll, outPath), ...(review !== null && { review }) })
1194 }
1195
1196 const loadedAt = await $.clock.now()
1197 const open = await read($, detail)
1198
1199 // The severity toggled while this read: the toggle's own load writes the report.
1200 if (open?.page === 'mmrun' && open.runid === runid && open.showAll !== showAll) {hooks/events.ts 191 lines1import type { AgentRun, AgentRunState, MmRun, MmSnapshot } from '../types'
2import { isFailedModel, runLabel } from './runs'
3import type { TestSummary } from './summarize-tests'
4import { lastDays } from './usage'
5
6// The event ledger: one JSONL file per session and local day, each line an OTel-style event. No prompt text, no command output.
7
8export const COMMAND_CHARS = 120
9export const MAX_BYTES = 2 * 1024 * 1024
10export const KEEP_DAYS = 30
11
12export type Severity = 'INFO' | 'WARN' | 'ERROR'
13export type Attributes = Record<string, string | number | boolean | null>
14export type LedgerEvent = { name: string; severity: Severity; attributes: Attributes }
15
16const DAY = /^\d{4}-\d{2}-\d{2}$/
17const ENDS: Partial<Record<AgentRunState, Severity>> = { done: 'INFO', aborted: 'WARN', error: 'ERROR', refusal: 'ERROR' }
18
19export const eventsDir = (home: string, project: string) => `${home}/.claude/harness/events/${project}`
20
21export const eventsPath = (home: string, project: string, day: string, session: string) => `${eventsDir(home, project)}/${day}/${session}.jsonl`
22
23export const cutCommand = (command: string) => command.trim().replace(/\s+/g, ' ').slice(0, COMMAND_CHARS)
24
25/** One event as read back: `at` epoch ms, `session` the session it belongs to. */
26export type LedgerRecord = { at: number; name: string; severity: string; session: string; attributes: Attributes }
27
28/** A session's events, oldest first. */
29export type SessionEvents = { session: string; events: LedgerRecord[] }
30
31/** What the events view shows: this session's events, and every other session's, the latest to start first. */
32export type EventsRead = { session: string; own: LedgerRecord[]; others: SessionEvents[] }
33
34const isScalar = (value: unknown) => value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
35
36/** The session a file's lines belong to when they do not say: its name up to the first `.`. */
37export const sessionOfFile = (name: string) => name.split('.')[0]!
38
39/** The events of one file's text; a line that is not an event is skipped. */
40export function parseLedger(text: string, fallbackSession: string): LedgerRecord[] {
41 return text.split('\n').flatMap(line => {
42 let raw: unknown
43
44 try {
45 raw = JSON.parse(line)
46 } catch {
47 return []
48 }
49
50 if (typeof raw !== 'object' || raw === null) {
51 return []
52 }
53
54 const { timestamp, event_name: name, severity_text: severity, attributes } = raw as Record<string, unknown>
55 const at = typeof timestamp === 'string' ? Date.parse(timestamp) : NaN
56
57 if (!Number.isFinite(at) || typeof name !== 'string' || name === '') {
58 return []
59 }
60
61 const attrs: Attributes =
62 typeof attributes === 'object' && attributes !== null && !Array.isArray(attributes) ? Object.fromEntries(Object.entries(attributes).filter(([, value]) => isScalar(value))) : {}
63 const id = attrs['session.id']
64
65 return [{ at, name, severity: typeof severity === 'string' ? severity : 'INFO', session: typeof id === 'string' && id !== '' ? id : fallbackSession, attributes: attrs }]
66 })
67}
68
69/** Events of any number of files grouped by session and sorted by time; a session's lines may come from several writers' files. */
70export function groupEvents(records: readonly LedgerRecord[], session: string): EventsRead {
71 const by = new Map<string, LedgerRecord[]>()
72
73 for (const one of records) {
74 const list = by.get(one.session) ?? []
75
76 list.push(one)
77 by.set(one.session, list)
78 }
79
80 const all = [...by].map(([id, events]): SessionEvents => ({ session: id, events: events.sort((a, b) => a.at - b.at) }))
81
82 return {
83 session,
84 own: all.find(one => one.session === session)?.events ?? [],
85 others: all.filter(one => one.session !== session).sort((a, b) => b.events[0]!.at - a.events[0]!.at),
86 }
87}
88
89/** One line of the file, without its newline: `session.id` leads the attributes. */
90export function eventLine(at: number, session: string, event: LedgerEvent): string {
91 return JSON.stringify({ timestamp: new Date(at).toISOString(), event_name: event.name, severity_text: event.severity, attributes: { 'session.id': session, ...event.attributes } })
92}
93
94const bytesOf = (line: string) => new TextEncoder().encode(line).length + 1
95
96/** `lines` with the oldest dropped until they and their newlines fit in `maxBytes`. */
97export function capped(lines: readonly string[], maxBytes = MAX_BYTES): string[] {
98 let total = lines.reduce((sum, line) => sum + bytesOf(line), 0)
99 let start = 0
100
101 while (total > maxBytes && start < lines.length) {
102 total -= bytesOf(lines[start]!)
103 start += 1
104 }
105
106 return lines.slice(start)
107}
108
109/** A runner of work one at a time: each starts once the one before has settled, and settles as its own work does. */
110export function serially(): <T>(work: () => Promise<T>) => Promise<T> {
111 let last: Promise<unknown> = Promise.resolve()
112
113 return work => {
114 const run = last.then(work)
115
116 last = run.catch(() => undefined)
117
118 return run
119 }
120}
121
122/** The date directories of `names` older than KEEP_DAYS before `at`'s local day. */
123export function staleDays(names: readonly string[], at: number): string[] {
124 const oldest = lastDays(at, KEEP_DAYS + 1).at(-1)!
125
126 return names.filter(name => DAY.test(name) && name < oldest)
127}
128
129/** A Bash result's text as the test gates read it: an errored call's text, else stdout and stderr. */
130export function bashText(output: unknown): string | null {
131 if (typeof output === 'string') {
132 return output
133 }
134
135 const out = typeof output === 'object' && output !== null ? (output as { stdout?: unknown; stderr?: unknown }) : null
136
137 if (out === null || typeof out.stdout !== 'string') {
138 return null
139 }
140
141 return typeof out.stderr === 'string' ? `${out.stdout}\n${out.stderr}` : out.stdout
142}
143
144/** A test run's result; `isFailure`: the call ended in PostToolUseFailure. A failure by its exit alone has an unknown fail count. */
145export function gateEvent(command: string, summary: TestSummary, isFailure: boolean): LedgerEvent {
146 const failed = summary.failed || isFailure
147
148 return {
149 name: 'gate.result',
150 severity: failed ? 'WARN' : 'INFO',
151 attributes: { command: cutCommand(command), pass: summary.pass, fail: failed && summary.fail === 0 ? null : summary.fail, outcome: failed ? 'fail' : 'pass' },
152 }
153}
154
155/** What changed between two writes of the agents: a call denied, and a running or idle agent that ended. */
156export function agentEvents(before: readonly AgentRun[], after: readonly AgentRun[]): LedgerEvent[] {
157 return after.flatMap(run => {
158 const was = before.find(one => one.agentId === run.agentId)
159 const head = { 'agent.id': run.agentId, 'agent.type': run.subagentType }
160 const severity = ENDS[run.state]
161 const isEnded = severity !== undefined && (was?.state === 'running' || was?.state === 'idle')
162
163 return [
164 ...((run.denied ?? 0) > (was?.denied ?? 0) ? [{ name: 'agent.denied', severity: 'WARN' as const, attributes: { ...head, tool: run.lastTool } }] : []),
165 ...(isEnded ? [{ name: 'agent.end', severity, attributes: { ...head, state: run.state, duration_ms: run.durationMs ?? null } }] : []),
166 ]
167 })
168}
169
170const isRunning = (run: MmRun) => run.models.some(model => model.status === 'RUNNING')
171
172/** The runs of `isOurs` that appeared or stopped running between two polls; none against no earlier poll. */
173export function runEvents(before: MmSnapshot | null, after: MmSnapshot | null, isOurs: (run: MmRun) => boolean): LedgerEvent[] {
174 if (before === null || after === null) {
175 return []
176 }
177
178 return after.runs.filter(isOurs).flatMap(run => {
179 const was = before.runs.find(one => one.runid === run.runid)
180 const head = { 'run.id': run.runid, label: runLabel(run), models: run.models.map(model => model.name).join(',') }
181 const isEnded = run.models.length > 0 && !isRunning(run) && (was === undefined || isRunning(was))
182
183 return [
184 ...(was === undefined ? [{ name: 'mmrun.start', severity: 'INFO' as const, attributes: { ...head, mode: run.mode } }] : []),
185 ...(isEnded
186 ? [{ name: 'mmrun.end', severity: run.models.some(isFailedModel) ? ('WARN' as const) : ('INFO' as const), attributes: { ...head, status: run.models.map(model => `${model.name}:${model.status}`).join(',') } }]
187 : []),
188 ]
189 })
190}
191hooks/failures.ts 21 lines1import type { HookFailure } from 'claude-code'
2
3// Keys already written this load: a hook that fails on every redraw writes one line.
4const logged = new Set<string>()
5
6/** True the first time `key` comes this load. */
7export function isFirstTime(key: string): boolean {
8 if (logged.has(key)) {
9 return false
10 }
11
12 logged.add(key)
13
14 return true
15}
16
17/** The debug line of a hook's failure; undefined after the first for `name` this load. `name` is the event and what its matcher picks. */
18export function failureLine(name: string, error: HookFailure): string | undefined {
19 return isFirstTime(`hook ${name}`) ? `dashboard: ${name} hook failed (${error.kind}): ${error.message ?? 'no message'}` : undefined
20}
21hooks/summarize-tests.ts 192 lines1/**
2 * `pass` is null when no line of the output gave a total; `fail` is null when a marker said failed with no failing test counted.
3 * `unit` is `packages` when only go package lines were counted; absent, the counts are tests.
4 */
5export type TestSummary = { pass: number | null; fail: number | null; failed: boolean; failures: string[]; unit?: 'packages' }
6
7type Parsed = Omit<TestSummary, 'failed' | 'fail'> & { fail: number; failed?: boolean }
8
9// Real test output lines run far shorter; longer ones are cut so no pattern below backtracks over them for seconds.
10const MAX_LINE = 2000
11// The card shows a handful; `fail` keeps the real count.
12export const MAX_FAILURES = 50
13
14const lines = (text: string) => text.split('\n').map(l => l.trim().slice(0, MAX_LINE))
15
16const sum = (all: RegExpMatchArray[]) => all.reduce((n, m) => n + Number(m[1]), 0)
17
18// One `N pass` / `N fail` pair per run; sum them.
19const bun = (text: string): Parsed | null => {
20 const pass = [...text.matchAll(/^\s*(\d+) pass\s*$/gm)]
21 const fail = [...text.matchAll(/^\s*(\d+) fail\s*$/gm)]
22 if (pass.length === 0 || fail.length === 0) return null
23 const failures = lines(text).filter(l => l.startsWith('✗') || l.startsWith('(fail)'))
24 return { pass: sum(pass), fail: sum(fail), failures }
25}
26
27// One summary line per test binary; sum them.
28const cargo = (text: string): Parsed | null => {
29 const all = [...text.matchAll(/^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed/gm)]
30 if (all.length === 0) return null
31 return {
32 pass: all.reduce((n, m) => n + Number(m[1]), 0),
33 fail: all.reduce((n, m) => n + Number(m[2]), 0),
34 failures: [],
35 }
36}
37
38// XCTest prints one `Executed` line per suite; the last is the outermost suite's total. Its failure count
39// counts assertions, so failing tests are counted by name when their error or `Test Case … failed` lines are there.
40const xctest = (all: string[]) => {
41 const last = all.map(l => /Executed (\d+) tests?, with (\d+) failures?/.exec(l)).filter(m => m !== null).at(-1)
42 if (last === undefined) return null
43 const named = new Map<string, string>()
44 for (const l of all) {
45 const name = /: error: -\[(\S+ \S+)\] : /.exec(l)?.[1]
46 if (name !== undefined && !named.has(name)) named.set(name, l)
47 }
48 for (const l of all) {
49 const name = /^Test Case '-\[(\S+ \S+)\]' failed\b/.exec(l)?.[1]
50 if (name !== undefined && !named.has(name)) named.set(name, l)
51 }
52 return { total: Number(last[1]), fail: named.size > 0 ? named.size : Number(last[2]), failures: [...named.values()] }
53}
54
55// Swift Testing names a test in quotes, or by its function when it has no display name.
56const ST_NAME = String.raw`(?:"(.+?)"|(\S+\(.*?\)))`
57const ST_RUN = /Test run with (\d+) tests? in \d+ suites? (passed|failed) after/
58const ST_FAILED = new RegExp(String.raw`\bTest ${ST_NAME}(?: with \d+ test cases?)? failed after`)
59const ST_ISSUE = new RegExp(String.raw`\bTest ${ST_NAME} recorded an issue(?: with .+?)? at (\S+?:\d+:\d+):`)
60
61const swiftTesting = (all: string[]) => {
62 const runs = all.map(l => ST_RUN.exec(l)).filter(m => m !== null)
63 // Failing test → where its first issue was recorded.
64 const named = new Map<string, string | null>()
65 for (const l of all) {
66 const issue = ST_ISSUE.exec(l)
67 const failed = issue ?? ST_FAILED.exec(l)
68 if (failed === null) continue
69 const name = failed[1] ?? failed[2]!
70 if (!named.has(name) || named.get(name) === null) named.set(name, issue?.[3] ?? null)
71 }
72 const last = runs.at(-1)
73 if (last === undefined && named.size === 0) return null
74 return {
75 total: last === undefined ? null : Number(last[1]),
76 fail: named.size,
77 failures: [...named].map(([name, at]) => (at === null ? name : `${name} ${at}`)),
78 isFailed: runs.some(m => m[2] === 'failed'),
79 }
80}
81
82// xcodebuild's own list after a failed test action, covering both frameworks.
83const failingTests = (text: string) => {
84 const section = /^Failing tests:\n((?:[ \t]+\S.*(?:\n|$))+)/m.exec(text)
85 return section === null ? null : lines(section[1]!).filter(l => l !== '')
86}
87
88const xcode = (text: string): Parsed | null => {
89 const all = lines(text)
90 const xct = xctest(all)
91 const st = swiftTesting(all)
92 if (xct === null && st === null) return null
93 const failed = st?.isFailed === true
94 // Failure lines alone, with neither an `Executed` nor a `Test run with` line: how many passed is unknown.
95 const isCounted = xct !== null || (st?.total ?? null) !== null
96 const listed = failingTests(text)
97 if (listed !== null) {
98 const fail = listed.length
99 return { pass: isCounted ? Math.max(0, (xct?.total ?? 0) + (st?.total ?? 0) - fail) : null, fail, failed, failures: listed }
100 }
101 return {
102 pass: isCounted ? Math.max(0, (xct?.total ?? 0) - (xct?.fail ?? 0)) + Math.max(0, (st?.total ?? 0) - (st?.fail ?? 0)) : null,
103 fail: (xct?.fail ?? 0) + (st?.fail ?? 0),
104 failed,
105 failures: [...(xct?.failures ?? []), ...(st?.failures ?? [])],
106 }
107}
108
109// Each `Ran N tests in …s` line, then its `OK` / `FAILED (…)` verdict; skipped tests are neither passes nor failures.
110const unittest = (text: string): Parsed | null => {
111 let total: number | null = null
112 let runs = 0
113 let pass = 0
114 let fail = 0
115 for (const l of lines(text)) {
116 const ran = /^Ran (\d+) tests? in [\d.]+s$/.exec(l)
117 if (ran) {
118 total = Number(ran[1])
119 continue
120 }
121 const verdict = /^(?:OK(?: \(([^)]*)\))?|FAILED \(([^)]*)\))$/.exec(l)
122 if (verdict === null || total === null) continue
123 const counts = verdict[1] ?? verdict[2] ?? ''
124 const count = (name: string) => Number(new RegExp(`\\b${name}=(\\d+)`).exec(counts)?.[1] ?? 0)
125 const failed = count('failures') + count('errors')
126 pass += Math.max(0, total - failed - count('skipped'))
127 fail += failed
128 runs += 1
129 total = null
130 }
131 return runs === 0 ? null : { pass, fail, failures: [] }
132}
133
134// One summary line per run, ending with `in 0.12s`; `-q` drops the `===` rule around it. Errors count as failures.
135// cargo's `test result:` line fits the same pattern and is cargo's.
136const pytest = (text: string): Parsed | null => {
137 const summaries = lines(text).filter(l => !l.startsWith('test result:') && /\b\d+ (?:passed|failed|errors?)\b.*\bin [\d.]+s\b/.test(l))
138 if (summaries.length === 0) return null
139 const count = (pattern: RegExp) => summaries.reduce((n, l) => n + Number(pattern.exec(l)?.[1] ?? 0), 0)
140 const pass = count(/\b(\d+) passed\b/)
141 const fail = count(/\b(\d+) failed\b/) + count(/\b(\d+) errors?\b/)
142 const failures = lines(text).filter(l => /^FAILED \S+::\S+/.test(l) || /^ERROR \S+\.py\b/.test(l))
143 return { pass, fail, failures }
144}
145
146// Per-package lines: `ok pkg 0.01s` / `ok pkg (cached)`, `FAIL pkg 0.01s` / `FAIL pkg [build failed]`.
147// With -v, unindented `--- PASS:` / `--- FAIL:` lines count top-level tests; without, only packages are known.
148const go = (text: string): Parsed | null => {
149 const okPackages = (text.match(/^ok\s+\S+\s+(?:\(cached\)|[\d.]+s)/gm) ?? []).length
150 const failPackages = (text.match(/^FAIL\s+\S+\s+(?:[\d.]+s|\[)/gm) ?? []).length
151 if (okPackages + failPackages === 0) return null
152 if (!/^(?:=== RUN\s|--- PASS: )/m.test(text)) return { pass: okPackages, fail: failPackages, failures: [], unit: 'packages' }
153 const tests = (verdict: string) => (text.match(new RegExp(`^--- ${verdict}: `, 'gm')) ?? []).length
154 return { pass: tests('PASS'), fail: tests('FAIL'), failed: failPackages > 0, failures: [] }
155}
156
157// plugins/mm/tests/test_mmrun.py and its kind: `ok <name>` / `FAIL <name> (…)` lines, then `all passed` or `<N> failed` last.
158const okFail = (text: string): Parsed | null => {
159 const all = lines(text).filter(l => l !== '')
160 const last = all.at(-1)
161 const footer = last === undefined ? null : /^(\d+) failed$/.exec(last)
162 if (last === undefined || (last !== 'all passed' && footer === null)) return null
163 const failures = all.filter(l => l.startsWith('FAIL '))
164 return { pass: all.filter(l => l.startsWith('ok ')).length, fail: footer === null ? 0 : Number(footer[1]), failures }
165}
166
167// An `ok <name> 5s` line would pass for a go package.
168const goUnlessOkFail = (text: string) => (okFail(text) === null ? go(text) : null)
169
170const PARSERS = [bun, cargo, xcode, unittest, pytest, okFail, goUnlessOkFail]
171
172// `** TEST FAILED **`, `** TEST EXECUTE FAILED **`…: xcodebuild failed even when every counted test passed.
173const FAILED_MARKER = /\*\* [A-Z ]*FAILED \*\*/
174
175// Every runner's summary counts, one output may hold several; any failure anywhere fails the whole.
176export const summarizeTests = (text: string): TestSummary | null => {
177 const parts = PARSERS.map(parse => parse(text)).filter(got => got !== null)
178 if (parts.length === 0) return null
179 // Package counts stand only when no runner counted tests; a failing package still fails the whole.
180 const counted = parts.some(p => p.unit === undefined) ? parts.filter(p => p.unit === undefined) : parts
181 const passes = counted.map(p => p.pass).filter(n => n !== null)
182 const fail = counted.reduce((n, p) => n + p.fail, 0)
183 const failed = parts.some(p => p.failed === true || p.fail > 0) || FAILED_MARKER.test(text)
184 return {
185 pass: passes.length === 0 ? null : passes.reduce((n, p) => n + p, 0),
186 fail: failed && fail === 0 ? null : fail,
187 failed,
188 failures: parts.flatMap(p => p.failures).slice(0, MAX_FAILURES),
189 ...(counted.every(p => p.unit === 'packages') && { unit: 'packages' as const }),
190 }
191}
192hooks/usage.ts 220 lines1import type { AskCounts, SkillCounts, UsageCounts, UsageDay, UsageLedger, UsageRead, UsageThread } from '../types'
2
3export const USAGE_DAYS = 7
4
5/**
6 * Each count against an uncached input token, by the API's price ratios: a weight to compare parts, never money.
7 * turn.step's usage does not split cache writes into 5m (1.25×) and 1h (2×): all take the 5-minute weight.
8 */
9export const WEIGHTS = { input: 1, cacheRead: 0.1, cacheWrite: 1.25, output: 5 } as const
10
11type ApiUsage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
12
13/** How a Skill call ended; null for a fork launched in the background, whose outcome comes later. */
14export type SkillOutcome = 'inline' | 'forked' | 'error' | null
15
16export type AskOutcome = 'recommended' | 'option' | 'typed' | 'declined'
17
18const NO_COUNTS: UsageCounts = { requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
19const NO_SKILL: SkillCounts = { invocations: 0, inline: 0, forked: 0, errors: 0 }
20const NO_ASKS: AskCounts = { dialogs: 0, questions: 0, recommended: 0, option: 0, typed: 0, declined: 0, under1m: 0, under2m: 0, under5m: 0, under10m: 0, over10m: 0 }
21// Each wait bucket but the last, by the ms it stays under.
22const WAIT_BUCKETS = [['under1m', 60_000], ['under2m', 120_000], ['under5m', 300_000], ['under10m', 600_000]] as const
23const THREADS: UsageThread[] = ['main', 'subagent']
24
25export const emptyDay = (): UsageDay => ({ models: {}, skills: {} })
26
27function added<T extends Record<string, number>>(a: T, b: T): T {
28 return Object.fromEntries(Object.keys(a).map(key => [key, a[key]! + b[key]!])) as T
29}
30
31export const equivalentOf = (counts: UsageCounts) =>
32 counts.input * WEIGHTS.input + counts.cacheRead * WEIGHTS.cacheRead + counts.cacheWrite * WEIGHTS.cacheWrite + counts.output * WEIGHTS.output
33
34/** One request's final usage, in the bucket of the model that answered and its kind of thread. */
35export function requestNoted(day: UsageDay, model: string, thread: UsageThread, usage: ApiUsage): UsageDay {
36 const was = day.models[model] ?? {}
37 const one = { requests: 1, input: usage.input_tokens, output: usage.output_tokens, cacheRead: usage.cache_read_input_tokens, cacheWrite: usage.cache_creation_input_tokens }
38
39 return { ...day, models: { ...day.models, [model]: { ...was, [thread]: added(was[thread] ?? NO_COUNTS, one) } } }
40}
41
42/** A Skill call's result: inline when it resolved, forked when its fork completed, else an error. */
43export function skillOutcomeOf(response: unknown): SkillOutcome {
44 const one = (typeof response === 'object' && response !== null ? response : {}) as Record<string, unknown>
45
46 if (one.status === 'forked') {
47 return one.background === true ? null : one.success === true ? 'forked' : 'error'
48 }
49
50 return one.success === true ? 'inline' : 'error'
51}
52
53/** The skill a Skill call named; its arguments are never read. */
54export function skillNameOf(input: unknown): string {
55 const skill = (typeof input === 'object' && input !== null ? input : {}) as { skill?: unknown }
56
57 return typeof skill.skill === 'string' && skill.skill !== '' ? skill.skill : '?'
58}
59
60export function skillNoted(day: UsageDay, name: string, outcome: SkillOutcome): UsageDay {
61 const was = day.skills[name] ?? NO_SKILL
62 const counts = added(was, { invocations: 1, inline: outcome === 'inline' ? 1 : 0, forked: outcome === 'forked' ? 1 : 0, errors: outcome === 'error' ? 1 : 0 })
63
64 return { ...day, skills: { ...day.skills, [name]: counts } }
65}
66
67/**
68 * Per question of an AskUserQuestion input, how the tool's result answered it: its `answers` map a question's text to the
69 * label chosen, a multiSelect's labels comma-joined, or the text typed. No result, or no answer to a question, is declined.
70 */
71export function askOutcomes(input: unknown, response: unknown): AskOutcome[] {
72 const questions = isRecord(input) && Array.isArray(input.questions) ? (input.questions as unknown[]) : []
73 const answers = isRecord(response) && isRecord(response.answers) ? response.answers : {}
74
75 return questions.map(one => {
76 const question = isRecord(one) ? one : {}
77 const labels = (Array.isArray(question.options) ? (question.options as unknown[]) : []).map(option => (isRecord(option) ? option.label : undefined))
78 const recommended = labels.find(label => typeof label === 'string' && label.includes('(Recommended)'))
79 const answer = typeof question.question === 'string' ? answers[question.question] : undefined
80
81 if (typeof answer !== 'string' || answer === '') {
82 return 'declined'
83 }
84
85 if (answer === recommended) {
86 return 'recommended'
87 }
88
89 if (labels.includes(answer)) {
90 return 'option'
91 }
92
93 return question.multiSelect === true && answer.split(', ').every(part => labels.includes(part)) ? 'option' : 'typed'
94 })
95}
96
97/** One dialog that ended: its questions by outcome, its wait in its bucket. */
98export function askNoted(day: UsageDay, outcomes: readonly AskOutcome[], waitMs: number): UsageDay {
99 const bucket = WAIT_BUCKETS.find(([, ms]) => waitMs < ms)?.[0] ?? 'over10m'
100 const count = (outcome: AskOutcome) => outcomes.filter(one => one === outcome).length
101 const one = { ...NO_ASKS, dialogs: 1, questions: outcomes.length, recommended: count('recommended'), option: count('option'), typed: count('typed'), declined: count('declined'), [bucket]: 1 }
102
103 return { ...day, asks: added(day.asks ?? NO_ASKS, one) }
104}
105
106export function daySum(a: UsageDay, b: UsageDay): UsageDay {
107 const models = { ...a.models }
108 const skills = { ...a.skills }
109
110 for (const [model, threads] of Object.entries(b.models)) {
111 const was = models[model] ?? {}
112
113 models[model] = Object.fromEntries(
114 THREADS.filter(thread => was[thread] !== undefined || threads[thread] !== undefined).map(thread => [thread, added(was[thread] ?? NO_COUNTS, threads[thread] ?? NO_COUNTS)]),
115 )
116 }
117
118 for (const [name, counts] of Object.entries(b.skills)) {
119 skills[name] = added(skills[name] ?? NO_SKILL, counts)
120 }
121
122 const isAsked = a.asks !== undefined || b.asks !== undefined
123
124 return { models, skills, ...(isAsked && { asks: added(a.asks ?? NO_ASKS, b.asks ?? NO_ASKS) }) }
125}
126
127const isCount = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value >= 0
128const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
129const hasCounts = (value: unknown, keys: readonly string[]) => isRecord(value) && keys.every(key => isCount(value[key]))
130
131/** A ledger file's day; null for one cut mid-write, or not of this shape. */
132export function parseUsageDay(text: string): UsageDay | null {
133 let raw: unknown
134
135 try {
136 raw = JSON.parse(text)
137 } catch {
138 return null
139 }
140
141 if (!isRecord(raw) || !isRecord(raw.models) || !isRecord(raw.skills)) {
142 return null
143 }
144
145 const isModels = Object.values(raw.models).every(threads => isRecord(threads) && THREADS.every(thread => threads[thread] === undefined || hasCounts(threads[thread], Object.keys(NO_COUNTS))))
146 const isSkills = Object.values(raw.skills).every(counts => hasCounts(counts, Object.keys(NO_SKILL)))
147 // A file written before the asks were kept has none.
148 const isAsks = raw.asks === undefined || hasCounts(raw.asks, Object.keys(NO_ASKS))
149
150 return isModels && isSkills && isAsks
151 ? { models: raw.models as UsageDay['models'], skills: raw.skills as UsageDay['skills'], ...(raw.asks !== undefined && { asks: raw.asks as AskCounts }) }
152 : null
153}
154
155/** Claude's own spelling of a project folder: the root with every `/` a `-`. */
156export const projectKey = (root: string) => root.replace(/\//g, '-')
157
158export const ledgerDir = (home: string, project: string, day: string) => `${home}/.claude/dashboard/usage/${project}/${day}`
159
160const pad2 = (n: number) => String(n).padStart(2, '0')
161
162/** The local day of `at`, `YYYY-MM-DD`. */
163export function dayOf(at: number): string {
164 const date = new Date(at)
165
166 return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
167}
168
169/** The `count` local days ending on `at`'s, newest first; each taken at its noon, so a daylight-saving shift keeps the day. */
170export function lastDays(at: number, count = USAGE_DAYS): string[] {
171 const date = new Date(at)
172
173 return Array.from({ length: count }, (_, i) => dayOf(new Date(date.getFullYear(), date.getMonth(), date.getDate() - i, 12).getTime()))
174}
175
176/** Per day, the other sessions' files and this session's own: its ledger where it holds the day, else its file. */
177export function daysOf(read: UsageRead | null, own: UsageLedger | null): Record<string, UsageDay> {
178 const isSame = read !== null && own !== null && read.session === own.session
179 const days = new Set([...Object.keys(read?.others ?? {}), ...Object.keys(read?.own ?? {}), ...Object.keys(own?.days ?? {})])
180
181 return Object.fromEntries(
182 [...days].map(day => {
183 const mine = own?.days[day]
184 const filed = read?.own[day]
185 const parts = [read?.others[day], ...(isSame ? [mine ?? filed] : [filed, mine])].filter((one): one is UsageDay => one !== undefined)
186
187 return [day, parts.reduce(daySum, emptyDay())]
188 }),
189 )
190}
191
192export type UsageTotal = { counts: UsageCounts; equivalent: number }
193
194/** What the usage page shows: each of `days` newest first, the main thread against the subagents, the skills by calls, the question dialogs. */
195export type UsageWeek = {
196 days: ({ day: string } & UsageTotal)[]
197 threads: ({ thread: UsageThread } & UsageTotal)[]
198 skills: ({ name: string } & SkillCounts)[]
199 asks: AskCounts
200}
201
202const totalOf = (counts: UsageCounts): UsageTotal => ({ counts, equivalent: Math.round(equivalentOf(counts)) })
203
204export function weekOf(byDay: Record<string, UsageDay>, days: readonly string[]): UsageWeek {
205 const shown = days.map(day => byDay[day] ?? emptyDay())
206 const threadSum = (day: UsageDay, thread: UsageThread) => Object.values(day.models).reduce((sum, one) => added(sum, one[thread] ?? NO_COUNTS), NO_COUNTS)
207 const skills = shown.reduce((sum, day) => daySum(sum, { models: {}, skills: day.skills }), emptyDay()).skills
208
209 return {
210 days: shown.map((day, i) => ({ day: days[i]!, ...totalOf(added(threadSum(day, 'main'), threadSum(day, 'subagent'))) })),
211 threads: THREADS.map(thread => ({ thread, ...totalOf(shown.reduce((sum, day) => added(sum, threadSum(day, thread)), NO_COUNTS)) })),
212 skills: Object.entries(skills)
213 .map(([name, counts]) => ({ name, ...counts }))
214 .sort((a, b) => b.invocations - a.invocations || a.name.localeCompare(b.name)),
215 asks: shown.reduce((sum, day) => added(sum, day.asks ?? NO_ASKS), NO_ASKS),
216 }
217}
218
219export const isEmptyWeek = (week: UsageWeek) => week.skills.length === 0 && week.asks.dialogs === 0 && week.days.every(one => one.counts.requests === 0)
220hooks/agent-model.ts 346 lines1import type { AgentInfo, SessionMessage, TurnCompleteReason } from 'claude-code'
2
3import type { AgentRun, AgentRunState, AgentUsage } from '../types'
4
5export const MAX_AGENTS = 30
6/** Characters of an agent's final answer kept on its record. */
7export const ANSWER_CHARS = 4000
8
9const SLOTS = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
10
11/** Running, failed, or ended after `seenAt` (unread): an agent that keeps its digit. */
12const holdsSlot = (run: AgentRun, seenAt: number) =>
13 run.state === 'running' || run.state === 'error' || run.state === 'refusal' || (run.denied ?? 0) > 0 || (run.endedAt ?? Infinity) > seenAt
14
15/**
16 * The new run takes the least digit no running, failed or unread agent holds (`seenAt`: when the Agents page was last
17 * visited), a read return giving it up; none when all nine are held.
18 */
19export function noteSpawn(list: readonly AgentRun[], run: AgentRun, seenAt = 0): AgentRun[] {
20 const rest = list.filter(one => one.agentId !== run.agentId)
21 const held = new Set(rest.filter(one => holdsSlot(one, seenAt)).map(one => one.slot))
22 const slot = SLOTS.find(digit => !held.has(digit))
23
24 if (slot === undefined) {
25 return [...rest, run].slice(-MAX_AGENTS)
26 }
27
28 const freed = rest.map(one => {
29 if (one.slot !== slot) {
30 return one
31 }
32
33 const { slot: _slot, ...without } = one
34
35 return without
36 })
37
38 return [...freed, { ...run, slot }].slice(-MAX_AGENTS)
39}
40
41/** A tool call that ended, ran, failed or was denied; one of an ended agent means it was sent on and runs again. */
42export function noteTool(list: readonly AgentRun[], agentId: string, label: string, now: number): AgentRun[] {
43 return list.map(one => (one.agentId === agentId ? { ...resumed(one, now), tools: one.tools + 1, lastTool: label, lastActivityAt: now } : one))
44}
45
46/** A message delivered to an ended agent (`to`, its id) resumes it now, before any tool of it ends. */
47export function noteResumed(list: readonly AgentRun[], to: string, now: number): AgentRun[] {
48 return list.map(one => (one.agentId === to && one.state !== 'running' ? { ...resumed(one, now), lastActivityAt: now } : one))
49}
50
51/**
52 * Running again from `now`, the time of its turns before kept in `activeMs`: the end and its tokens go, the last answer stays
53 * readable until the next replaces it.
54 */
55function resumed(run: AgentRun, now: number): AgentRun {
56 if (run.state === 'running') {
57 return run
58 }
59
60 const { endedAt: _endedAt, durationMs, outputTokens: _outputTokens, usage: _usage, ...rest } = run
61
62 return { ...rest, state: 'running', activeMs: durationMs ?? 0, turnAt: now }
63}
64
65export function noteDenied(list: readonly AgentRun[], agentId: string): AgentRun[] {
66 return list.map(one => (one.agentId === agentId ? { ...one, denied: (one.denied ?? 0) + 1 } : one))
67}
68
69export function noteDone(
70 list: readonly AgentRun[],
71 agentId: string,
72 done: { reason: TurnCompleteReason; durationMs: number; outputTokens?: number; endedAt: number; answer?: string; usage?: AgentUsage },
73): AgentRun[] {
74 return list.map(one =>
75 one.agentId === agentId
76 ? {
77 ...one,
78 state: stateOf(done.reason),
79 // The engine times the latest turn alone.
80 durationMs: (one.activeMs ?? 0) + done.durationMs,
81 endedAt: done.endedAt,
82 ...(done.outputTokens !== undefined && { outputTokens: done.outputTokens }),
83 ...(done.usage !== undefined && { usage: done.usage }),
84 ...(done.answer !== undefined && { answer: done.answer.slice(0, ANSWER_CHARS) }),
85 }
86 : one,
87 )
88}
89
90const isOpen = (run: AgentRun) => run.state === 'running' || run.state === 'idle'
91
92/** The `$.agent.list()` statuses that stop a running agent, as the state it takes. */
93const LISTED_STOPS: Partial<Record<string, AgentRunState>> = { idle: 'idle', completed: 'done', failed: 'error', killed: 'aborted' }
94
95/**
96 * Closes the running and idle agents the engine lists as ended (a killed one has no turn.complete) and idles the running ones it
97 * lists idle; one an earlier list showed and this one drops is closed aborted, one never listed (a workflow's) stays as it was.
98 */
99export function noteListed(list: readonly AgentRun[], listed: readonly Pick<AgentInfo, 'id' | 'status'>[], now: number): AgentRun[] {
100 const stops = new Map(listed.map(info => [info.id, LISTED_STOPS[info.status]]))
101
102 return list.map(one => {
103 if (!stops.has(one.agentId)) {
104 return isOpen(one) && one.listed === true ? { ...one, state: 'aborted', endedAt: now, durationMs: elapsedOf(one, now) } : one
105 }
106
107 const state = stops.get(one.agentId)
108 const seen: AgentRun = one.listed === true ? one : { ...one, listed: true }
109
110 if (!isOpen(one) || state === undefined || (one.state === 'idle' && state === 'idle')) {
111 return seen
112 }
113
114 // Idle is no end: its clock stops until a message or a tool resumes it.
115 return state === 'idle' ? { ...seen, state, durationMs: elapsedOf(one, now) } : { ...seen, state, endedAt: now, durationMs: elapsedOf(one, now) }
116 })
117}
118
119export function stateOf(reason: TurnCompleteReason): AgentRunState {
120 return reason === 'answer' ? 'done' : reason
121}
122
123const baseName = (path: string) => path.split('/').filter(Boolean).pop() ?? path
124
125/** `Edit register.tsx`, `Bash git status`, or the bare tool name. */
126export function toolLabel(e: { tool: string; file_path?: unknown; command?: unknown }): string {
127 if ((e.tool === 'Read' || e.tool === 'Edit' || e.tool === 'Write') && typeof e.file_path === 'string') {
128 return `${e.tool} ${baseName(e.file_path)}`
129 }
130
131 if (e.tool === 'Bash' && typeof e.command === 'string') {
132 return `Bash ${e.command.replace(/\s+/g, ' ').trim().slice(0, 30)}`
133 }
134
135 return e.tool
136}
137
138/** `45s`, `27m`, `2h05m`, `3d`: an overview age, the seconds dropped past a minute. */
139export function fmtAge(ms: number): string {
140 const s = Math.max(0, Math.floor(ms / 1000))
141
142 if (s < 60) {
143 return `${s}s`
144 }
145
146 if (s < 3600) {
147 return `${Math.floor(s / 60)}m`
148 }
149
150 return s < 86_400 ? `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m` : `${Math.floor(s / 86_400)}d`
151}
152
153export function fmtDuration(ms: number): string {
154 const s = Math.max(0, Math.floor(ms / 1000))
155
156 if (s < 60) {
157 return `${s}s`
158 }
159
160 if (s < 3600) {
161 return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
162 }
163
164 return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
165}
166
167/** `950`, `9.4k`, `41k`, `182k`, `1.2M`: one decimal under 100k, none from there to a million; `—` when unknown. */
168export function fmtTokens(n: number | null | undefined): string {
169 if (n === null || n === undefined) {
170 return '—'
171 }
172
173 if (n < 1000) {
174 return `${n}`
175 }
176
177 if (n < 99_950) {
178 return `${Number((n / 1000).toFixed(1))}k`
179 }
180
181 return n < 999_500 ? `${Math.round(n / 1000)}k` : `${Number((n / 1_000_000).toFixed(1))}M`
182}
183
184export function glyphOf(state: AgentRunState): { glyph: string; color: string } {
185 if (state === 'running') {
186 return { glyph: '●', color: 'permission' }
187 }
188
189 if (state === 'idle') {
190 return { glyph: '○', color: 'inactive' }
191 }
192
193 // Cancelled by the person: a warning, red is for failures.
194 if (state === 'aborted') {
195 return { glyph: '⊘', color: 'warning' }
196 }
197
198 return state === 'done' ? { glyph: '✓', color: 'success' } : { glyph: '✗', color: 'error' }
199}
200
201export function elapsedOf(run: AgentRun, now: number): number {
202 return run.durationMs ?? (run.activeMs ?? 0) + now - (run.turnAt ?? run.startedAt)
203}
204
205/**
206 * Text after the glyph: `worker Build mm plugin 3m12s 41 tools Edit register.tsx`; `isCompact` drops the tool fields.
207 * `flight`, a call still running (`Bash 3m…`), stands in for the last tool.
208 */
209export function bandText(run: AgentRun, now: number, isCompact = false, flight?: string): string {
210 const parts = [run.subagentType, run.description, fmtDuration(elapsedOf(run, now))]
211
212 if (run.state === 'running') {
213 if (!isCompact) {
214 parts.push(`${run.tools} tools`)
215
216 if ((flight ?? run.lastTool) !== '') {
217 parts.push(flight ?? run.lastTool)
218 }
219 }
220 } else if (run.outputTokens !== undefined) {
221 parts.push(`${fmtTokens(run.outputTokens)} out`)
222 }
223
224 return parts.join(' ')
225}
226
227// East Asian Wide and Fullwidth ranges; emoji are told by their presentation instead.
228const WIDE_RANGES: readonly [number, number][] = [
229 [0x1100, 0x115f],
230 [0x2329, 0x232a],
231 [0x2e80, 0x303e],
232 [0x3041, 0x33ff],
233 [0x3400, 0x4dbf],
234 [0x4e00, 0x9fff],
235 [0xa000, 0xa4cf],
236 [0xa960, 0xa97f],
237 [0xac00, 0xd7a3],
238 [0xf900, 0xfaff],
239 [0xfe10, 0xfe19],
240 [0xfe30, 0xfe6f],
241 [0xff00, 0xff60],
242 [0xffe0, 0xffe6],
243 [0x16fe0, 0x16fe4],
244 [0x17000, 0x18cff],
245 [0x1aff0, 0x1b2ff],
246 [0x1f200, 0x1f2ff],
247 [0x20000, 0x2fffd],
248 [0x30000, 0x3fffd],
249]
250
251const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
252// Single character classes, so a grapheme of any length is scanned once.
253const PLAIN_ASCII = /^[\x20-\x7e]*$/
254const ZERO_WIDTH = /^[\p{M}\p{Default_Ignorable_Code_Point}]+$/u
255const EMOJI = /\p{Emoji_Presentation}|\p{Emoji}️/u
256
257const isWide = (char: string) => {
258 const codePoint = char.codePointAt(0) ?? 0
259
260 return WIDE_RANGES.some(([low, high]) => codePoint >= low && codePoint <= high)
261}
262
263/** Terminal cells a grapheme takes: 0 for marks and zero-width alone, 2 for an emoji or a wide character. */
264function cellsOf(grapheme: string): number {
265 if (ZERO_WIDTH.test(grapheme)) {
266 return 0
267 }
268
269 return EMOJI.test(grapheme) || [...grapheme].some(isWide) ? 2 : 1
270}
271
272/** Terminal cells `text` takes. */
273export function widthOf(text: string): number {
274 if (PLAIN_ASCII.test(text)) {
275 return text.length
276 }
277
278 let sum = 0
279
280 for (const { segment } of graphemes.segment(text)) {
281 sum += cellsOf(segment)
282 }
283
284 return sum
285}
286
287/** Cuts `text` to at most `columns` cells between graphemes, ending in `…` when cut. */
288export function fit(text: string, columns: number): string {
289 if (widthOf(text) <= columns) {
290 return text
291 }
292
293 if (columns <= 0) {
294 return ''
295 }
296
297 let used = 0
298 let out = ''
299
300 for (const { segment } of graphemes.segment(text)) {
301 const cells = cellsOf(segment)
302
303 if (used + cells > columns - 1) {
304 break
305 }
306
307 used += cells
308 out += segment
309 }
310
311 return `${out}…`
312}
313
314/** Calls a running agent's detail lists. */
315const PEEK_CALLS = 3
316const CALL_CHARS = 80
317// The first of these a call's input holds as a string is its summary.
318const ARG_KEYS = ['file_path', 'command', 'pattern', 'path', 'url', 'query', 'description', 'prompt', 'skill', 'subagent_type']
319
320const firstLine = (text: string) => text.split('\n').map(line => line.trim()).find(line => line !== '') ?? ''
321
322/** `Read board.ts`, `Bash bun test --watch`, `Grep isStalled`, or the bare tool name. */
323function callLine(tool: string, input: Record<string, unknown>): string {
324 const key = ARG_KEYS.find(one => typeof input[one] === 'string' && (input[one] as string).trim() !== '')
325
326 if (key === undefined) {
327 return tool
328 }
329
330 const value = String(input[key])
331 const arg = key === 'file_path' ? baseName(value) : value.replace(/\s+/g, ' ').trim()
332
333 return `${tool} ${arg}`.slice(0, CALL_CHARS)
334}
335
336/** A running agent's transcript in brief: the task it was given, its last three calls, the first line of its latest text. */
337export function peekOf(messages: readonly SessionMessage[]): { task: string; calls: string[]; text: string } {
338 const uses = messages.filter(one => one.role === 'assistant').flatMap(one => one.toolUses)
339
340 return {
341 task: firstLine(messages.find(one => one.role === 'user')?.text ?? ''),
342 calls: uses.slice(-PEEK_CALLS).map(use => callLine(use.tool, use.input)),
343 text: firstLine(messages.findLast(one => one.role === 'assistant' && one.text.trim() !== '')?.text ?? ''),
344 }
345}
346hooks/ask-recommended.tsx 82 lines1import type { EngineInterface, HookFailure, On } from 'claude-code'
2
3import { fit, widthOf } from './agent-model'
4import { failureLine } from './failures'
5import { t } from './i18n'
6
7// The dialog's width when no surface has measured it.
8const ASK_COLUMNS = 80
9
10// What each dialog's button does, by its call's tool_use_id. The engine documents requestId = tool_use_id only for ToolResult, so a lone pending dialog also answers a button whose id is not found.
11const presses = new Map<string, () => void>()
12
13const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
14
15/** Each question's one option whose label holds "(Recommended)", in order; null when any question has none or several. */
16export function recommendedLabels(questions: readonly unknown[]): string[] | null {
17 const labels = questions.map(one => {
18 const options = isRecord(one) && Array.isArray(one.options) ? (one.options as unknown[]) : []
19 const marked = options.map(option => (isRecord(option) ? option.label : undefined)).filter((label): label is string => typeof label === 'string' && label.includes('(Recommended)'))
20
21 return marked.length === 1 ? marked[0]! : null
22 })
23
24 return labels.length > 0 && labels.every(label => label !== null) ? (labels as string[]) : null
25}
26
27/** Makes call `id` a pending dialog: `pressed` resolves when its own button is pressed; `done` clears it. */
28export function awaitPress(id: string): { pressed: Promise<null>; done: () => void } {
29 let mine: () => void = () => undefined
30 const pressed = new Promise<null>(resolve => (mine = () => resolve(null)))
31
32 presses.set(id, mine)
33
34 return {
35 pressed,
36 done: () => {
37 if (presses.get(id) === mine) {
38 presses.delete(id)
39 }
40 },
41 }
42}
43
44/** A hook's `.catch`: its failure to the debug log, once per hook this load. Declared per file: validate follows $ into this file's functions only. */
45function hookFailed($: EngineInterface, name: string, error: HookFailure): void {
46 const line = failureLine(name, error)
47
48 if (line !== undefined) {
49 $.ui.log(line, { to: 'debug' })
50 }
51}
52
53export function registerAskRecommended(on: On): void {
54 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
55 const labels = recommendedLabels(e.props.questions)
56
57 if (labels === null) {
58 return next(e)
59 }
60
61 const { Box, Button, Text } = $.ui.resolve(e)
62 const label = t().useRecommended
63 const columns = (e.viewport?.columns ?? ASK_COLUMNS) - widthOf(label) - 5
64
65 return (
66 <Box flexDirection="column">
67 <Box columnGap={1}>
68 <Text color="subtle" wrap="truncate">
69 {fit(t().recommendedLine(labels), columns)}
70 </Text>
71 <Button key="ask-recommended" label={label} variant="secondary" onPress={() => (presses.get(e.requestId) ?? (presses.size === 1 ? [...presses.values()][0] : undefined))?.()} />
72 </Box>
73 {await next(e)}
74 </Box>
75 )
76 }).catch(($, e, next) => {
77 hookFailed($, 'ui.render AskUserQuestion', next.error)
78
79 return next(e)
80 })
81}
82hooks/board.ts 1417 lines1import type { SessionRateLimit } from 'claude-code'
2
3import type { AgentRun, AgentUsage, AskCounts, BoardNode, BoardRead, BoardRequest, BoardStatus, DashSeen, GateRun, MmModel, MmRun, MmSnapshot, SessionPresence, UsageCounts, WorktreeInfo } from '../types'
4import { bandText, elapsedOf, fit, fmtDuration, fmtTokens, glyphOf, widthOf } from './agent-model'
5import { t } from './i18n'
6import { elapsedSecs, fmtRunTokens, fmtSecs, isFailedModel, runLabel } from './runs'
7import { activityText, taskOfAgent, taskOfModel } from './tasks'
8import type { Flight } from './timeline'
9import { dayOf, isEmptyWeek } from './usage'
10import type { UsageWeek } from './usage'
11
12/** How long a finished item stays on the band, in ms. */
13export const FRESH_MS = 20_000
14export const MAX_BAND_ROWS = 5
15/** How long a command's failing gate stays pending unless the same command passes. */
16export const GATE_PENDING_MS = 30 * 60_000
17export const GATE_COMMAND_COLUMNS = 60
18export const RECENT_GATES = 5
19export const OVERVIEW_GATES = 3
20export const OVERVIEW_TREES = 5
21/** A running agent with no tool call ending for this long is marked quiet, unless a call it began is still running. */
22export const STALL_MS = 120_000
23/** Items the idle overview lists under its gray line. */
24const IDLE_RECENT = 3
25/** A session replying after a turn at least this long toasts. */
26export const LONG_TURN_MS = 120_000
27/** A session replied this long ago counts as idle: left open, not waiting on the person. */
28export const REPLIED_STALE_MS = 30 * 60_000
29const PEER_TITLE_COLUMNS = 40
30const DAY_MS = 86_400_000
31/** Other sessions' states kept as seen, so one back from silence does not toast again. */
32const PEER_TOAST_KEYS = 200
33// Band agent rows: the type column at most this wide, the time column this wide, a last tool kept this wide before the tool columns go.
34const TYPE_COLUMNS = 16
35const TIME_COLUMNS = 6
36const LAST_TOOL_COLUMNS = 12
37// Group ids; groupWord turns them into the band's words.
38const SESSIONS_GROUP = 'sessions'
39export const CACHE_GROUP = 'cache'
40const GATES_GROUP = 'gates'
41
42const ERROR = 'error'
43const INACTIVE = 'inactive'
44const PERMISSION = 'permission'
45const SUCCESS = 'success'
46const WARNING = 'warning'
47
48/** A time a segment shows, counted from `from` (epoch ms) at `now`: the desktop draws it as a Client keyed `key` that moves each second. */
49export type Live = { key: string; from: number; now: number; format: 'duration' | 'age' }
50export type Seg = { text: string; color?: string; bold?: boolean; dim?: boolean; live?: Live }
51export type Line = Seg[]
52
53/** 1 failed or denied and not yet seen, 2 ended within FRESH_MS, 3 running; null when off the band. */
54export type Tier = 1 | 2 | 3
55
56export type Counts = { pending: number; running: number; unread: number }
57
58/** Per tier, and apart the aborted agents (⊘ in the summary, not ✓) and the failed other sessions (✗, not !). */
59type Tally = Record<Tier, number> & { aborted: number; failed: number }
60
61/** `run`: an agent, drawn on the band in columns lined up with the other agents shown; `flight`, its call still running. */
62type Entry = { tier: Tier; startedAt: number; group: string; full: Line; compact: Line; counts: Tally; run?: AgentRun; flight?: Flight }
63
64/** Other sessions working, replied, and waiting on the person (asking a permission, failed or replied). */
65export type PeerCounts = { working: number; replied: number; waiting: number }
66
67export type Board = { entries: Entry[]; counts: Counts; peers: PeerCounts; now: number }
68
69const isFailedAgent = (run: AgentRun) => run.state === 'error' || run.state === 'refusal' || (run.denied ?? 0) > 0
70
71const isUnseen = (endedAt: number | undefined, seenAt: number) => endedAt === undefined || endedAt > seenAt
72
73const isFresh = (endedAt: number | undefined, now: number) => endedAt !== undefined && now - endedAt < FRESH_MS
74
75function agentTier(run: AgentRun, seen: DashSeen, now: number): Tier | null {
76 if (isFailedAgent(run) && (run.state === 'running' || isUnseen(run.endedAt, seen.agents))) {
77 return 1
78 }
79
80 if (run.state === 'running') {
81 return 3
82 }
83
84 return isFresh(run.endedAt, now) ? 2 : null
85}
86
87function modelTier(model: MmRun['models'][number], seen: DashSeen, now: number): Tier | null {
88 if (isFailedModel(model) && isUnseen(model.endedAt, seen.runs)) {
89 return 1
90 }
91
92 if (model.status === 'RUNNING') {
93 return 3
94 }
95
96 return isFresh(model.endedAt, now) ? 2 : null
97}
98
99type Bucket = keyof Counts
100
101export function agentBucket(run: AgentRun, seen: DashSeen, now: number): Bucket | null {
102 if (agentTier(run, seen, now) === 1) {
103 return 'pending'
104 }
105
106 if (run.state === 'running') {
107 return 'running'
108 }
109
110 // Not ended: nothing to read yet.
111 return run.state !== 'idle' && isUnseen(run.endedAt, seen.agents) ? 'unread' : null
112}
113
114export function modelBucket(model: MmRun['models'][number], seen: DashSeen, now: number): Bucket | null {
115 if (modelTier(model, seen, now) === 1) {
116 return 'pending'
117 }
118
119 if (model.status === 'RUNNING') {
120 return 'running'
121 }
122
123 return !isFailedModel(model) && isUnseen(model.endedAt, seen.runs) ? 'unread' : null
124}
125
126/** Quiet: running with no call ended for STALL_MS and, when the timeline knows, none in `flight`. */
127export const isStalled = (run: AgentRun, now: number, flight?: Flight) => flight === undefined && run.state === 'running' && now - run.lastActivityAt >= STALL_MS
128
129/** `Bash 3m…`: the call still running and for how long. */
130export const flightText = (flight: Flight, now: number) => `${flight.name} ${fmtAge(now - flight.requestedAt)}…`
131
132/**
133 * `● worker Build mm plugin 3m12s 41 tools Edit register.tsx`, ending in `✗ denied N` once a call was denied, then `quiet 2m00s` once quiet;
134 * a call in `flight` reads `Bash 3m…` in the last tool's place.
135 */
136export function agentLine(run: AgentRun, now: number, isCompact = false, flight?: Flight): Line {
137 const { glyph, color } = glyphOf(run.state)
138 const word = t().agentStates[run.state]
139 const line: Line = [{ text: glyph, color }, { text: ` ${bandText(run, now, isCompact, flight === undefined ? undefined : flightText(flight, now))}${word === '' ? '' : ` ${word}`}` }]
140
141 if ((run.denied ?? 0) > 0) {
142 line.push({ text: ' ' }, { text: t().denied(run.denied ?? 0), color: ERROR })
143 }
144
145 if (isStalled(run, now, flight)) {
146 line.push({ text: ' ' }, { text: t().quiet(fmtDuration(now - run.lastActivityAt)), color: WARNING })
147 }
148
149 return line
150}
151
152/** `review-ui · codex ● 7m12s · grok ✓ 5m02s · agy ✗ FAIL:1`, durations drawn against `polledAt`. */
153export function runLine(run: MmRun, polledAt: number): Line {
154 const line: Line = [{ text: runLabel(run) }]
155
156 for (const model of run.models) {
157 const secs = elapsedSecs(model, polledAt)
158 const time = secs === undefined ? '' : ` ${fmtSecs(secs)}`
159
160 if (model.status === 'RUNNING') {
161 line.push({ text: ` · ${model.name} ` }, { text: '●', color: PERMISSION }, { text: time })
162 } else if (model.status === 'DONE') {
163 line.push({ text: ` · ${model.name} ` }, { text: '✓', color: SUCCESS }, { text: time })
164 } else {
165 line.push({ text: ` · ${model.name} ` }, { text: '✗', color: ERROR }, { text: ` ${model.status}` })
166 }
167 }
168
169 return line
170}
171
172const noCounts = (): Tally => ({ 1: 0, 2: 0, 3: 0, aborted: 0, failed: 0 })
173
174/** A run with failing tests, or one its summary or exit called failed whatever it counted. */
175export const isFailedGate = (gate: GateRun) => (gate.fail ?? 0) > 0 || gate.failed === true
176
177/** `packages · ` before the counts of go packages. */
178const unitPrefix = (gate: GateRun) => (gate.unit === 'packages' ? `${t().packagesUnit} · ` : '')
179
180/** `22 pass · 2 fail`; `— pass` when no line gave a total, `failed` in place of a failure count none gave. */
181export const gateCounts = (gate: GateRun) => `${unitPrefix(gate)}${gate.pass ?? '—'} pass · ${gate.fail === null ? t().gateFailed : `${gate.fail} fail`}`
182
183/** The newest `count` runs, newest first. */
184export const recentGates = (gates: readonly GateRun[], count = RECENT_GATES) => gates.slice(-count).reverse()
185
186/**
187 * Each command's latest run in each tree, where that run failed within GATE_PENDING_MS, no edit in its tree came after,
188 * and its tree is the main one or still in `trees` (any while `trees` is null, before the first collection).
189 */
190export function pendingGates(gates: readonly GateRun[], now: number, trees: readonly WorktreeInfo[] | null = null): GateRun[] {
191 const latest = new Map(gates.map(gate => [`${gate.where}\n${gate.key ?? gate.command}`, gate]))
192 const isListed = (gate: GateRun) => gate.where === 'main' || trees === null || trees.some(tree => tree.name === gate.where)
193
194 return [...latest.values()].filter(gate => isFailedGate(gate) && gate.stale !== true && now - gate.at < GATE_PENDING_MS && isListed(gate))
195}
196
197// A leading `cd <dir> &&` (or `;`), or a `NAME=value` assignment, before the command proper.
198const COMMAND_LEAD = /^(?:cd\s+(?:'[^']*'|"[^"]*"|\S+)\s*(?:&&|;)|[A-Za-z_]\w*=(?:'[^']*'|"[^"]*"|\S*?)(?:\s*;|\s+))\s*/
199
200/** `bun test` of `cd /x && S=1; bun test`: the first line, the leading cd and assignments dropped, whitespace folded. */
201export function commandHead(command: string): string {
202 const [first = '', ...body] = command.trim().split('\n')
203 // A heredoc's opener alone reads the same for every script: its body's first line tells them apart.
204 const opened = /<<-?\s*['"]?\w+/.test(first) ? body.find(line => line.trim() !== '') : undefined
205 let head = `${first.trim()}${opened === undefined ? '' : ` ${opened.trim()}`}`
206
207 for (let lead = COMMAND_LEAD.exec(head); lead !== null && lead[0].length < head.length; lead = COMMAND_LEAD.exec(head)) {
208 head = head.slice(lead[0].length)
209 }
210
211 return head.replace(/\s+/g, ' ')
212}
213
214/** `2 fail`; `failed` when the run failed with nothing counted failing; else `186 pass`, `— pass` when no line gave a total. */
215export const gateOutcome = (gate: GateRun) => unitPrefix(gate) + ((gate.fail ?? 0) > 0 ? `${gate.fail} fail` : gate.failed === true ? t().gateFailed : `${gate.pass ?? '—'} pass`)
216
217/** `✗ gate claude plugin test plugins/dashboard · 2 fail`, then ` · agent-x` when it ran in a worktree. */
218function gateLine(gate: GateRun): Line {
219 const where = gate.where === 'main' ? '' : ` · ${gate.where}`
220
221 return [{ text: '✗', color: ERROR }, { text: ` ${t().gateLine(fit(gate.command, GATE_COMMAND_COLUMNS), gateOutcome(gate))}${where}` }]
222}
223
224/** The overview's needs-you row: `✗ gate claude plugin test plugins/dashboard · agent-x · 2 fail`, or `· failed` as gateOutcome words it. */
225export const pendingGateLine = (gate: GateRun): Line => [{ text: '✗', color: ERROR }, { text: ` ${t().gatePending(fit(gate.command, GATE_COMMAND_COLUMNS), gate.where, gateOutcome(gate))}` }]
226
227type PeerState = Exclude<SessionPresence['state'], 'idle' | 'ended'>
228
229export const PEER_WORDS: Record<PeerState, { glyph: string; color: string }> = {
230 permission: { glyph: '!', color: WARNING },
231 failed: { glyph: '✗', color: ERROR },
232 replied: { glyph: '?', color: WARNING },
233 working: { glyph: '●', color: PERMISSION },
234}
235
236/** Another session the overview lists. */
237export type ShownPeer = SessionPresence & { state: PeerState }
238
239const isShownPeer = (peer: SessionPresence): peer is ShownPeer => peer.state in PEER_WORDS
240
241const isStaleReply = (peer: SessionPresence, now: number) => peer.state === 'replied' && now - peer.since >= REPLIED_STALE_MS
242
243/** `! harness needs approval Bash · 3m05s`, or `✗ harness errored · 3m05s`. */
244function peerLine(peer: SessionPresence & { state: 'permission' | 'failed' }, now: number): Line {
245 const { glyph, color } = PEER_WORDS[peer.state]
246
247 return [{ text: glyph, color }, { text: ` ${[peer.name, t().peerWords[peer.state], peer.detail ?? ''].filter(part => part !== '').join(' ')} · ${fmtDuration(now - peer.since)}` }]
248}
249
250/** The main thread idle past the prompt cache's TTL: for how long, and the context tokens the next message rewrites when known. */
251export type ColdCache = { idleMs: number; tokens: number | null }
252
253/** `~ cache cold · idle 1h12m · next message rewrites ~182k tokens`. */
254function cacheLine(cold: ColdCache): Line {
255 return [{ text: t().cacheCold, color: WARNING }, { text: ` · ${t().cacheIdle(fmtDuration(cold.idleMs))}${cold.tokens === null ? '' : ` · ${t().cacheRewrite(fmtTokens(cold.tokens))}`}` }]
256}
257
258const LIMIT_NAMES: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
259
260/** `2h10m`, `3d4h` past a day. */
261// Whole minutes under an hour: nothing redraws the hint each second, so seconds would stand still.
262const fmtReset = (ms: number) =>
263 ms < 60_000 ? '<1m' : ms < 3_600_000 ? `${Math.floor(ms / 60_000)}m` : ms < DAY_MS ? fmtDuration(ms) : `${Math.floor(ms / DAY_MS)}d${Math.floor((ms % DAY_MS) / 3_600_000)}h`
264
265/** `5h 42% · resets in 2h10m`; the kind as the engine names it when not a known window, no reset when it gave none. */
266export function limitText(limit: SessionRateLimit, now: number): string {
267 const resetsAt = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
268 const name = `${LIMIT_NAMES[limit.kind] ?? limit.kind} ${limit.percentUsed}%`
269
270 return Number.isNaN(resetsAt) ? name : `${name} · ${t().limitReset(fmtReset(Math.max(0, resetsAt - now)))}`
271}
272
273/** When the band's pending gates next change with time alone: a gate's expiry; null when none will. */
274/** When the overview next changes with time alone: a running agent turning quiet, a failed gate leaving needs-you, a reply going stale; null for never. */
275export function nextOverviewChange(
276 agents: readonly AgentRun[],
277 gates: readonly GateRun[],
278 peers: readonly SessionPresence[],
279 now: number,
280 trees: readonly WorktreeInfo[] | null,
281 flights: ReadonlyMap<string, Flight>,
282): number | null {
283 const times = [
284 ...agents.filter(run => run.state === 'running' && flights.get(run.agentId) === undefined && !isStalled(run, now)).map(run => run.lastActivityAt + STALL_MS),
285 ...pendingGates(gates, now, trees).map(gate => gate.at + GATE_PENDING_MS),
286 ...peers.filter(peer => peer.state === 'replied' && !isStaleReply(peer, now)).map(peer => peer.since + REPLIED_STALE_MS),
287 ]
288
289 return times.length === 0 ? null : Math.min(...times)
290}
291
292export function nextBandChange(gates: readonly GateRun[], now: number, trees: readonly WorktreeInfo[] | null = null): number | null {
293 const times = pendingGates(gates, now, trees).map(gate => gate.at + GATE_PENDING_MS)
294
295 return times.length === 0 ? null : Math.min(...times)
296}
297
298/**
299 * What the band and the overview draw from; `peers` are the other sessions, `cold` this one's cold prompt cache, `flights` the agents' calls still running,
300 * `trees` the worktrees pendingGates keeps gates of. Rate limits are not drawn here: only PromptHint shows them.
301 */
302export function boardOf(
303 agents: readonly AgentRun[],
304 snap: MmSnapshot | null,
305 seen: DashSeen,
306 now: number,
307 gates: readonly GateRun[] = [],
308 peers: readonly SessionPresence[] = [],
309 cold: ColdCache | null = null,
310 flights: ReadonlyMap<string, Flight> = new Map(),
311 trees: readonly WorktreeInfo[] | null = null,
312): Board {
313 const entries: Entry[] = []
314 const counts: Counts = { pending: 0, running: 0, unread: 0 }
315 const tally: PeerCounts = { working: 0, replied: 0, waiting: 0 }
316
317 for (const peer of peers) {
318 // A failed turn waits on the person until that session's next prompt: no staleness, unlike a reply.
319 if (peer.state === 'permission' || peer.state === 'failed') {
320 const line = peerLine({ ...peer, state: peer.state }, now)
321
322 tally.waiting += 1
323 entries.push({ tier: 1, startedAt: peer.since, group: SESSIONS_GROUP, full: line, compact: line, counts: peer.state === 'failed' ? { ...noCounts(), failed: 1 } : { ...noCounts(), 1: 1 } })
324 } else if (peer.state === 'working') {
325 counts.running += 1
326 tally.working += 1
327 } else if (peer.state === 'replied' && !isStaleReply(peer, now)) {
328 tally.replied += 1
329 tally.waiting += 1
330 }
331 }
332
333 for (const gate of pendingGates(gates, now, trees)) {
334 const line = gateLine(gate)
335
336 counts.pending += 1
337 entries.push({ tier: 1, startedAt: gate.at, group: GATES_GROUP, full: line, compact: line, counts: { ...noCounts(), 1: 1 } })
338 }
339
340 for (const run of agents) {
341 const tier = agentTier(run, seen, now)
342 const bucket = agentBucket(run, seen, now)
343
344 if (bucket !== null) {
345 counts[bucket] += 1
346 }
347
348 if (tier !== null) {
349 const tally = tier === 2 && run.state === 'aborted' ? { ...noCounts(), aborted: 1 } : { ...noCounts(), [tier]: 1 }
350 const flight = flights.get(run.agentId)
351
352 entries.push({ tier, startedAt: run.startedAt, group: 'agents', full: agentLine(run, now, false, flight), compact: agentLine(run, now, true, flight), counts: tally, run, ...(flight !== undefined && { flight }) })
353 }
354 }
355
356 for (const run of snap?.runs ?? []) {
357 const tally = noCounts()
358 let best: Tier | null = null
359
360 for (const model of run.models) {
361 const tier = modelTier(model, seen, now)
362 const bucket = modelBucket(model, seen, now)
363
364 if (bucket !== null) {
365 counts[bucket] += 1
366 }
367
368 if (tier !== null) {
369 tally[tier] += 1
370 best = best === null ? tier : (Math.min(best, tier) as Tier)
371 }
372 }
373
374 if (best !== null) {
375 const line = runLine(run, snap?.polledAt ?? now)
376
377 entries.push({ tier: best, startedAt: run.createdAt, group: run.mode || 'mmrun', full: line, compact: line, counts: tally })
378 }
379 }
380
381 entries.sort((a, b) => a.tier - b.tier || a.startedAt - b.startedAt)
382
383 // Counted in no bucket nor tier: it is no work item, only a heads-up, so it comes last and is the first group dropped.
384 if (cold !== null) {
385 const line = cacheLine(cold)
386
387 entries.push({ tier: 2, startedAt: now - cold.idleMs, group: CACHE_GROUP, full: line, compact: line, counts: noCounts() })
388 }
389
390 return { entries, counts, peers: tally, now }
391}
392
393/** The counts joined by ` · ` within `columns`: running dropped first, then unread, then waiting; the last one left is cut. */
394function summaryLine(counts: Counts, waiting: number, columns: number): Line {
395 // `keep`: the higher, the longer it stays; the counts that need the person stay longest.
396 let parts = [
397 { keep: 3, line: counts.pending > 0 ? [{ text: t().pendingCount(counts.pending), color: ERROR }] : [] },
398 { keep: 0, line: counts.running > 0 ? [{ text: '●', color: PERMISSION }, { text: t().runCount(counts.running) }] : [] },
399 { keep: 1, line: counts.unread > 0 ? [{ text: t().unreadCount(counts.unread), bold: true }] : [] },
400 { keep: 2, line: waiting > 0 ? [{ text: t().waitingCount(waiting), color: WARNING }] : [] },
401 ].filter(part => part.line.length > 0)
402 const joined = () => parts.flatMap((part, i) => (i === 0 ? part.line : [{ text: ' · ' }, ...part.line]))
403
404 while (parts.length > 1 && lineWidth(joined()) > columns) {
405 const least = Math.min(...parts.map(part => part.keep))
406
407 parts = parts.filter(part => part.keep !== least)
408 }
409
410 return fitLine(joined(), columns)
411}
412
413const groupWord = (group: string) =>
414 group === SESSIONS_GROUP ? t().sessionsGroup : group === CACHE_GROUP ? t().cacheGroup : group === GATES_GROUP ? t().gatesGroup : group
415
416/** `agents ✗1 ●2 ✓1 ⊘1` per group, in the order its first entry comes, with the color of its worst tier; other sessions as `sessions ✗1 !1 ●2 ?1`. */
417function groupLines(entries: readonly Entry[], peers: PeerCounts): { line: Line; color: string }[] {
418 const groups = new Map<string, Tally>()
419
420 for (const entry of entries) {
421 const tally = groups.get(entry.group) ?? noCounts()
422
423 for (const key of [1, 2, 3, 'aborted', 'failed'] as const) {
424 tally[key] += entry.counts[key]
425 }
426
427 groups.set(entry.group, tally)
428 }
429
430 if (peers.working + peers.replied > 0) {
431 const tally = groups.get(SESSIONS_GROUP) ?? noCounts()
432
433 tally[3] += peers.working
434 groups.set(SESSIONS_GROUP, tally)
435 }
436
437 return [...groups].map(([group, tally]) => {
438 const line: Line = [{ text: groupWord(group) }]
439 const isSessions = group === SESSIONS_GROUP
440 let color: string | null = null
441
442 for (const [key, glyph, tone] of [['failed', '✗', ERROR], [1, isSessions ? '!' : '✗', isSessions ? WARNING : ERROR], [3, '●', PERMISSION], [2, '✓', SUCCESS], ['aborted', '⊘', WARNING]] as const) {
443 if (tally[key] > 0) {
444 line.push({ text: ' ' }, { text: glyph, color: tone }, { text: `${tally[key]}` })
445 color ??= tone
446 }
447 }
448
449 if (group === CACHE_GROUP) {
450 line.push({ text: ' ' }, { text: '~', color: WARNING })
451 color ??= WARNING
452 }
453
454 if (isSessions && peers.replied > 0) {
455 line.push({ text: ' ' }, { text: '?', color: WARNING }, { text: `${peers.replied}` })
456 color ??= WARNING
457 }
458
459 return { line, color: color ?? SUCCESS }
460 })
461}
462
463/** The groups joined by ` · ` within `columns`: whole groups dropped from the right, each leaving a `•`; the counts when not even one fits. */
464function summaryOf(entries: readonly Entry[], counts: Counts, peers: PeerCounts, columns: number): Line {
465 const groups = groupLines(entries, peers)
466
467 for (let kept = groups.length; kept >= 1; kept -= 1) {
468 const line: Line = groups.slice(0, kept).flatMap((group, i) => (i === 0 ? group.line : [{ text: ' · ' }, ...group.line]))
469
470 for (const dropped of groups.slice(kept)) {
471 line.push({ text: ' ' }, { text: '•', color: dropped.color })
472 }
473
474 if (widthOf(line.map(seg => seg.text).join('')) <= columns) {
475 return line
476 }
477 }
478
479 return summaryLine(counts, peers.waiting, columns)
480}
481
482/**
483 * The band's lines within `rows`: up to three entries whole; else failures alone in `rows - 1`
484 * and the rest on one summary line `columns` wide; with a single row, the counts.
485 */
486export function bandLines(board: Board, rows: number, columns: number): Line[] {
487 const { entries, counts, peers, now } = board
488
489 if (entries.length <= Math.min(rows, 3)) {
490 return entryLines(entries, now, columns, false)
491 }
492
493 if (rows <= 1) {
494 return [summaryLine(counts, peers.waiting, columns)]
495 }
496
497 const alone = entries.filter(entry => entry.tier === 1).slice(0, rows - 1)
498 const rest = entries.filter(entry => !alone.includes(entry))
499
500 return [...entryLines(alone, now, columns, true), ...(rest.length === 0 ? [] : [summaryOf(rest, counts, peers, columns)])]
501}
502
503/** The entries' lines, the agents among them in columns lined up with each other. */
504function entryLines(entries: readonly Entry[], now: number, columns: number, isCompact: boolean): Line[] {
505 const rows = agentRows(
506 entries.flatMap(entry => (entry.run === undefined ? [] : [{ run: entry.run, flight: entry.flight }])),
507 now,
508 columns,
509 isCompact,
510 )
511
512 return entries.map(entry => (entry.run === undefined ? (isCompact ? entry.compact : entry.full) : rows.get(entry.run)!))
513}
514
515type AgentCells = { glyph: Seg; type: string; title: string; time: string; tools: string; last: string; tail: Line }
516
517function cellsOf(run: AgentRun, now: number, flight: Flight | undefined): AgentCells {
518 const { glyph, color } = glyphOf(run.state)
519 const word = t().agentStates[run.state]
520 const isRunning = run.state === 'running'
521 const tail: Line = [
522 ...(word === '' ? [] : [{ text: ` ${word}` }]),
523 ...((run.denied ?? 0) > 0 ? [{ text: ' ' }, { text: t().denied(run.denied ?? 0), color: ERROR }] : []),
524 ...(isStalled(run, now, flight) ? [{ text: ' ' }, { text: t().quiet(fmtDuration(now - run.lastActivityAt)), color: WARNING }] : []),
525 ]
526
527 return {
528 glyph: { text: glyph, color },
529 type: run.subagentType,
530 title: run.description,
531 time: fmtDuration(elapsedOf(run, now)),
532 tools: isRunning ? `${run.tools} tools` : run.outputTokens === undefined ? '' : `${fmtTokens(run.outputTokens)} out`,
533 last: !isRunning ? '' : flight === undefined ? run.lastTool : flightText(flight, now),
534 tail,
535 }
536}
537
538const lineWidth = (line: Line) => widthOf(line.map(seg => seg.text).join(''))
539
540export const padTo = (text: string, columns: number) => text + ' '.repeat(Math.max(0, columns - widthOf(text)))
541
542export const alignRight = (text: string, columns: number) => ' '.repeat(Math.max(0, columns - widthOf(text))) + text
543
544/**
545 * `● worker Build mm plugin 3m12s 41 tools Edit register.tsx` per run: type and title padded to the widest shown,
546 * the time right-aligned in TIME_COLUMNS. When not all fits, the tools and last-tool columns go first, then the title is cut,
547 * then the type, a name left no cells going with its gap; then the tail is cut, the glyph and the time going last.
548 */
549function agentRows(shown: readonly { run: AgentRun; flight?: Flight | undefined }[], now: number, columns: number, isCompact: boolean): Map<AgentRun, Line> {
550 const runs = shown.map(one => one.run)
551 const cells = shown.map(one => cellsOf(one.run, now, one.flight))
552 const typeMax = Math.min(TYPE_COLUMNS, Math.max(0, ...cells.map(one => widthOf(one.type))))
553 const titleMax = Math.max(0, ...cells.map(one => widthOf(one.title)))
554 const toolsW = Math.max(0, ...cells.map(one => widthOf(one.tools)))
555 // The glyph and its space, the type, the gaps either side of the title, the time.
556 const fixed = 2 + typeMax + 2 + 2 + TIME_COLUMNS
557 const wideTail = (one: AgentCells) => (one.tools === '' ? 0 : 2 + toolsW) + (one.last === '' ? 0 : 2 + Math.min(widthOf(one.last), LAST_TOOL_COLUMNS)) + lineWidth(one.tail)
558 const isWide = !isCompact && fixed + titleMax + Math.max(0, ...cells.map(wideTail)) <= columns
559 const tailW = Math.max(0, ...cells.map(one => (isWide ? wideTail(one) : lineWidth(one.tail))))
560 // Cells for the names and the gap after each, between the glyph's and the time's.
561 const room = columns - 2 - TIME_COLUMNS - tailW
562 const typeW = Math.max(0, Math.min(typeMax, room - 2))
563 const titleW = Math.max(0, Math.min(titleMax, room - (typeW > 0 ? typeW + 2 : 0) - 2))
564
565 return new Map(
566 runs.map((run, i) => {
567 const one = cells[i]!
568 const hasMore = one.last !== '' || one.tail.length > 0
569 const names = [...(typeW > 0 ? [padTo(fit(one.type, typeW), typeW)] : []), ...(titleW > 0 ? [padTo(fit(one.title, titleW), titleW)] : [])]
570 const head: Line = [
571 one.glyph,
572 { text: ` ${[...names, alignRight(one.time, TIME_COLUMNS)].join(' ')}` },
573 ...(isWide && one.tools !== '' ? [{ text: ` ${hasMore ? padTo(one.tools, toolsW) : one.tools}` }] : []),
574 ]
575 // The last tool takes what the row leaves it, so the tail after it stays whole.
576 const lastW = columns - lineWidth(head) - 2 - lineWidth(one.tail)
577 const line: Line = [...head, ...(isWide && one.last !== '' ? [{ text: ' ' }, { text: fit(one.last, lastW), dim: true }] : []), ...one.tail]
578
579 return [run, fitLine(line, columns)]
580 }),
581 )
582}
583
584export type OverviewItem = { kind: 'agent'; run: AgentRun } | { kind: 'model'; run: MmRun; model: MmModel }
585
586export type Overview = {
587 /** Needs you: the pending bucket. */
588 pending: OverviewItem[]
589 /** Needs you too: the gates pendingGates gives. */
590 gates: GateRun[]
591 running: OverviewItem[]
592 /** Done: unread agents and unread mmrun models; an agent the person cancelled counts in `aborted` instead. */
593 returned: number
594 aborted: number
595 reviewed: number
596 /** The last IDLE_RECENT that ended, newest first. */
597 recent: OverviewItem[]
598 /** Other sessions: those asking a permission, then failed, then replied, then working, each oldest first. */
599 sessions: ShownPeer[]
600}
601
602const endedAtOf = (item: OverviewItem) => (item.kind === 'agent' ? item.run.endedAt : item.model.endedAt)
603
604/** The overview page's items, sorted into its sections. */
605export function overviewOf(
606 agents: readonly AgentRun[],
607 snap: MmSnapshot | null,
608 seen: DashSeen,
609 now: number,
610 peers: readonly SessionPresence[] = [],
611 gates: readonly GateRun[] = [],
612 trees: readonly WorktreeInfo[] | null = null,
613): Overview {
614 const order = Object.keys(PEER_WORDS)
615 const sessions = peers.filter(isShownPeer).filter(peer => !isStaleReply(peer, now)).sort((a, b) => order.indexOf(a.state) - order.indexOf(b.state) || a.since - b.since)
616 const overview: Overview = { pending: [], gates: pendingGates(gates, now, trees), running: [], returned: 0, aborted: 0, reviewed: 0, recent: [], sessions }
617 const ended: OverviewItem[] = []
618 const sort = (item: OverviewItem, bucket: Bucket | null) => {
619 if (bucket === 'unread') {
620 overview[item.kind === 'model' ? 'reviewed' : item.run.state === 'aborted' ? 'aborted' : 'returned'] += 1
621 } else if (bucket !== null) {
622 overview[bucket].push(item)
623 }
624
625 if (endedAtOf(item) !== undefined) {
626 ended.push(item)
627 }
628 }
629
630 for (const run of agents) {
631 sort({ kind: 'agent', run }, agentBucket(run, seen, now))
632 }
633
634 for (const run of snap?.runs ?? []) {
635 for (const model of run.models) {
636 sort({ kind: 'model', run, model }, modelBucket(model, seen, now))
637 }
638 }
639
640 overview.recent = ended.sort((a, b) => (endedAtOf(b) ?? 0) - (endedAtOf(a) ?? 0)).slice(0, IDLE_RECENT)
641
642 return overview
643}
644
645/** `worker · Build mm plugin` or `design / codex`. */
646export const itemTitle = (item: OverviewItem) => (item.kind === 'agent' ? `${item.run.subagentType} · ${item.run.description}` : `${runLabel(item.run)} / ${item.model.name}`)
647
648/** itemTail's two parts, either may be empty: the tools or a model's output tokens, and the time. */
649function tailParts(item: OverviewItem, now: number, polledAt: number): [string, string] {
650 if (item.kind === 'agent') {
651 return [`${item.run.tools} tools`, fmtDuration(elapsedOf(item.run, now))]
652 }
653
654 const secs = elapsedSecs(item.model, polledAt)
655
656 return [item.model.outputTokens === undefined ? '' : fmtRunTokens(item.model.outputTokens), secs === undefined ? '' : fmtSecs(secs)]
657}
658
659/** The running row's right end: `41 tools 3m12s`, or a model's output tokens and time. */
660export function itemTail(item: OverviewItem, now: number, polledAt: number): string {
661 return tailParts(item, now, polledAt)
662 .filter(part => part !== '')
663 .join(' ')
664}
665
666/**
667 * `status title` … `tail`, the tail ending at `columns`: the title is cut first, then the tail goes down to its last part;
668 * the status and that part go last.
669 */
670function edgeLine(status: Line, title: string, tail: readonly string[], columns: number): Line {
671 const statusW = lineWidth(status)
672 const whole = tail.filter(part => part !== '').join(' ')
673 const right = statusW + 1 + widthOf(whole) <= columns ? whole : (tail.at(-1) ?? '')
674 const room = columns - widthOf(right) - 1
675 // Under two cells, ` …` would stand for the title: the status goes on alone.
676 const head = fitLine(room >= statusW + 2 ? [...status, { text: ` ${title}` }] : status, room)
677 const gap = columns - lineWidth(head) - widthOf(right)
678
679 return fitLine([...head, { text: `${' '.repeat(Math.max(1, gap))}${right}` }], columns)
680}
681
682/** A needs-you row: the agent's compact band line, or the model's run line. */
683export const pendingLine = (item: OverviewItem, now: number, polledAt: number): Line =>
684 item.kind === 'agent' ? agentLine(item.run, now, true) : runLine({ ...item.run, models: [item.model] }, polledAt)
685
686/** `● running worker · Build mm plugin` … `41 tools 3m12s`, the tail ending at `columns`; a quiet agent, none of its calls in `flight`, reads `◐ quiet 2m00s`. */
687export function runningLine(item: OverviewItem, now: number, polledAt: number, columns: number, flight?: Flight): Line {
688 const status: Line =
689 item.kind === 'agent' && isStalled(item.run, now, flight)
690 ? [{ text: `◐ ${t().quiet(fmtDuration(now - item.run.lastActivityAt))}`, color: WARNING }]
691 : [{ text: '●', color: PERMISSION }, { text: ` ${t().runWord}` }]
692
693 return edgeLine(status, itemTitle(item), tailParts(item, now, polledAt), columns)
694}
695
696/** `harness · fix the band`, the title cut to 40 columns. */
697export const peerTitle = (peer: SessionPresence) => (peer.title === undefined ? peer.name : `${peer.name} · ${fit(peer.title, PEER_TITLE_COLUMNS)}`)
698
699/** An other-sessions row: `! needs approval harness · fix the band` … `3m05s`, the time ending at `columns`. */
700export function sessionLine(peer: ShownPeer, now: number, columns: number): Line {
701 const { glyph, color } = PEER_WORDS[peer.state]
702
703 return edgeLine([{ text: glyph, color }, { text: ` ${t().peerWords[peer.state]}` }], peerTitle(peer), [fmtDuration(now - peer.since)], columns)
704}
705
706const peerKey = (peer: SessionPresence) => `${peer.id}:${peer.state}:${peer.since}`
707
708/** A toast for another session: `ask` when it asks a permission or failed, `reply` when it replied. */
709export type PeerToast = { text: string; kind: 'ask' | 'reply' }
710
711/**
712 * Toasts for other sessions in `prev` that newly asked a permission, failed, or replied after a turn of LONG_TURN_MS or more,
713 * and `toasted` with every state of `next` added; a session not in `prev` (first read, or back from silence) only adds its state.
714 * `toasted` comes back null when nothing was added.
715 */
716export function peerToasts(toasted: readonly string[], prev: readonly SessionPresence[], next: readonly SessionPresence[]): { toasts: PeerToast[]; toasted: string[] | null } {
717 const known = new Set(toasted)
718 const fresh = next.filter(peer => !known.has(peerKey(peer)))
719 const toasts = fresh
720 .filter(peer => prev.some(was => was.id === peer.id))
721 .flatMap((peer): PeerToast[] => {
722 if (peer.state === 'permission') {
723 return [{ text: t().peerPermissionToast(peerTitle(peer), peer.detail ?? ''), kind: 'ask' }]
724 }
725
726 if (peer.state === 'failed') {
727 return [{ text: t().peerFailedToast(peerTitle(peer)), kind: 'ask' }]
728 }
729
730 const turn = peer.turnStartedAt === undefined ? 0 : peer.since - peer.turnStartedAt
731
732 return peer.state === 'replied' && turn >= LONG_TURN_MS ? [{ text: t().peerRepliedToast(peerTitle(peer), fmtDuration(turn), peer.detail ?? ''), kind: 'reply' }] : []
733 })
734
735 return { toasts, toasted: fresh.length === 0 ? null : [...toasted, ...fresh.map(peerKey)].slice(-PEER_TOAST_KEYS) }
736}
737
738/** `12m` of 12m40s: the idle line's coarse age. */
739function fmtAge(ms: number): string {
740 const s = Math.max(0, Math.floor(ms / 1000))
741
742 if (s < 60) {
743 return `${s}s`
744 }
745
746 if (s < 3600) {
747 return `${Math.floor(s / 60)}m`
748 }
749
750 return s < 86_400 ? `${Math.floor(s / 3600)}h` : `${Math.floor(s / 86_400)}d`
751}
752
753/** An ended item's glyph in its state's color, and its words: `worker returned`, `ui / kimi STALE`. */
754function endedOf(item: OverviewItem): { glyph: Seg; words: string } {
755 if (item.kind === 'agent') {
756 const { glyph, color } = glyphOf(item.run.state)
757
758 return { glyph: { text: glyph, color }, words: `${item.run.subagentType} ${t().agentStates[item.run.state]}` }
759 }
760
761 const { status } = item.model
762 const glyph: Seg = status === 'DONE' ? { text: '✓', color: SUCCESS } : status === 'STALE' ? { text: '~', color: WARNING } : { text: '✗', color: ERROR }
763
764 return { glyph, words: `${runLabel(item.run)} / ${item.model.name} ${status === 'DONE' ? t().agentStates.done : status}` }
765}
766
767/** The band with nothing on it, dim: `idle · last ✓ worker returned 12m ago · gate ✓ 186 pass 3m ago`, each part only when there is one. */
768export function idleLine(recent: OverviewItem | undefined, gate: GateRun | undefined, now: number): Line {
769 const line: Line = [{ text: t().idleBand, dim: true }]
770
771 if (recent !== undefined) {
772 const { glyph, words } = endedOf(recent)
773
774 line.push({ text: ` · ${t().idleLast} `, dim: true }, glyph, { text: ` ${words} ${t().gateAgo(fmtAge(now - (endedAtOf(recent) ?? now)))}`, dim: true })
775 }
776
777 if (gate !== undefined) {
778 const glyph: Seg = { text: isFailedGate(gate) ? '✗' : '✓', color: gate.stale === true ? INACTIVE : isFailedGate(gate) ? ERROR : SUCCESS }
779 const stale = gate.stale === true ? ` · ${t().gateStale}` : ''
780
781 line.push({ text: ` · ${t().gateWord} `, dim: true }, glyph, { text: ` ${gateOutcome(gate)}${stale} ${t().gateAgo(fmtAge(now - gate.at))}`, dim: true })
782 }
783
784 return line
785}
786
787/** `✓ worker · Build mm plugin · 12m00s ago`. */
788/** `✓ worker · Build mm plugin`: an ended item's glyph and title. */
789export function endedHead(item: OverviewItem): string {
790 const glyph = item.kind === 'agent' ? glyphOf(item.run.state).glyph : item.model.status === 'DONE' ? '✓' : '✗'
791
792 return `${glyph} ${itemTitle(item)}`
793}
794
795export const endedText = (item: OverviewItem, now: number) => `${endedHead(item)} · ${t().ago(fmtDuration(now - (endedAtOf(item) ?? now)))}`
796
797/** Cuts a line of segments to `columns` cells, ending in `…` when cut. */
798export function fitLine(line: Line, columns: number): Line {
799 if (widthOf(line.map(seg => seg.text).join('')) <= columns) {
800 return line
801 }
802
803 const out: Line = []
804 let left = columns
805
806 for (const seg of line) {
807 const width = widthOf(seg.text)
808
809 if (width < left) {
810 out.push(seg)
811 left -= width
812 continue
813 }
814
815 // The trailing `…` forces a cut even when this segment alone fits exactly, since more text follows it.
816 out.push({ ...seg, text: fit(`${seg.text}…`, left) })
817 break
818 }
819
820 return out
821}
822
823/** `! needs you 2 · ● running 1 · 3 unread · ⊘ aborted 1 · ✗ gates 1 · updated 3s ago`, the zero counts left out; empty when all are zero. */
824export function overviewCounts(overview: Overview, now: number, polledAt: number | undefined): Line {
825 const needsYou = overview.pending.length + overview.gates.length
826 const unread = overview.returned + overview.reviewed
827 const parts: Line[] = [
828 needsYou > 0 ? [{ text: '!', color: WARNING }, { text: ` ${t().countNeedsYou(needsYou)}` }] : [],
829 overview.running.length > 0 ? [{ text: '●', color: PERMISSION }, { text: ` ${t().countRunning(overview.running.length)}` }] : [],
830 unread > 0 ? [{ text: t().unreadCount(unread), bold: true }] : [],
831 overview.aborted > 0 ? [{ text: '⊘', color: WARNING }, { text: ` ${t().countAborted(overview.aborted)}` }] : [],
832 overview.gates.length > 0 ? [{ text: '✗', color: ERROR }, { text: ` ${t().countGates(overview.gates.length)}` }] : [],
833 ].filter(part => part.length > 0)
834
835 if (parts.length > 0 && polledAt !== undefined) {
836 parts.push([{ text: t().overviewUpdated(fmtDuration(now - polledAt)), dim: true }])
837 }
838
839 return parts.flatMap((part, i) => (i === 0 ? part : [{ text: ' · ' }, ...part]))
840}
841
842/** Cells a plain Button's hotkey takes before its label: `1: `. */
843export const HOTKEY_COLUMNS = 3
844
845/** A row drawn as `before`, a plain Button labelled `label`, then `after`. */
846export type ButtonRow = { before: Line; label: string; after: Line }
847
848const isPlainSeg = (seg: Seg) => seg.color === undefined && seg.dim !== true && seg.bold !== true
849
850/** The line's first run of unstyled text becomes the label, its edge spaces kept outside; the styled segments stay as they are. */
851export function splitRow(line: Line): ButtonRow {
852 const start = line.findIndex(seg => isPlainSeg(seg) && seg.text.trim() !== '')
853 let end = start
854
855 while (end < line.length && isPlainSeg(line[end]!)) {
856 end += 1
857 }
858
859 const text = line
860 .slice(start, end)
861 .map(seg => seg.text)
862 .join('')
863 const lead = text.slice(0, text.length - text.trimStart().length)
864 const trail = text.slice(text.trimEnd().length)
865
866 return {
867 before: [...line.slice(0, start), ...(lead === '' ? [] : [{ text: lead }])],
868 label: text.trim(),
869 after: [...(trail === '' ? [] : [{ text: trail }]), ...line.slice(end)],
870 }
871}
872
873// Tables: the gap between columns. On the Agents page, below TASK_MIN_COLUMNS task cells the tokens, model, call-in-flight, tools
874// and denied columns go, in that order.
875const GAP = ' '
876const TASK_MIN_COLUMNS = 12
877
878export type AgentRow = ButtonRow & { run: AgentRun; isDim: boolean }
879
880/** Input tokens all told: uncached, read from the cache, written to it. */
881const inputOf = (usage: AgentUsage) => usage.input + usage.cacheRead + usage.cacheWrite
882
883/** The Agents page's tokens: in plus out, `191k`; `—` with no usage known. */
884export const tokensText = (usage: AgentUsage | undefined) => fmtTokens(usage && inputOf(usage) + usage.output)
885
886/** `in 182k · cache read 91% · out 9.4k`. */
887export const usageText = (usage: AgentUsage) =>
888 t().usageLine(fmtTokens(inputOf(usage)), inputOf(usage) === 0 ? 0 : Math.round((usage.cacheRead / inputOf(usage)) * 100), fmtTokens(usage.output))
889
890/**
891 * The Agents page: a header `state type task model time tokens tools denied`, then per run the status cell, a label from
892 * the type to the tools, the denied cell and a call still running (`Bash 3m…`, dim); columns line up by display width,
893 * the hotkey's cells kept after the status.
894 */
895export function agentTable(runs: readonly AgentRun[], now: number, columns: number, flights: ReadonlyMap<string, Flight> = new Map()): { head: string; rows: AgentRow[] } {
896 const heads = t().agentColumns
897 const cells = runs.map(run => {
898 const flight = run.state === 'running' ? flights.get(run.agentId) : undefined
899 const task = taskOfAgent(run)
900
901 return {
902 glyph: glyphOf(run.state),
903 word: run.state === 'running' ? t().runWord : t().agentStates[run.state],
904 type: task.kind,
905 task: task.title,
906 model: task.model.replace(/^claude-/, ''),
907 time: fmtDuration(elapsedOf(run, now)),
908 tokens: tokensText(run.usage),
909 tools: `${task.tools ?? 0}`,
910 denied: (run.denied ?? 0) > 0 ? `✗${run.denied}` : '',
911 flight: flight === undefined ? '' : flightText(flight, now),
912 }
913 })
914 const widest = (head: string, of: (one: (typeof cells)[number]) => string) => Math.max(widthOf(head), ...cells.map(one => widthOf(of(one))))
915 const stateW = widest(heads.state, one => `${one.glyph.glyph} ${one.word}`)
916 const typeW = Math.min(TYPE_COLUMNS, widest(heads.type, one => one.type))
917 const taskMax = widest(heads.task, one => one.task)
918 const timeW = widest(heads.time, one => one.time)
919 const optional = {
920 tokens: widest(heads.tokens, one => one.tokens),
921 model: widest(heads.model, one => one.model),
922 // No head: the column is there only while a call runs.
923 flight: widest('', one => one.flight),
924 tools: widest(heads.tools, one => one.tools),
925 denied: widest(heads.denied, one => one.denied),
926 }
927 const shown = { tokens: true, model: true, flight: true, tools: true, denied: true }
928 const keys = ['tokens', 'model', 'flight', 'tools', 'denied'] as const
929 // The state, the gap and hotkey, the type, the gaps either side of the task, the time, and each optional column shown with its gap.
930 const fixed = () =>
931 stateW + GAP.length + HOTKEY_COLUMNS + typeW + 2 * GAP.length + timeW + keys.reduce((sum, key) => sum + (shown[key] && optional[key] > 0 ? GAP.length + optional[key] : 0), 0)
932
933 for (const key of keys) {
934 if (columns - fixed() >= TASK_MIN_COLUMNS) {
935 break
936 }
937
938 shown[key] = false
939 }
940
941 const taskW = Math.max(0, Math.min(taskMax, columns - fixed()))
942 // Past the task the type gives up its cells, then the state word; a column left no cells goes with its gap.
943 const typeFit = Math.max(0, Math.min(typeW, columns - fixed() + typeW + (taskW > 0 ? 0 : GAP.length)))
944 const isWord = typeFit > 0 || stateW + GAP.length + HOTKEY_COLUMNS + timeW <= columns
945 // Without the word: the glyph and a space.
946 const beforeW = isWord ? stateW + GAP.length : 2
947 const timeFit = Math.max(0, Math.min(timeW, columns - beforeW - HOTKEY_COLUMNS))
948 const labelOf = (type: string, task: string, model: string, time: string, tokens: string, tools: string) =>
949 [
950 ...(typeFit > 0 ? [padTo(fit(type, typeFit), typeFit)] : []),
951 ...(taskW > 0 ? [padTo(fit(task, taskW), taskW)] : []),
952 ...(shown.model ? [padTo(model, optional.model)] : []),
953 alignRight(fit(time, timeFit), timeFit),
954 ...(shown.tokens ? [alignRight(tokens, optional.tokens)] : []),
955 ...(shown.tools ? [alignRight(tools, optional.tools)] : []),
956 ].join(GAP)
957 const head = `${padTo(isWord ? heads.state : '', beforeW - GAP.length)}${GAP}${' '.repeat(HOTKEY_COLUMNS)}${[
958 labelOf(heads.type, heads.task, heads.model, heads.time, heads.tokens, heads.tools),
959 ...(shown.denied ? [heads.denied] : []),
960 ].join(GAP)}`
961
962 return {
963 head,
964 rows: runs.map((run, i) => {
965 const one = cells[i]!
966 const isDim = run.state === 'done'
967 const dim = isDim ? { dim: true } : {}
968 const label = labelOf(one.type, one.task, one.model, one.time, one.tokens, one.tools)
969 const isFlight = shown.flight && one.flight !== ''
970 // The flight cell lines up after the denied column, blank or not.
971 const pad = isFlight ? ' '.repeat(optional.denied - widthOf(one.denied)) : ''
972 const denied: Line = !shown.denied ? [] : one.denied !== '' ? [{ text: GAP }, { text: one.denied, color: ERROR, ...dim }, ...(pad === '' ? [] : [{ text: pad }])] : isFlight ? [{ text: `${GAP}${pad}` }] : []
973
974 return {
975 run,
976 isDim,
977 before: [
978 { text: one.glyph.glyph, color: one.glyph.color, ...dim },
979 { text: isWord ? `${padTo(` ${one.word}`, stateW - widthOf(one.glyph.glyph))}${GAP}` : ' ', ...dim },
980 ],
981 label,
982 after: [...denied, ...(isFlight ? [{ text: GAP }, { text: one.flight, dim: true }] : [])],
983 }
984 }),
985 }
986}
987
988/** The Agents page's rows: running, failed and unread (ended after `seenAt`) listed; the rest that ended folded. */
989export function agentFold(runs: readonly AgentRun[], seenAt: number): { listed: AgentRun[]; folded: AgentRun[] } {
990 const isListed = (run: AgentRun) => run.state === 'running' || isFailedAgent(run) || isUnseen(run.endedAt, seenAt)
991
992 return { listed: runs.filter(isListed), folded: runs.filter(run => !isListed(run)) }
993}
994
995/** The folded row: `✓4 done`, then `⊘1 aborted` when one was cancelled. */
996export function foldText(folded: readonly AgentRun[]): string {
997 const aborted = folded.filter(run => run.state === 'aborted').length
998 const done = folded.length - aborted
999
1000 return [done > 0 ? t().foldDone(done) : '', aborted > 0 ? `⊘${aborted} ${t().agentStates.aborted}` : ''].filter(part => part !== '').join(' · ')
1001}
1002
1003/** A model's glyph in its state's color: running, returned, lost contact, failed. */
1004function modelGlyph(model: MmModel): Seg {
1005 if (model.status === 'RUNNING') {
1006 return { text: '●', color: PERMISSION }
1007 }
1008
1009 return model.status === 'DONE' ? { text: '✓', color: SUCCESS } : model.status === 'STALE' ? { text: '~', color: WARNING } : { text: '✗', color: ERROR }
1010}
1011
1012/**
1013 * The Reviews page per run: a head `design · review aaaa proj`, then ` ● codex RUNNING 4m15s 25.8k tok` per model, the columns
1014 * lined up across every run shown, a running model's `3 tools · Bash` after them; a returned model's row dim.
1015 * All within `columns`: the activity is cut first, then the model name, then the tokens go.
1016 */
1017export function runTable(runs: readonly MmRun[], polledAt: number, columns: number): { run: MmRun; head: Line; rows: Line[] }[] {
1018 const models = runs.flatMap(run => run.models)
1019 const timeOf = (model: MmModel) => {
1020 const secs = elapsedSecs(model, polledAt)
1021
1022 return secs === undefined ? '' : fmtSecs(secs)
1023 }
1024 const tokOf = (model: MmModel) => fmtRunTokens(model.outputTokens)
1025 const widest = (of: (model: MmModel) => string) => Math.max(0, ...models.map(model => widthOf(of(model))))
1026 const nameW = widest(model => model.name)
1027 const statusW = widest(model => model.status)
1028 const timeW = widest(timeOf)
1029 const tokW = widest(tokOf)
1030 // The indent, the glyph and its space, the status, the time.
1031 const base = GAP.length + 2 + statusW + GAP.length + timeW
1032 const isTok = tokW > 0 && base + GAP.length + tokW <= columns
1033 const nameFit = Math.max(0, Math.min(nameW, columns - base - (isTok ? GAP.length + tokW : 0) - GAP.length))
1034
1035 return runs.map(run => {
1036 const dir = run.workdir.split('/').filter(Boolean).pop() ?? run.workdir
1037
1038 return {
1039 run,
1040 head: fitLine([{ text: `${run.tag || '-'} · ${run.mode}`, bold: true }, { text: `${GAP}${run.runid.slice(-4)}${GAP}${dir}`, dim: true }], columns),
1041 rows: run.models.map(model => {
1042 // The row marks no session: null leaves isThisSession out.
1043 const task = taskOfModel(run, model, null)
1044 const dim = model.status === 'DONE' ? { dim: true } : {}
1045 const text = [
1046 ...(nameFit > 0 ? [padTo(fit(task.provider, nameFit), nameFit)] : []),
1047 padTo(model.status, statusW),
1048 alignRight(timeOf(model), timeW),
1049 ...(isTok ? [alignRight(fmtRunTokens(task.outputTokens), tokW)] : []),
1050 ].join(GAP)
1051 const activity = activityText(task)
1052
1053 return fitLine(
1054 [{ text: GAP, ...dim }, { ...modelGlyph(model), ...dim }, { text: ` ${text}`.trimEnd(), ...dim }, ...(activity === '' ? [] : [{ text: `${GAP}${activity}`, dim: true }])],
1055 columns,
1056 )
1057 }),
1058 }
1059 })
1060}
1061
1062// Below this many columns each usage table keeps its name, its main figure and one more.
1063const USAGE_WIDE_COLUMNS = 60
1064
1065/** Rows of cells as aligned columns within `columns`: the first left-aligned and cut to the room the others leave, the rest right-aligned. */
1066function cellLines(rows: readonly string[][], columns: number): string[] {
1067 const widths = rows[0]!.map((_, i) => Math.max(...rows.map(row => widthOf(row[i]!))))
1068 const first = Math.max(1, Math.min(widths[0]!, columns - widths.slice(1).reduce((sum, one) => sum + GAP.length + one, 0)))
1069
1070 return rows.map(row => fit([padTo(fit(row[0]!, first), first), ...row.slice(1).map((cell, i) => alignRight(cell, widths[i + 1]!))].join(GAP), columns))
1071}
1072
1073/** The usage page's question lines: dialogs and questions, the share of questions by answer, the dialogs by wait. */
1074export function askLines(asks: AskCounts): string[] {
1075 const share = (n: number) => (asks.questions === 0 ? '—' : `${Math.round((n * 100) / asks.questions)}%`)
1076
1077 return [
1078 t().usageAsks(asks.dialogs, asks.questions),
1079 t().usageAskAnswers(share(asks.recommended), share(asks.option), share(asks.typed), share(asks.declined)),
1080 t().usageAskWaits(asks.under1m, asks.under2m, asks.under5m, asks.under10m, asks.over10m),
1081 ]
1082}
1083
1084/** The usage page as tables: the last 7 days newest first, the main thread against the subagents, the question dialogs, the skills by calls; then what it leaves out. */
1085export function usageLines(week: UsageWeek, columns: number): Line[] {
1086 if (isEmptyWeek(week)) {
1087 return [[{ text: fit(t().usageEmpty, columns), dim: true }]]
1088 }
1089
1090 const isWide = columns >= USAGE_WIDE_COLUMNS
1091 const heads = t().usageColumns
1092 const total = week.threads.reduce((sum, one) => sum + one.equivalent, 0)
1093 const share = (n: number) => (total > 0 ? `${Math.round((n * 100) / total)}%` : '—')
1094 // A day without a request recorded is unknown, not 0.
1095 const cells = (one: { counts: UsageCounts; equivalent: number }) =>
1096 [one.equivalent, ...(isWide ? [one.counts.input, one.counts.cacheRead, one.counts.cacheWrite] : []), one.counts.output].map(n => (one.counts.requests === 0 ? '—' : fmtTokens(n)))
1097 const plain = (text: string): Line => [{ text: fit(text, columns), dim: true }]
1098 const section = (title: string, rows: string[][]): Line[] => [
1099 [{ text: fit(title, columns), bold: true }],
1100 ...cellLines(rows, columns).map((text, i): Line => [{ text, ...(i === 0 && { dim: true }) }]),
1101 ]
1102
1103 return [
1104 ...section(t().usageWeekTitle, [
1105 isWide ? [heads.day, heads.equivalent, heads.input, heads.cacheRead, heads.cacheWrite, heads.output] : [heads.day, heads.equivalent, heads.output],
1106 ...week.days.map(one => [one.day.slice(5), ...cells(one)]),
1107 ]),
1108 ...t().usageWeights.map(plain),
1109 ...section(t().usageThreadsTitle, [
1110 [heads.thread, heads.requests, heads.equivalent, heads.share],
1111 ...week.threads.map(one => [t().usageThreads[one.thread], String(one.counts.requests), fmtTokens(one.equivalent), share(one.equivalent)]),
1112 ]),
1113 ...(week.asks.dialogs === 0 ? [] : [[{ text: fit(t().usageAsksTitle, columns), bold: true }], ...askLines(week.asks).map((text): Line => [{ text: fit(text, columns) }])]),
1114 ...(week.skills.length === 0
1115 ? []
1116 : section(`${t().usageSkillsTitle} · ${week.skills.length}`, [
1117 isWide ? [heads.skill, heads.calls, heads.inline, heads.forked, heads.errors] : [heads.skill, heads.calls, heads.errors],
1118 ...week.skills.map(one => [one.name, ...(isWide ? [one.invocations, one.inline, one.forked, one.errors] : [one.invocations, one.errors]).map(String)]),
1119 ])),
1120 ...t().usageCoverage.map(plain),
1121 ]
1122}
1123
1124/** Each status's theme key on the progress page. */
1125export const PROGRESS_COLORS: Record<BoardStatus, string> = { doing: PERMISSION, blocked: ERROR, todo: INACTIVE, done: SUCCESS, dropped: INACTIVE }
1126
1127const PROGRESS_ORDER: readonly BoardStatus[] = ['doing', 'blocked', 'todo', 'done']
1128
1129/** The progress page's groups in order, the empty ones and dropped nodes left out; each newest first. */
1130export function progressGroups(nodes: readonly BoardNode[]): { status: BoardStatus; nodes: BoardNode[] }[] {
1131 const newest = [...nodes].sort((a, b) => b.updatedAt - a.updatedAt)
1132
1133 return PROGRESS_ORDER.map(status => ({ status, nodes: newest.filter(one => one.status === status) })).filter(group => group.nodes.length > 0)
1134}
1135
1136const STALE_MS = 24 * 3_600_000
1137
1138/** Whole hours a doing node has gone without an update, 24 or more; else null. */
1139export function staleHours(node: BoardNode, now: number): number | null {
1140 return node.status === 'doing' && now - node.updatedAt >= STALE_MS ? Math.floor((now - node.updatedAt) / 3_600_000) : null
1141}
1142
1143/** A node's status theme key: a stale doing node's is inactive. */
1144export function progressColor(node: BoardNode, now: number): string {
1145 return staleHours(node, now) === null ? PROGRESS_COLORS[node.status] : INACTIVE
1146}
1147
1148/** `Done when: <done_when>` for a node not done that has one; else null. */
1149export function progressDoneWhen(node: BoardNode): string | null {
1150 return node.status === 'done' || node.done_when === '' ? null : t().progressDoneWhen(node.done_when)
1151}
1152
1153/** `feature · 2026-10-03 · builds on: Usage page, Ask reminder`: a node's kind, the day it last changed and what it extends; a stale node's hours without an update. */
1154export function progressMeta(node: BoardNode, nodes: readonly BoardNode[], now: number): string {
1155 const titles = node.builds_on.map(id => nodes.find(one => one.id === id)?.title ?? id)
1156 const hours = staleHours(node, now)
1157
1158 return [t().progressKinds[node.kind], dayOf(node.updatedAt), ...(titles.length === 0 ? [] : [t().progressBuildsOn(titles)]), ...(hours === null ? [] : [t().progressStale(hours)])].join(' · ')
1159}
1160
1161// The terminal progress page: lanes for this many lines, two cells each; pieces listed under a request, legacy nodes listed.
1162const LANES = 3
1163const LISTED_PIECES = 4
1164const LISTED_LEGACY = 10
1165// The rollup's most cells; the age column's width, `30d!` the widest.
1166const ROLLUP_CELLS = 8
1167const AGE_COLUMNS = 4
1168// Closed requests older than this fold into one line.
1169const CLOSED_SHOWN_MS = 7 * DAY_MS
1170const SUBTLE = 'subtle'
1171
1172/** Each piece status's glyph and theme key. */
1173export const PIECE_GLYPHS: Record<BoardStatus, Seg> = {
1174 todo: { text: '◌', color: SUBTLE },
1175 doing: { text: '▸', color: PERMISSION },
1176 done: { text: '✓', color: SUCCESS },
1177 blocked: { text: '⊘', color: ERROR },
1178 dropped: { text: '-', color: INACTIVE },
1179}
1180
1181/** A request's pieces not dropped, in the order they were added. */
1182export const requestPieces = (request: BoardRequest, nodes: readonly BoardNode[]) =>
1183 request.pieces.flatMap(id => nodes.filter(one => one.id === id && one.status !== 'dropped'))
1184
1185/** A request's glyph: closed ✓, dropped -, ready ?, else ⊘ with a blocked piece, ▸ with a doing one, ◌ with neither. */
1186export function requestGlyph(request: BoardRequest, nodes: readonly BoardNode[]): Seg {
1187 const pieces = requestPieces(request, nodes)
1188
1189 if (request.state === 'closed' || request.state === 'dropped') {
1190 return PIECE_GLYPHS[request.state === 'closed' ? 'done' : 'dropped']
1191 }
1192
1193 if (request.state === 'ready') {
1194 return { text: '?', color: WARNING }
1195 }
1196
1197 return PIECE_GLYPHS[pieces.some(one => one.status === 'blocked') ? 'blocked' : pieces.some(one => one.status === 'doing') ? 'doing' : 'todo']
1198}
1199
1200/** `<1m`, `12m`, `5h`, `3d`. */hooks/desktop.tsx 52 lines1import { agentCards } from './desktop/agents'
2import { detailBody } from './desktop/detail'
3import { gpuBody } from './desktop/gpu'
4import { tabs } from './desktop/kit'
5import type { El, PaneData } from './desktop/kit'
6import { overview } from './desktop/overview'
7import { progressBody } from './desktop/progress'
8import { runCards } from './desktop/reviews'
9import { timelineBody } from './desktop/timeline'
10import { usageBody } from './desktop/usage'
11
12export { drawDesktopBand } from './desktop/band'
13export { card, chip, MODEL_GLYPHS, modelTone, PIXELS_PER_COLUMN, posixQuote, textCells, widthTierOf } from './desktop/kit'
14export type { PaneData } from './desktop/kit'
15
16export function drawDesktopPaneError(el: El, data: Pick<PaneData, 'page' | 'pages' | 'onPage' | 'onClose'> & { message: string }) {
17 const { Box, Text } = el
18
19 return (
20 <Box flexDirection="column" rowGap={1}>
21 {tabs(el, data)}
22 <Text color="error" wrap="truncate">{`✗ ${data.message}`}</Text>
23 </Box>
24 )
25}
26
27export function drawDesktopPane(el: El, data: PaneData) {
28 const { Box } = el
29 const body =
30 detailBody(el, data) ??
31 (data.page === 'overview'
32 ? overview(el, data)
33 : data.page === 'agents'
34 ? agentCards(el, data)
35 : data.page === 'mmrun'
36 ? runCards(el, data)
37 : data.page === 'timeline'
38 ? timelineBody(el, data)
39 : data.page === 'usage'
40 ? usageBody(el, data)
41 : data.page === 'progress'
42 ? progressBody(el, data)
43 : gpuBody(el, data))
44
45 return (
46 <Box flexDirection="column" rowGap={1}>
47 {tabs(el, data)}
48 {body}
49 </Box>
50 )
51}
52hooks/desktop/gpu.tsx 195 lines1import type { RenderChildren } from 'claude-code'
2
3import { fmtAge, fmtDuration } from '../agent-model'
4import { MEMORY, ring } from '../desktop-svg'
5import { t } from '../i18n'
6import { card, gauge, iconOf, kpis } from './kit'
7import type { El, PaneData } from './kit'
8
9/** Fills `/gpu ` into the prompt; register.tsx passes it beside PaneData. */
10export type GpuFill = { onFillGpu?: () => void }
11
12const gib = (mib: number) => (mib / 1024).toFixed(1)
13const shortName = (name: string) => name.replace(/^NVIDIA /, '').replace(/^GeForce /, '')
14const pct = (n: number | null) => (n === null ? 'N/A' : `${n}%`)
15const RING_PX = 22
16
17/** One GPU's or the Tegra's numbers as its row draws them. */
18type Gauges = { title: string; meta: string; util: number | null; utilAlt: string; memFrac: number | null; memText: string; memAlt: string }
19
20export function gpuBody(el: El, data: PaneData & GpuFill) {
21 const { Box, Button, Input, Select, Svg, Text } = el
22 const watch = data.gpu
23 const now = data.now
24
25 if (watch === null) {
26 const hosts = data.gpuHosts ?? []
27 return [
28 card(el, [
29 <Box flexDirection="column" alignItems="center" rowGap={1} paddingY={1}>
30 {iconOf(el, 'gpu', 'idle', t().watchGpu, 32)}
31 <Text color="subtle" wrap="wrap">
32 {t().noHost}
33 </Text>
34 <Button key="gpu-fill" label={t().gpuFill} variant="secondary" onPress={() => data.onFillGpu?.()} />
35 </Box>,
36 ]),
37 <Box flexDirection="column" gap={1}>
38 {hosts.length > 0 && (
39 <Select
40 key="gpu-select-host"
41 label={t().gpuConfiguredHost}
42 options={hosts.map(h => ({ value: h, label: h }))}
43 onSelect={host => data.onConnectGpu?.(host)}
44 />
45 )}
46 <Input
47 key="gpu-input-host"
48 label={t().gpuSshHost}
49 placeholder="host"
50 submitLabel={t().connect}
51 onSubmit={host => data.onConnectGpu?.(host)}
52 />
53 </Box>,
54 ]
55 }
56
57 const isStale = watch.error !== null
58 const sample = watch.sample
59 // Stale numbers keep their values, dimmed.
60 const valueColor = isStale ? 'inactive' : 'text'
61 const staleLines = isStale
62 ? [
63 <Text color="warning" wrap="truncate-end">
64 {watch.okAt === null ? t().noSampleYet : t().gpuStaleAgo(fmtAge(now - watch.okAt))}
65 </Text>,
66 <Text color="subtle" wrap="truncate-end">{`✗ ${watch.error}`}</Text>,
67 ]
68 : []
69 const gpuCount = sample?.kind === 'nvidia' ? sample.gpus.length : sample?.kind === 'tegra' ? 1 : 0
70 const head = (
71 <Box flexDirection="row" columnGap={1} alignItems="center" justifyContent="space-between">
72 <Text color="text" bold wrap="truncate">
73 {watch.host}
74 </Text>
75 <Text color="subtle" wrap="truncate-end">
76 {[...(gpuCount === 0 ? [] : [`${gpuCount} GPU`]), ...(watch.okAt === null ? [] : [t().updatedAgo(fmtDuration(now - watch.okAt))])].join(' · ')}
77 </Text>
78 </Box>
79 )
80 const buttons = (
81 <Box flexDirection="row" columnGap={1}>
82 <Button key="gpu-change-host" label={t().changeHost} variant="secondary" onPress={() => data.onChangeGpuHost?.()} />
83 <Button key="gpu-refresh" label={t().refresh} variant="secondary" onPress={() => data.onConnectGpu?.(watch.host)} />
84 </Box>
85 )
86 const hostCard = (rows: RenderChildren[]) => [...staleLines, card(el, [head, ...rows, buttons])]
87
88 if (sample === null) {
89 return hostCard(isStale ? [] : [<Text color="subtle">{t().gpuConnecting(watch.host)}</Text>])
90 }
91
92 if (sample.kind === 'none' || sample.kind === 'error') {
93 return hostCard([<Text color="subtle">{sample.kind === 'none' ? t().gpuNone : sample.message}</Text>])
94 }
95
96 /** K2 in MEMORY: the kit's gauge takes a tone, and memory has a color of its own. */
97 const memoryRing = (frac: number | null, alt: string) => <Svg source={ring(frac, MEMORY, RING_PX, isStale)} alt={alt} width={RING_PX} height={RING_PX} />
98
99 /** A ring, its percent bold (dim while stale), its label subtle. */
100 const ringCell = (drawn: RenderChildren, value: string, label: string) => (
101 <Box flexDirection="row" columnGap={1} alignItems="center">
102 {drawn}
103 <Text color={valueColor} {...(!isStale && { bold: true })}>
104 {value}
105 </Text>
106 <Text color="subtle" wrap="truncate-end">
107 {label}
108 </Text>
109 </Box>
110 )
111
112 const row = (one: Gauges) => (
113 <Box flexDirection="column" rowGap={1}>
114 <Text wrap="truncate-end">
115 <Text color={valueColor} bold>
116 {one.title}
117 </Text>
118 {one.meta === '' ? null : <Text color="subtle">{` ${one.meta}`}</Text>}
119 </Text>
120 <Box flexDirection="row" columnGap={3} rowGap={1} flexWrap="wrap">
121 {ringCell(gauge(el, one.util === null ? null : one.util / 100, 'running', one.utilAlt, RING_PX, isStale), pct(one.util), t().gpuUtilLabel)}
122 {ringCell(memoryRing(one.memFrac, one.memAlt), one.memFrac === null ? 'N/A' : `${Math.round(one.memFrac * 100)}%`, t().vram(one.memText))}
123 </Box>
124 </Box>
125 )
126
127 const rows: Gauges[] =
128 sample.kind === 'tegra'
129 ? [
130 (() => {
131 const memFrac = sample.ramUsed !== null && sample.ramTotal !== null && sample.ramTotal > 0 ? sample.ramUsed / sample.ramTotal : null
132
133 return {
134 title: 'Tegra',
135 meta: sample.temp === null ? '' : `${Math.round(sample.temp)}°C`,
136 util: sample.util,
137 utilAlt: t().tegraUtilAlt(pct(sample.util), isStale),
138 memFrac,
139 memText: sample.ramUsed !== null && sample.ramTotal !== null ? `${gib(sample.ramUsed)} / ${gib(sample.ramTotal)} GiB` : 'N/A',
140 memAlt: t().tegraRamAlt(gib(sample.ramUsed ?? 0), gib(sample.ramTotal ?? 1), Math.round((memFrac ?? 0) * 100), isStale),
141 }
142 })(),
143 ]
144 : sample.gpus.map(one => {
145 const memFrac = one.memUsed !== null && one.memTotal !== null && one.memTotal > 0 ? one.memUsed / one.memTotal : null
146
147 return {
148 title: `GPU${one.index}`,
149 meta: [shortName(one.name), ...(one.temp === null ? [] : [`${one.temp}°C`]), ...(one.power === null ? [] : [`${Math.round(one.power)}W`])].join(' · '),
150 util: one.util,
151 utilAlt: t().gpuUtilAlt(one.index, pct(one.util), isStale),
152 memFrac,
153 memText: one.memUsed !== null && one.memTotal !== null ? `${gib(one.memUsed)} / ${gib(one.memTotal)} GiB` : 'N/A',
154 memAlt: t().gpuMemAlt(one.index, gib(one.memUsed ?? 0), gib(one.memTotal ?? 1), Math.round((memFrac ?? 0) * 100), isStale),
155 }
156 })
157
158 // The tiles: the mean of the utilizations known, memory used over the total known; a value unknown is `—`, never 0.
159 const utils = rows.flatMap(one => (one.util === null ? [] : [one.util]))
160 const mems = sample.kind === 'tegra' ? (sample.ramUsed !== null && sample.ramTotal !== null ? [[sample.ramUsed, sample.ramTotal]] : []) : sample.gpus.flatMap(one => (one.memUsed !== null && one.memTotal !== null ? [[one.memUsed, one.memTotal]] : []))
161 const memTotal = mems.reduce((sum, [, total]) => sum + (total ?? 0), 0)
162 const utilTile = utils.length === 0 ? '—' : `${Math.round(utils.reduce((sum, n) => sum + n, 0) / utils.length)}%`
163 const memTile = memTotal <= 0 ? '—' : `${Math.round((mems.reduce((sum, [used]) => sum + (used ?? 0), 0) * 100) / memTotal)}%`
164 const tiles = kpis(el, [
165 { label: t().gpuKpiHosts, value: '1', color: valueColor, isZero: false },
166 { label: t().gpuKpiGpus, value: String(rows.length), color: valueColor, isZero: rows.length === 0 },
167 { label: t().gpuUtilLabel, value: utilTile, color: isStale ? 'inactive' : 'permission', isZero: utilTile === '—' },
168 { label: t().gpuVramLabel, value: memTile, color: valueColor, isZero: memTile === '—' },
169 ])
170
171 const procs = sample.kind === 'nvidia' ? [...sample.procs].sort((a, b) => (b.memMiB ?? 0) - (a.memMiB ?? 0)).slice(0, 5) : []
172 const top5 =
173 procs.length === 0
174 ? []
175 : [
176 <Text color={valueColor} bold>
177 {t().topProcs}
178 </Text>,
179 ...procs.map(one => (
180 <Box flexDirection="row" columnGap={1} justifyContent="space-between">
181 <Box flexShrink={1} minWidth={0}>
182 <Text color="subtle" wrap="truncate-end">
183 {one.name}
184 </Text>
185 </Box>
186 <Box flexShrink={0}>
187 <Text color="subtle">{`${one.memMiB === null ? 'N/A' : `${gib(one.memMiB)} GiB`} · PID ${one.pid}`}</Text>
188 </Box>
189 </Box>
190 )),
191 ]
192
193 return [...staleLines, tiles, card(el, [head, ...rows.map(row), ...top5, buttons])]
194}
195