Side pane that shows running subagents and workflows as a live tree

A side pane for Claude Code that shows your subagents and workflows as a live tree. You see who is running, what each agent is doing now, how long it took and how many tokens it used. When a run ends, it moves to History, where you can replay it as a timeline or a trace.

Type this at the Claude Code prompt:
/plugin install agent-tree --marketplace SeanoChang/agent-tree
Answer y to add the marketplace, then pick a scope (user scope loads it in every session). The pane is active at once; no restart is needed.
Open the pane with /agent-tree. It also opens by itself when a subagent starts and the terminal is at least 144 columns wide.
Needs: a Claude Code build that runs function-hook mods (tested on 2.1.292). Optional: rsvg-convert (brew install librsvg) to save PNG pictures.
| View | What you get |
|---|---|
| Tree | Each run with its agents nested under it: status, the current step, model, tokens and time |
| Timeline | One bar per agent. The critical path (the chain of agents that set the end time) is heavy, and dots mark idle time |
| Trace | One lane per agent, with every tool call, edit and hand-back in order. Search it with /, jump between problems with n p |
| Board | Agents grouped by status |
| History | The last 150 runs across sessions, per repo, with a short report for each |
More:
m on two runs, or = to compare a run with its last run of the same work. You see time, idle time, tokens by model, failures, tool calls and the files each run changed.x saves the open Timeline or Trace as SVG (and PNG) in ~/Downloads/agent-tree/.
Click the pane (or press ctrl+x tab) to give it the keyboard. ? lists every key.
Arrows move inside one zone at a time, like a TV remote. In the content, ↑ ↓ move and ← → fold. To switch a tab or a view, press ↑ on the top row to reach the bar, then ← →. Direct keys work from anywhere: 1 2 for Live and History, v for the next view, ? for help.
Run /plugin, pick agent-tree, and set:
| Option | Values | Default |
|---|---|---|
theme | minimal (plain glyphs, any terminal), kitty, fish, dog (colours and emoji) | minimal |
ai | off (no model calls), cheap (Haiku writes run reports and titles), full (also Sonnet on demand: e explains a run, g finds patterns in History) | cheap |
The cheap and full modes make model calls on your account. Set ai to off if you do not want that.
The mod listens to Claude Code's hook events (agent spawn, tool calls, turn end) and keeps live runs in session state and History in the plugin store. It reads subagent transcripts only when you open a trace. See docs/ARCHITECTURE.md for the data flow and the key map.
git clone https://github.com/SeanoChang/agent-tree && cd agent-tree
claude --plugin-dir . # run it from the folder
claude plugin validate .
claude plugin test .
Issues and ideas are welcome: open an issue or a discussion. A screenshot of the pane helps most.
MIT. See LICENSE.
hooks/register.tsx 1293 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register, Timer } from 'claude-code'
3
4import type { AgentNode, EditRecord, NodeStatus, PatternsDoc, Report, TraceRow, TraceView, TraceZoom, ViewProps } from '../types'
5import { themeNameOf, themeOf, type ThemeName } from './theme'
6import {
7 changesLine, cleanTitle, describeTool, diffCounts, editRecords, editedPath, fileRows, firstPrompt, firstSentence, handbackOf, fitView,
8 lineDiff, parseJournal, pipeline, scopeNodes, transcriptEdits, folderKey, runKey,
9} from './list'
10import { PART_TOKENS, REPORT_SYSTEM, REPORT_TOKENS, isRawReport, kTokens, parseReport, partInput, runInput } from './report'
11import { ZOOMS, buildTrace, finishParse, newParse, onlyLane, parseLines, traceHits, traceMarks, traceWindow, type TraceEvent } from './trace'
12import {
13 AI_MODES, EXPLAIN_SYSTEM, PATTERNS_SYSTEM, STORY_SYSTEM, TIER_NAME, aiAllows, explainInput, parseBrief, parsePatterns,
14 parseStory, patternsInput, storyInput, type AiMode, type Tier,
15} from './ai'
16import { criticalPath, idleGaps, insights, timelineRows } from './lens'
17import { DESK, pictureSvg, timelineHeight, timelineSvg, traceSvg, type TimeBar } from './desktop/svg'
18// phase 6: the desktop's own native view, drawn from the same data
19import { drawDesktop } from './desktop/pane'
20import { DESK_DEFAULT, deskUi } from './desktop/state'
21
22const PANE = 'agent-tree'
23// Bumped when the view module's props or state change shape: a new key mounts a
24// fresh instance, where the old one would carry its state into the new code.
25const VIEW_KEY = 'tree-v7'
26// A view that failed (one draw over its budget, a throw) is not drawn again under
27// its key, so each failure moves it to a new key: at most FAULT_RETRIES in
28// FAULT_WINDOW, after which it waits for a reload as before.
29const FAULT_RETRIES = 3
30const FAULT_WINDOW = 10 * 60_000
31let viewGen = 0
32let faultsAt: number[] = []
33const viewKey = () => (viewGen ? `${VIEW_KEY}-${viewGen}` : VIEW_KEY)
34const TITLE = 'Agents'
35const HISTORY = 'history'
36const HISTORY_RUNS = 150
37const nodes = atom({ plugin: 'agent-tree', key: 'nodes' } as const, [])
38const edits = atom({ plugin: 'agent-tree', key: 'edits' } as const, [])
39// The last wheel move over the pane, which the view applies once per seq.
40const wheel = atom({ plugin: 'agent-tree', key: 'wheel' } as const, { seq: 0, by: 0 })
41// The look chosen in /config, read from the options at each load.
42let themeName: ThemeName = 'minimal'
43// What the AI layer may do, from /config: off, cheap (Haiku) or full (Haiku, and Sonnet on demand).
44let aiMode: AiMode = 'cheap'
45// A new seq redraws the pane after an AI block was written where the view does not subscribe (the store).
46const aiSeq = atom({ plugin: 'agent-tree', key: 'ai' } as const, { seq: 0 })
47// Runs whose brief Sonnet is writing, whether patterns are being written, agents whose story is.
48const explaining = new Set<string>()
49let patternsBusy = false
50const storying = new Set<string>()
51const AI_SPEND = 'aiSpend'
52const PATTERNS = 'patterns'
53const WEEK = 7 * 86_400_000
54const EDITS = 'edits'
55const EDITS_KEPT = 400
56const EDIT_TEXT = 6000
57// The file the Changes view has open: only its edits travel to the view.
58let diffPath: string | null = null
59// where this session keeps subagent transcripts, learned from a Stop event or a workflow's folder
60let subagentsDir: string | undefined
61const backfilled = new Set<string>()
62
63// ── the trace the view has open ─────────────────────────────────────────────
64// What the view asked for: which run, how close, and where it reads.
65// `lane` cuts the rows to one agent's lane; `query` is a search the rows are matched against.
66let traceReq: { run: string; zoom: TraceZoom; offset: number; lane?: string; query?: string } | null = null
67// The run's trace as last built (all its rows), and the window the view gets.
68let traceBuilt: { key: string; at: number; lanes: TraceView['lanes']; rows: TraceRow[]; missing: number; storyBy?: string } | undefined
69let traceSnap: TraceView | undefined
70let tracer: Timer | undefined
71// A new seq redraws the pane after the trace was read again.
72const traceSeq = atom({ plugin: 'agent-tree', key: 'trace' } as const, { seq: 0 })
73// phase 6: what the desktop view has open (its tab, run, item, view, filters)
74const desk = atom({ plugin: 'agent-tree', key: 'desk' } as const, DESK_DEFAULT)
75// Each transcript's events, kept while its file does not change; a running agent's
76// file is read again at most every few seconds.
77const transcripts = new Map<string, { size: number; mtimeMs: number; checkedAt: number; events: TraceEvent[] }>()
78// Where each agent's transcript is: a path, or null once looked for and not found.
79const transcriptAt = new Map<string, string | null>()
80// $.fs.read takes files up to 4 MiB; bigger ones are read in 3 MiB pieces with dd.
81const READ_CAP = 3 * 1024 * 1024
82const DD_BLOCK = 65_536
83const DD_BLOCKS = READ_CAP / DD_BLOCK
84const TRACE_WINDOW = 60
85const TRACE_TEXT = 120
86
87// Agent tool calls seen in any loop. A spawn whose tool_use_id is not here
88// came from somewhere else (a workflow run), so it is filed under that run.
89const agentCalls = new Set<string>()
90// Each Agent call's `isolation`, read when its spawn arrives.
91const isolationOf = new Map<string, 'worktree' | 'remote'>()
92const digesting = new Set<string>()
93// Each finished run's whole answer, held until its report is written: the node
94// keeps only its start, and a report read from that start calls the work unfinished.
95const answers = new Map<string, string>()
96const ANSWERS_HELD = 50
97const holdAnswer = (id: string, text: string | undefined) => {
98 if (!text) return
99 answers.delete(id)
100 answers.set(id, text)
101 for (const old of answers.keys()) { if (answers.size <= ANSWERS_HELD) break; answers.delete(old) }
102}
103let reconciler: Timer | undefined
104let poller: Timer | undefined
105const titling = new Set<string>()
106// The main loop's current turn, from the last prompt it took: its subagents form one group.
107let turn: string | undefined
108const TITLE_CONCURRENCY = 4
109
110const AGENT_TOOLS = new Set(['Agent', 'Task'])
111const excerpt = (s: string | undefined, n = 400) => (s ? s.slice(0, n) : undefined)
112// A node's kept answer: its start, and its whole length when that start is all it keeps.
113// An empty answer keeps what the node had; a new answer drops an old length.
114const withResult = (n: AgentNode, s: string | undefined, cap = 400): AgentNode => {
115 if (!s) return n
116 const { resultLength: _old, ...rest } = n
117 return { ...rest, result: s.slice(0, cap), ...(s.length > cap ? { resultLength: s.length } : {}) }
118}
119const scriptField = (script: string | undefined, field: string) =>
120 new RegExp(`${field}:\\s*['"]([^'"]+)['"]`).exec(script ?? '')?.[1]
121
122const runningWorkflow = (list: AgentNode[]) =>
123 [...list].reverse().find(n => n.kind === 'workflow' && n.status === 'running')
124
125const patch = ($: Engine, id: string, fn: (n: AgentNode) => AgentNode) =>
126 update($, nodes, list => list.map(n => (n.id === id ? fn(n) : n)))
127
128const finish = (status: NodeStatus, at: number) => (n: AgentNode): AgentNode =>
129 n.status === 'running' ? { ...n, status, endedAt: at } : n
130
131const statusOf = (word: string | undefined): NodeStatus =>
132 word === 'failed' ? 'failed' : word === 'killed' ? 'killed' : 'done'
133
134async function add($: Engine, node: AgentNode) {
135 await update($, nodes, list => [...list.filter(n => n.id !== node.id), node].slice(-400))
136 ensureTimers($)
137 // Unasked opens wait for a wide terminal; a refusal here must not fail the spawn.
138 void $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
139}
140
141function ensureTimers($: Engine) {
142 reconciler ??= $.clock.every(5000, () => void reconcile($))
143 poller ??= $.clock.every(2000, () => void pollJournals($))
144}
145
146// $.agent.list() is the engine's own record of subagent status. It catches
147// ends no event reported (a killed background agent). Workflow agents are not listed.
148async function reconcile($: Engine) {
149 const at = await $.clock.now()
150 const listed = new Map((await $.agent.list()).map(a => [a.id, a]))
151 await update($, nodes, list =>
152 list.map(n => {
153 const info = listed.get(n.id)
154 if (!info || n.status !== 'running' || info.status === 'running') return n
155 return { ...n, status: statusOf(info.status === 'completed' ? 'done' : info.status), endedAt: at }
156 }),
157 )
158 await settleGroups($)
159 await archive($)
160 if (!(await read($, nodes)).some(n => n.status === 'running')) {
161 reconciler?.cancel()
162 reconciler = undefined
163 }
164}
165
166// A workflow's transcript folder says exactly which agents are its own, under
167// which script label and phase, on what type and model, and when each ended.
168async function pollJournals($: Engine) {
169 const wfs = (await read($, nodes)).filter(n => n.kind === 'workflow' && n.status === 'running' && n.transcriptDir)
170 if (wfs.length === 0) {
171 poller?.cancel()
172 poller = undefined
173 return
174 }
175 for (const wf of wfs) await syncJournal($, wf)
176 void titleAgents($)
177}
178
179async function syncJournal($: Engine, wf: AgentNode) {
180 const dir = wf.transcriptDir
181 if (!dir) return
182 const text = await $.fs.read(`${dir}/journal.jsonl`).catch(() => '')
183 const entries = parseJournal(text)
184 if (entries.length === 0) return
185 const at = await $.clock.now()
186 const list = await read($, nodes)
187 const known = new Map(list.map(n => [n.id, n]))
188 const fresh: AgentNode[] = []
189 for (const j of entries) {
190 const n = known.get(j.agentId)
191 if (n && n.tag !== undefined && n.type !== undefined && n.prompt !== undefined && (!j.isDone || n.status !== 'running')) continue
192 const meta = n?.type === undefined
193 ? await $.fs.read(`${dir}/agent-${j.agentId}.meta.json`).then(t => JSON.parse(t) as { agentType?: string; model?: string }).catch(() => undefined)
194 : undefined
195 const prompt = n?.prompt ?? firstPrompt(await $.fs.read(`${dir}/agent-${j.agentId}.jsonl`).catch(() => ''))
196 fresh.push({
197 ...(n ?? { id: j.agentId, kind: 'agent', label: j.label ?? `agent ${j.agentId.slice(0, 6)}`, status: 'running', startedAt: at, tools: 0 }),
198 parentId: wf.id,
199 tag: j.label ?? n?.tag,
200 phase: j.phase ?? n?.phase,
201 type: n?.type ?? meta?.agentType,
202 model: n?.model ?? meta?.model,
203 prompt: excerpt(prompt),
204 ...(j.isDone && n?.status === 'running' ? { status: 'done' as const, endedAt: at } : {}),
205 ...(j.isDone && !n ? { status: 'done' as const, endedAt: at } : {}),
206 })
207 }
208 const phases = [...new Set(entries.map(j => j.phase).filter((p): p is string => !!p))]
209 await update($, nodes, all => {
210 const byId = new Map(fresh.map(f => [f.id, f]))
211 const merged = all.map(n => byId.get(n.id) ?? (n.id === wf.id ? { ...n, phases } : n))
212 const added = fresh.filter(f => !all.some(n => n.id === f.id))
213 return [...merged, ...added].slice(-400)
214 })
215}
216
217// A group runs while any member runs. When the last one ends, the group ends with
218// it, gets one digest of all their reports and one toast, and moves to History.
219async function settleGroups($: Engine) {
220 const list = await read($, nodes)
221 for (const g of list.filter(n => n.kind === 'group' && n.status === 'running')) {
222 const kids = list.filter(k => k.parentId === g.id)
223 if (kids.length === 0 || kids.some(k => k.status === 'running')) continue
224 const status: NodeStatus = kids.some(k => k.status === 'failed') ? 'failed' : kids.every(k => k.status === 'killed') ? 'killed' : 'done'
225 const endedAt = Math.max(...kids.map(k => k.endedAt ?? g.startedAt))
226 const tokens = kids.reduce((a, k) => a + (k.tokens ?? 0), 0)
227 await patch($, g.id, x => ({ ...x, status, endedAt, tokens: tokens || undefined }))
228 void digest($, g.id)
229 await announce($, g.id)
230 }
231}
232
233// Subagents the main loop spawns in one turn are one piece of work. Once a turn has
234// two, they move into a group; later ones join it. One atomic update, so spawns that
235// land together (parallel Agent calls) all end up inside.
236async function regroup($: Engine, t: string): Promise<string | undefined> {
237 const id = `grp:${t}`
238 let isGrouped = false
239 await update($, nodes, all => {
240 const strays = all.filter(n => n.kind === 'agent' && !n.parentId && n.turn === t)
241 const has = all.some(n => n.id === id)
242 isGrouped = has || strays.length >= 2
243 if (!isGrouped || strays.length === 0) return all
244 const moved = all.map(n => (strays.includes(n) ? { ...n, parentId: id } : n))
245 if (has) return moved.map(n => (n.id === id && n.status !== 'running' ? { ...n, status: 'running' as const, endedAt: undefined, digested: false } : n))
246 const group: AgentNode = {
247 id, kind: 'group', label: strays[0]!.label, type: 'group', turn: t, where: strays[0]!.where,
248 status: 'running', startedAt: Math.min(...strays.map(f => f.startedAt)), tools: 0, titled: true,
249 }
250 return [...moved, group]
251 })
252 return isGrouped ? id : undefined
253}
254
255// A group's name says what its members work on together, from their task descriptions.
256// Named again when members join while Haiku is naming it.
257async function titleGroup($: Engine, id: string) {
258 if (titling.has(id)) return
259 const list = await read($, nodes)
260 const g = list.find(n => n.id === id)
261 const kids = list.filter(k => k.parentId === id)
262 if (!g || kids.length === 0 || g.titledFor === kids.length) return
263 titling.add(id)
264 const r = await ask($, 'haiku', {
265 maxTokens: 30,
266 system: 'You name a batch of AI agents that work toward one goal, so a person can scan a list of runs. Reply with the title only: 3 to 7 words, starting with a verb, naming the shared goal, no quotes, no final period.',
267 prompt: `Agents and their tasks:\n${kids.map(k => `- ${k.label}: ${(k.prompt ?? '').slice(0, 300)}`).join('\n')}`,
268 })
269 titling.delete(id)
270 const title = r?.isAnswered && r.text ? cleanTitle(r.text) : undefined
271 await patch($, id, x => ({ ...x, label: title ?? x.label, titledFor: kids.length, prompt: kids.map(k => k.label).join('; ') }))
272 void titleGroup($, id)
273}
274
275// Workflow agents carry script labels ("read:types"); a person wants "Read the type fields".
276async function titleAgents($: Engine) {
277 const list = await read($, nodes)
278 const wfIds = new Set(list.filter(n => n.kind === 'workflow').map(n => n.id))
279 const todo = list.filter(n => n.kind === 'agent' && n.parentId && wfIds.has(n.parentId) && !n.titled && n.prompt && !titling.has(n.id))
280 for (const n of todo.slice(0, Math.max(0, TITLE_CONCURRENCY - titling.size))) {
281 titling.add(n.id)
282 void ask($, 'haiku', {
283 maxTokens: 30,
284 system: 'You name tasks given to AI agents so a person can scan a list of them. Reply with the title only: 3 to 7 words, starting with a verb, no quotes, no final period.',
285 prompt: `Task:\n${(n.prompt ?? '').slice(0, 800)}`,
286 }).then(async r => {
287 const title = r?.isAnswered && r.text ? cleanTitle(r.text) : undefined
288 await patch($, n.id, x => ({ ...x, titled: true, label: title ?? x.label }))
289 }).catch(() => patch($, n.id, x => ({ ...x, titled: true }))).finally(() => {
290 titling.delete(n.id)
291 void titleAgents($)
292 })
293 }
294}
295
296async function endWorkflow($: Engine, taskId: string, word: string | undefined, result?: string) {
297 const wf = (await read($, nodes)).find(n => n.kind === 'workflow' && n.status === 'running' && n.taskId === taskId)
298 if (!wf) return
299 await syncJournal($, wf)
300 const at = await $.clock.now()
301 const status = statusOf(word)
302 // An agent the journal never saw end did not finish: it was cut with the run.
303 await update($, nodes, all =>
304 all.map(n => (n.id === wf.id ? withResult(finish(status, at)(n), result) : n.parentId === wf.id ? finish('killed', at)(n) : n)),
305 )
306 holdAnswer(wf.id, result)
307 void digest($, wf.id)
308 await announce($, wf.id)
309 await archive($)
310}
311
312// A finished top-level run gets a toast: what it was, how it ended, what it changed.
313async function announce($: Engine, id: string) {
314 const list = await read($, nodes)
315 const n = list.find(x => x.id === id)
316 if (!n || n.parentId || n.status === 'running') return
317 const rows = fileRows(scopeNodes(list, { kind: 'node', id: n.id }))
318 const head = n.status === 'failed' ? '✗ Failed' : n.status === 'killed' ? '■ Stopped' : '✓ Finished'
319 $.ui.toast(`${head}: ${n.label} · ${changesLine(rows)}`)
320}
321
322// Every model call goes through here: the /config setting decides who may write,
323// and what each call spent is kept for the History header.
324type Completion = { isAnswered: boolean; text?: string; usage?: { input_tokens: number; output_tokens: number } }
325async function ask($: Engine, tier: Tier, req: { system: string; prompt: string; maxTokens: number }): Promise<Completion | undefined> {
326 if (!aiAllows(aiMode, tier)) return undefined
327 const r = (await $.model.complete({ model: tier, ...req }).catch(() => undefined)) as Completion | undefined
328 const used = tokensOf(r)
329 // kept off the caller's path, one write at a time, so two calls never lose each other's spend
330 if (used) spendChain = spendChain.then(() => noteSpend($, used)).catch(() => undefined)
331 return r
332}
333let spendChain: Promise<void> = Promise.resolve()
334const tokensOf = (r: Completion | undefined) => (r?.usage ? r.usage.input_tokens + r.usage.output_tokens : 0)
335
336async function noteSpend($: Engine, tokens: number) {
337 const at = await $.clock.now()
338 const prev = ((await $.store.get(AI_SPEND)) as { at: number; tokens: number }[] | undefined) ?? []
339 await $.store.set(AI_SPEND, [...prev.filter(x => at - x.at < WEEK), { at, tokens }].slice(-2000))
340}
341
342async function aiWeek($: Engine): Promise<number> {
343 const at = await $.clock.now()
344 const list = ((await $.store.get(AI_SPEND)) as { at: number; tokens: number }[] | undefined) ?? []
345 return list.filter(x => at - x.at < WEEK).reduce((a, x) => a + x.tokens, 0)
346}
347
348const bumpAi = ($: Engine) => update($, aiSeq, s => ({ seq: (s?.seq ?? 0) + 1 }))
349
350// A node's change lands where the node is: the live list, History, or both.
351async function patchAnywhere($: Engine, id: string, fn: (n: AgentNode) => AgentNode) {
352 if ((await read($, nodes)).some(n => n.id === id)) await patch($, id, fn)
353 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
354 if (history.some(n => n.id === id)) await $.store.set(HISTORY, history.map(n => (n.id === id ? fn(n) : n)))
355 await bumpAi($)
356}
357
358// Live nodes over History: a finished run can sit in both for a moment, and the live copy wins.
359async function allNodes($: Engine): Promise<AgentNode[]> {
360 const byId = new Map<string, AgentNode>()
361 for (const n of [...(((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []), ...(await read($, nodes))]) byId.set(n.id, n)
362 return [...byId.values()]
363}
364
365// ── story steps: Haiku turns an agent's tool log into a few steps when it ends ──
366async function writeStory($: Engine, id: string) {
367 if (!aiAllows(aiMode, 'haiku') || storying.has(id)) return
368 const all = await read($, nodes)
369 const n = all.find(x => x.id === id)
370 if (!n || n.kind !== 'agent' || n.status === 'running' || n.story || n.storyTried) return
371 storying.add(id)
372 try {
373 await writeStoryOf($, n, all)
374 } catch {
375 // no transcript to read, or the read failed: the story is not asked again
376 await patch($, id, x => ({ ...x, storyTried: true })).catch(() => undefined)
377 } finally {
378 storying.delete(id)
379 }
380}
381
382async function writeStoryOf($: Engine, n: AgentNode, all: AgentNode[]) {
383 const id = n.id
384 await locateTranscripts($, [n], all)
385 const path = transcriptAt.get(id)
386 const at = await $.clock.now()
387 const events = path ? await transcriptEvents($, id, path, false, at) : undefined
388 if (!events?.length) { await patch($, id, x => ({ ...x, storyTried: true })); return }
389 const r = await ask($, 'haiku', { maxTokens: 400, system: STORY_SYSTEM, prompt: storyInput(n, events) })
390 const lines = r?.isAnswered && r.text ? parseStory(r.text) : undefined
391 const tokens = tokensOf(r)
392 await patch($, id, x => ({ ...x, storyTried: true, ...(lines ? { story: { steps: lines, model: TIER_NAME.haiku, ...(tokens ? { tokens } : {}), at } } : {}) }))
393 // an open trace reads the new steps at its next build
394 traceBuilt = undefined
395 await archive($)
396}
397
398// ── Explain this run: Sonnet, on demand, cached on the run ──────────────────
399// The caller has put the run in `explaining`; it leaves when the brief is stored.
400async function explainRun($: Engine, runId: string) {
401 try {
402 const all = await allNodes($)
403 const run = all.find(n => n.id === runId)
404 if (!run) return
405 const now = await $.clock.now()
406 const seen = insights(scopeNodes(all, { kind: 'node', id: run.id }), all, now).map(i => i.text)
407 const r = await ask($, 'sonnet', { maxTokens: 900, system: EXPLAIN_SYSTEM, prompt: explainInput(run, all, seen) })
408 const brief = r?.isAnswered && r.text ? parseBrief(r.text) : undefined
409 const tokens = tokensOf(r)
410 if (brief) await patchAnywhere($, runId, x => ({ ...x, explain: { ...brief, model: TIER_NAME.sonnet, ...(tokens ? { tokens } : {}), at: now } }))
411 } finally {
412 explaining.delete(runId)
413 await bumpAi($).catch(() => undefined)
414 }
415}
416
417// ── patterns across runs: Sonnet, on demand or weekly, one set per repository ──
418async function patternsKey($: Engine): Promise<string> {
419 const repo = await sessionRepo($)
420 return repo ? folderKey(repo) : 'all'
421}
422
423async function patternsDoc($: Engine): Promise<PatternsDoc | undefined> {
424 const docs = ((await $.store.get(PATTERNS)) as Record<string, PatternsDoc> | undefined) ?? {}
425 return docs[await patternsKey($)]
426}
427
428// The caller has set `patternsBusy`; it is cleared when the cards are stored.
429async function writePatterns($: Engine) {
430 try {
431 const key = await patternsKey($)
432 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
433 const ids = new Set(history.map(n => n.id))
434 const runs = history.filter(n => (!n.parentId || !ids.has(n.parentId)) && (key === 'all' || runKey(n) === key))
435 .sort((a, b) => b.startedAt - a.startedAt)
436 if (runs.length < 2) return
437 const r = await ask($, 'sonnet', { maxTokens: 1200, system: PATTERNS_SYSTEM, prompt: patternsInput(runs, history) })
438 const cards = r?.isAnswered && r.text ? parsePatterns(r.text, runs) : undefined
439 const tokens = tokensOf(r)
440 if (cards) {
441 const docs = ((await $.store.get(PATTERNS)) as Record<string, PatternsDoc> | undefined) ?? {}
442 await $.store.set(PATTERNS, { ...docs, [key]: { cards, model: TIER_NAME.sonnet, ...(tokens ? { tokens } : {}), at: await $.clock.now() } })
443 }
444 } finally {
445 patternsBusy = false
446 await bumpAi($).catch(() => undefined)
447 }
448}
449
450// The report: what finished work achieved, in short plain sentences a person
451// scans. One Haiku call when it finishes, so the words are there before anyone
452// looks. Written bottom-up: an agent from its own report, a workflow phase from
453// its agents' reports, a cluster or a workflow from its part reports.
454// a reply that is not the asked-for JSON still says something: its first sentence is the result;
455// JSON that would not parse is never shown as words
456function reportFrom(r: Completion | undefined, at: number): Report | undefined {
457 if (!r?.isAnswered || !r.text) return undefined
458 const fallback = /[{}]/.test(r.text) ? '' : firstSentence(r.text, 300)
459 const parsed = parseReport(r.text) ?? (fallback ? { result: fallback } : undefined)
460 if (!parsed) return undefined
461 const tokens = r.usage ? r.usage.input_tokens + r.usage.output_tokens : 0
462 return { ...parsed, model: TIER_NAME.haiku, ...(tokens ? { tokens } : {}), at }
463}
464
465async function digest($: Engine, id: string) {
466 if (digesting.has(id)) return
467 const list = await read($, nodes)
468 const n = list.find(x => x.id === id)
469 if (!n || n.digested || n.status === 'running') return
470 const kids = list.filter(k => k.parentId === id)
471 // a cluster's report reads its members' reports: wait until each finished member has one;
472 // a workflow waits for the agent reports still being written, then writes what it has
473 if (n.kind === 'group' && kids.some(k => k.status !== 'running' && !k.digested && k.result)) return
474 if (n.kind === 'workflow' && kids.some(k => digesting.has(k.id))) return
475 digesting.add(id)
476 if (n.kind === 'workflow') await writeParts($, id, true)
477 const now = await read($, nodes)
478 const node = now.find(x => x.id === id) ?? n
479 const hasInput = node.kind === 'agent' ? !!node.result?.trim() : kids.length > 0 || !!node.result?.trim()
480 const r = hasInput ? await ask($, 'haiku', { maxTokens: REPORT_TOKENS, system: REPORT_SYSTEM, prompt: runInput(node, now, answers.get(id)) }) : undefined
481 answers.delete(id)
482 const report = reportFrom(r, await $.clock.now())
483 await patch($, id, x => ({
484 ...x, digested: true,
485 ...(report ? { report, ...(report.result ? { summary: report.result } : {}), ...(report.done ? { points: report.done } : {}) } : {}),
486 }))
487 // released only once the report is stored, so a second trigger cannot write it twice
488 digesting.delete(id)
489 await archive($)
490 // an agent's report may be what its cluster, its workflow or its phase was waiting for
491 const parent = node.parentId ? (await read($, nodes)).find(x => x.id === node.parentId) : undefined
492 if (!parent || (parent.kind !== 'group' && parent.kind !== 'workflow')) return
493 if (parent.status !== 'running') { if (!parent.digested) void digest($, parent.id) }
494 else if (parent.kind === 'workflow') void writeParts($, parent.id, false)
495}
496
497// A workflow's phases that have finished get a part report each, read from their
498// agents' reports. While the run goes on, a phase waits until each of its agents
499// has its own short report; when the run ends (`force`), it is written
500// from what there is. A phase that gained agents since its report is written again.
501async function writeParts($: Engine, wfId: string, force: boolean) {
502 const list = await read($, nodes)
503 const wf = list.find(n => n.id === wfId)
504 if (!wf) return
505 for (const p of pipeline(wf, list)) {
506 if (p.running > 0 || p.total === 0) continue
507 const agents = list.filter(k => k.parentId === wfId && (k.phase ?? 'Agents') === p.phase)
508 if (!force && agents.some(k => !k.digested)) continue
509 await partDigest($, wfId, p.phase)
510 }
511}
512
513async function partDigest($: Engine, wfId: string, phase: string) {
514 const key = `${wfId}::${phase}`
515 if (digesting.has(key)) return
516 // taken before the first await, so a second trigger cannot slip in while this one reads
517 digesting.add(key)
518 try {
519 const list = await read($, nodes)
520 const wf = list.find(n => n.id === wfId)
521 const total = list.filter(k => k.parentId === wfId && (k.phase ?? 'Agents') === phase).length
522 // read now, not when the caller looked: another trigger may have written it meanwhile
523 if (!wf || wf.partReports?.[phase]?.count === total) return
524 const r = await ask($, 'haiku', { maxTokens: PART_TOKENS, system: REPORT_SYSTEM, prompt: partInput(wf, phase, list) })
525 const report = reportFrom(r, await $.clock.now())
526 await patch($, wfId, x => ({ ...x, partReports: { ...x.partReports, [phase]: { ...(report ?? {}), count: total } } }))
527 } finally {
528 // released only once the report is stored
529 digesting.delete(key)
530 }
531}
532
533type Change = NonNullable<AgentNode['changes']>
534const addChange = (prev: AgentNode['changes'], e: { path: string; added: number; removed: number }): Change => {
535 const c = prev?.[e.path] ?? { edits: 0, added: 0, removed: 0 }
536 return { ...prev, [e.path]: { edits: c.edits + 1, added: c.added + e.added, removed: c.removed + e.removed } }
537}
538
539const slim = (n: AgentNode): AgentNode => ({ ...n, prompt: excerpt(n.prompt, 300), result: excerpt(n.result, 600), activity: undefined, act: undefined })
540
541// The session's root folder: where it started, or where /cd moved it. A shell
542// cd does not move it, and neither does the folder the mod's commands run in.
543async function sessionRepo($: Engine): Promise<string | undefined> {
544 return (await $.session.root().catch(() => '')) || undefined
545}
546
547// Runs saved before the repo was the root folder get its key from where their
548// transcripts are kept: ~/.claude/projects/<root folder key>/..., once.
549async function backfillRepos($: Engine) {
550 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
551 const byId = new Map(history.map(n => [n.id, n]))
552 const topOf = (n: AgentNode): AgentNode => (n.parentId && byId.has(n.parentId) ? topOf(byId.get(n.parentId)!) : n)
553 const tops = history.filter(n => topOf(n) === n && !n.repoTried)
554 if (tops.length === 0) return
555 const agentsUnder = new Map(tops.map(t => [t.id, history.filter(n => n.kind === 'agent' && topOf(n) === t).map(n => n.id)]))
556 const ids = [...new Set([...agentsUnder.values()].flat())]
557 const home = await $.env.get('HOME')
558 const names = ids.flatMap((id, i) => [...(i ? ['-o'] : []), '-name', `agent-${id}.jsonl`])
559 const found = ids.length
560 ? await $.process.run(['find', `${home}/.claude/projects`, '-maxdepth', '6', '(', ...names, ')'], { timeoutMs: 20000 }).catch(() => undefined)
561 : undefined
562 const keyOf = new Map((found?.stdout ?? '').split('\n').filter(Boolean).map(p => [p.replace(/^.*agent-|\.jsonl$/g, ''), p.split('/projects/')[1]?.split('/')[0]]))
563 const keys = new Map(tops.map(t => [t.id, (agentsUnder.get(t.id) ?? []).map(id => keyOf.get(id)).find(Boolean)]))
564 await $.store.set(HISTORY, history.map(n => {
565 if (!keys.has(n.id)) return n
566 const key = keys.get(n.id)
567 // a key from the transcript's folder wins over a repo recorded from the wrong folder
568 const { repo: _repo, ...rest } = n
569 return key ? { ...rest, repoKey: key, repoTried: true } : { ...n, repoTried: true }
570 }))
571}
572
573// The repo as a view prop: left out when there is none, since props hold no undefined.
574async function repoProp($: Engine): Promise<{ repo?: string }> {
575 const repo = await sessionRepo($)
576 return repo ? { repo } : {}
577}
578
579// Runs kept before reports were read from SubagentHandback calls get theirs
580// from their transcripts, once.
581async function backfillReports($: Engine) {
582 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
583 const todo = history.filter(n => n.kind === 'agent' && !n.result && !n.reportTried)
584 if (todo.length === 0) return
585 const home = await $.env.get('HOME')
586 const names = todo.flatMap((n, i) => [...(i ? ['-o'] : []), '-name', `agent-${n.id}.jsonl`])
587 const found = await $.process.run(['find', `${home}/.claude/projects`, '-maxdepth', '6', '(', ...names, ')'], { timeoutMs: 20000 }).catch(() => undefined)
588 const pathOf = new Map((found?.stdout ?? '').split('\n').filter(Boolean).map(p => [p.replace(/^.*agent-|\.jsonl$/g, ''), p]))
589 const reports = new Map<string, string>()
590 for (const n of todo) {
591 const path = pathOf.get(n.id)
592 const report = path ? handbackOf(await $.fs.read(path).catch(() => '')) : undefined
593 if (report) reports.set(n.id, report)
594 }
595 const tried = new Set(todo.map(n => n.id))
596 await $.store.set(HISTORY, history.map(n => (tried.has(n.id) ? withResult({ ...n, reportTried: true }, reports.get(n.id), 600) : n)))
597}
598
599// Reports written before the whole answer was read came from its first 400 (or 600)
600// characters, and often called finished work unfinished. Each such agent's report is
601// written again from its transcript, once, then each cluster over them. A report kept
602// as raw JSON, from a reply cut at its token cap, is written again too (the second
603// mark: the first pass made many of those). Every open session runs this at its
604// start, so the first takes a mark and the others leave it.
605const REDONE = 'reportsRedone2'
606const REDO_CONCURRENCY = 4
607async function redoReports($: Engine) {
608 if (!aiAllows(aiMode, 'haiku')) return
609 const now = await $.clock.now()
610 const mark = (await $.store.get(REDONE)) as { token: string; at: number; done?: boolean } | undefined
611 // a mark left by a session that ended mid-way is taken over after 15 minutes
612 if (mark && (mark.done || now - mark.at < 15 * 60_000)) return
613 const token = `${now}-${Math.random().toString(36).slice(2)}`
614 await $.store.set(REDONE, { token, at: now })
615 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
616 const isCut = (n: AgentNode) => n.resultLength !== undefined || (n.result?.length ?? 0) >= 400
617 const todo = history.filter(n => n.kind === 'agent' && ((n.resultLength === undefined && isCut(n)) || isRawReport(n.summary)))
618 // only a cut answer needs its transcript
619 const cut = todo.filter(isCut)
620 const home = await $.env.get('HOME')
621 const names = cut.flatMap((n, i) => [...(i ? ['-o'] : []), '-name', `agent-${n.id}.jsonl`])
622 const found = cut.length
623 ? await $.process.run(['find', `${home}/.claude/projects`, '-maxdepth', '6', '(', ...names, ')'], { timeoutMs: 20000 }).catch(() => undefined)
624 : undefined
625 // another session took the job while the transcripts were looked for
626 if (((await $.store.get(REDONE)) as { token?: string } | undefined)?.token !== token) return
627 const pathOf = new Map((found?.stdout ?? '').split('\n').filter(Boolean).map(p => [p.replace(/^.*agent-|\.jsonl$/g, ''), p]))
628 const fulls = new Map<string, string>()
629 for (const n of cut) {
630 const path = pathOf.get(n.id)
631 const full = path ? handbackOf(await $.fs.read(path).catch(() => '')) : undefined
632 if (full && full.length > n.result!.length) fulls.set(n.id, full)
633 }
634 const reports = new Map<string, Report>()
635 const write = async (list: AgentNode[], ns: AgentNode[], full?: (n: AgentNode) => string | undefined) => {
636 for (let i = 0; i < ns.length; i += REDO_CONCURRENCY) {
637 await Promise.all(ns.slice(i, i + REDO_CONCURRENCY).map(async n => {
638 const r = await ask($, 'haiku', { maxTokens: REPORT_TOKENS, system: REPORT_SYSTEM, prompt: runInput(n, list, full?.(n)) })
639 const report = reportFrom(r, await $.clock.now())
640 if (report) reports.set(n.id, report)
641 }))
642 }
643 }
644 const withReport = (n: AgentNode): AgentNode => {
645 const report = reports.get(n.id)
646 return {
647 ...n, ...(fulls.has(n.id) ? { resultLength: fulls.get(n.id)!.length } : {}),
648 ...(report ? { report, ...(report.result ? { summary: report.result } : {}), ...(report.done ? { points: report.done } : {}) } : {}),
649 }
650 }
651 // a raw report with no transcript is written from the kept copy, its cut named
652 const agents = todo.filter(n => fulls.has(n.id) || isRawReport(n.summary))
653 await write(history, agents, n => fulls.get(n.id))
654 // a cluster's report reads its members' reports, so it is written after theirs
655 const redone = history.map(withReport)
656 const groups = redone.filter(g => g.kind === 'group' && (isRawReport(g.summary) || agents.some(a => a.parentId === g.id && reports.has(a.id))))
657 await write(redone, groups)
658 // History may have grown while the reports were written: only these nodes change
659 const latest = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
660 await $.store.set(HISTORY, latest.map(withReport))
661 await $.store.set(REDONE, { token, at: now, done: true })
662}
663
664// A finished top-level run, with everything under it, is kept across sessions.
665async function archive($: Engine) {
666 const list = await read($, nodes)
667 const ids = new Set(list.map(n => n.id))
668 const tops = list.filter(n => !n.parentId || !ids.has(n.parentId))
669 const subtree = (id: string): AgentNode[] => list.filter(n => n.parentId === id).flatMap(k => [k, ...subtree(k.id)])
670 const done = tops.map(t => [t, ...subtree(t.id)]).filter(run => run.every(n => n.status !== 'running'))
671 if (done.length === 0) return
672 const prev = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
673 const repo = await sessionRepo($)
674 const fresh = done.flat().map(slim).map(n => (repo && !n.repo ? { ...n, repo, repoTried: true } : n))
675 const freshIds = new Set(fresh.map(n => n.id))
676 const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
677 if (fresh.every(f => prev.some(p => p.id === f.id && p.status === f.status && p.label === f.label && p.summary === f.summary && p.parentId === f.parentId
678 && same(p.report, f.report) && same(p.partReports, f.partReports) && same(p.story, f.story) && same(p.explain, f.explain)))) return
679 const merged = [...prev.filter(p => !freshIds.has(p.id)), ...fresh]
680 const runTops = merged.filter(n => !n.parentId || !merged.some(m => m.id === n.parentId))
681 const keep = new Set(runTops.slice(-HISTORY_RUNS).map(n => n.id))
682 const rootOf = (n: AgentNode): string => {
683 const p = n.parentId && merged.find(m => m.id === n.parentId)
684 return p ? rootOf(p) : n.id
685 }
686 await $.store.set(HISTORY, merged.filter(n => keep.has(rootOf(n))))
687 // their edits go with them, so History can still show the diffs
688 const kept = new Set(merged.filter(n => keep.has(rootOf(n))).map(n => n.id))
689 const pastEdits = ((await $.store.get(EDITS)) as EditRecord[] | undefined) ?? []
690 const freshEdits = (await read($, edits)).filter(r => freshIds.has(r.agentId)).map(r => ({ ...r, old: r.old.slice(0, 2500), new: r.new.slice(0, 2500) }))
691 const known = new Set(pastEdits.map(r => r.id))
692 await $.store.set(EDITS, [...pastEdits, ...freshEdits.filter(r => !known.has(r.id))].filter(r => kept.has(r.agentId)).slice(-EDITS_KEPT))
693}
694
695export const register: Register = (on, options) => {
696 themeName = themeNameOf(options?.theme)
697 aiMode = AI_MODES.includes(options?.ai as AiMode) ? (options!.ai as AiMode) : 'cheap'
698 on('session.start', async ($, e, next) => {
699 await $.command.register({
700 name: 'agent-tree',
701 description: 'Show subagents and workflows in a side pane (`clear` empties the history)',
702 })
703 await archive($)
704 await backfillReports($)
705 await backfillRepos($)
706 void redoReports($).catch(() => undefined)
707 if ((await read($, nodes)).some(n => n.status === 'running')) ensureTimers($)
708 // patterns written more than a week ago are written again, in the background, on Full only
709 const doc = aiAllows(aiMode, 'sonnet') ? await patternsDoc($) : undefined
710 if (doc && (await $.clock.now()) - doc.at > WEEK && !patternsBusy) {
711 patternsBusy = true
712 void writePatterns($).catch(() => undefined)
713 }
714
715 return next(e)
716 })
717
718 on('command.run', { command: 'agent-tree' }, async ($, e) => {
719 if (e.args.trim() === 'clear') {
720 await update($, nodes, list => list.filter(n => n.status === 'running'))
721 await $.store.set(HISTORY, [])
722 await $.store.set(EDITS, [])
723 await update($, edits, () => [])
724 return { text: 'Agent history cleared.' }
725 }
726 await $.ui.open({ id: PANE, title: TITLE })
727
728 return { text: 'Agents pane opened. Click it; ? shows the keys.' }
729 })
730
731 on('tool.call', { tool: 'Agent' }, (_$, e, next) => {
732 agentCalls.add(e.tool_use_id)
733 if (e.isolation) isolationOf.set(e.tool_use_id, e.isolation)
734 return next(e)
735 })
736
737 on('agent.spawn', async ($, e, next) => {
738 const startedAt = await $.clock.now()
739 const ran = await next(e)
740 if (ran.deny !== undefined || !ran.agentId) return ran
741
742 const list = await read($, nodes)
743 const fromWorkflow = !agentCalls.has(e.tool_use_id) ? runningWorkflow(list) : undefined
744 const fromMain = !e.parentAgentId && !fromWorkflow
745 const t = fromMain ? (turn ??= `t${startedAt}`) : undefined
746 await add($, {
747 id: ran.agentId,
748 kind: 'agent',
749 parentId: e.parentAgentId ?? fromWorkflow?.id,
750 turn: t,
751 label: e.name ?? e.description,
752 type: e.subagentType,
753 model: ran.model,
754 where: isolationOf.get(e.tool_use_id) ?? 'main',
755 status: 'running',
756 startedAt,
757 tools: 0,
758 act: 'think',
759 prompt: excerpt(e.prompt),
760 titled: !fromWorkflow,
761 })
762 const group = t ? await regroup($, t) : undefined
763 if (group) void titleGroup($, group)
764
765 return ran
766 })
767
768 on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
769 const id = `wf:${e.tool_use_id}`
770 const name = e.name ?? scriptField(e.script, 'name') ?? 'workflow'
771 const description = scriptField(e.script, 'description')
772 await add($, {
773 id, kind: 'workflow', parentId: e.agentId, label: description ?? name, tag: name, type: 'workflow',
774 status: 'running', startedAt: await $.clock.now(), tools: 0, prompt: description,
775 })
776 const ran = await next(e)
777 if (ran.deny !== undefined || ran.isError) {
778 await patch($, id, finish('failed', await $.clock.now()))
779 } else {
780 const { taskId, workflowName, transcriptDir } = ran.result
781 await patch($, id, n => ({ ...n, taskId, transcriptDir, tag: workflowName ?? n.tag }))
782 ensureTimers($)
783 }
784
785 return ran
786 })
787
788 on('tool.call', async ($, e, next) => {
789 if (!e.agentId) return next(e)
790 const { agentId, tool } = e
791 const input = e as unknown as Record<string, unknown>
792 const { act, activity } = describeTool(tool, input)
793 const list = await read($, nodes)
794 const calledAt = await $.clock.now()
795 if (list.some(n => n.id === agentId)) {
796 await patch($, agentId, n => ({
797 ...n, tools: n.tools + 1, lastTool: tool, lastToolAt: calledAt, act, activity, status: 'running', endedAt: undefined,
798 work: act === 'think' ? n.work : { ...n.work, [act]: (n.work?.[act] ?? 0) + 1 },
799 }))
800 // An agent that hands its report back through a tool ends with no final text.
801 // SubagentHandback is not in the typed tool list, so the name is compared as a string.
802 if ((tool as string) === 'SubagentHandback' && typeof input.message === 'string') {
803 const report = input.message
804 await patch($, agentId, n => withResult(n, report))
805 holdAnswer(agentId, report)
806 }
807 ensureTimers($)
808 } else {
809 // A workflow agent seen before its journal line: filed under the running
810 // workflow now, and corrected by the journal on the next poll.
811 const wf = runningWorkflow(list)
812 if (!wf) return next(e)
813 await add($, {
814 id: agentId, kind: 'agent', parentId: wf.id, label: `agent ${agentId.slice(0, 6)}`,
815 status: 'running', startedAt: calledAt, tools: 1, lastTool: tool, lastToolAt: calledAt, act, activity,
816 work: act === 'think' ? {} : { [act]: 1 },
817 })
818 }
819
820 // An edit is recorded once it has landed: its before and after text, where it
821 // sits in the file, and a true line count of what it added and removed.
822 const path = editedPath(tool, input)
823 if (!path) return next(e)
824 const before = tool === 'Write' ? await $.fs.read(path).catch(() => undefined) : undefined
825 const ran = await next(e)
826 if (ran.deny !== undefined || ran.isError) return ran
827 const after = await $.fs.read(path).catch(() => undefined)
828 const at = await $.clock.now()
829 const recs = editRecords(tool, input, before, after).map((r, i) => ({
830 ...r, id: `${e.tool_use_id}:${i}`, agentId, at,
831 old: r.old.slice(0, EDIT_TEXT), new: r.new.slice(0, EDIT_TEXT),
832 }))
833 const stats = recs.map(r => diffCounts(lineDiff(r.old, r.new)))
834 await update($, edits, all => [...all, ...recs].slice(-EDITS_KEPT))
835 await patch($, agentId, n => {
836 let changes = n.changes
837 for (const s of stats) changes = addChange(changes, { path, ...s })
838 return { ...n, changes }
839 })
840 return ran
841 })
842
843 on('turn.complete', async ($, e, next) => {
844 const { agentId } = e
845 if (agentId) {
846 const at = await $.clock.now()
847 const u = e.usage
848 const tokens = u ? u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : undefined
849 const status: NodeStatus = e.isAborted ? 'killed' : 'done'
850 const list = await read($, nodes)
851 const wf = runningWorkflow(list)
852 if (list.some(n => n.id === agentId)) {
853 await patch($, agentId, n => withResult({
854 ...finish(status, at)(n),
855 model: n.model ?? u?.model,
856 tokens: (n.tokens ?? 0) + (tokens ?? 0),
857 }, e.answer))
858 } else if (wf) {
859 // A workflow agent that never called a tool is first seen as it ends.
860 await add($, withResult({
861 id: agentId, kind: 'agent', parentId: wf.id, label: `agent ${agentId.slice(0, 6)}`,
862 model: u?.model, status, startedAt: at - e.durationMs, endedAt: at, tools: 0, tokens,
863 }, e.answer))
864 }
865 holdAnswer(agentId, e.answer)
866 void digest($, agentId)
867 void writeStory($, agentId).catch(() => undefined)
868 await announce($, agentId)
869 await settleGroups($)
870 await archive($)
871 }
872
873 return next(e)
874 })
875
876 // A background task's end reaches the main loop as a queued prompt whose
877 // origin is `task-notification`, its text naming the task id and status.
878 on('prompt.submit', async ($, e, next) => {
879 // a prompt taken while idle opens a new turn; one delivered into a running turn
880 // (typed ahead, or a background task's notice) stays part of it
881 if (!e.turnId) turn = `t${await $.clock.now()}`
882 if (e.origin.kind === 'task-notification') {
883 const id = /<task-id>\s*([^<\s]+)/.exec(e.text)?.[1]
884 if (id) await endWorkflow($, id, /<status>\s*(\w+)/.exec(e.text)?.[1], /<result>([\s\S]*?)<\/result>/.exec(e.text)?.[1]?.trim())
885 }
886 return next(e)
887 })
888
889 // Backstop: at each stop the engine lists the background work still in flight.
890 // A running workflow missing from that list has ended.
891 on('classic.Stop', async ($, e, next) => {
892 if (e.transcript_path) subagentsDir = `${e.transcript_path.replace(/\.jsonl$/, '')}/subagents`
893 const inFlight = e.background_tasks
894 if (Array.isArray(inFlight)) {
895 const live = new Set(inFlight.map(t => t.id))
896 const gone = (await read($, nodes)).filter(n => n.kind === 'workflow' && n.status === 'running' && n.taskId && !live.has(n.taskId))
897 for (const wf of gone) if (wf.taskId) await endWorkflow($, wf.taskId, 'completed')
898 }
899 return next(e)
900 })
901
902 // The transcript's own Agent and Workflow rows shrink to one line; the pane is the full view.
903 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
904 const { tool, isRunning, isErrored } = e.props
905 if (!AGENT_TOOLS.has(tool) && tool !== 'Workflow') return next(e)
906 const { Box, Text } = $.ui.resolve(e)
907 const input = (e.props.input ?? {}) as { description?: string; subagent_type?: string; name?: string; script?: string }
908 const label = tool === 'Workflow'
909 ? scriptField(input.script, 'description') ?? input.name ?? scriptField(input.script, 'name') ?? 'workflow'
910 : input.description ?? 'subagent'
911 const kind = tool === 'Workflow' ? 'Workflow' : `${input.subagent_type ?? 'General-purpose'} agent`
912 const t = themeOf(themeName)
913 const st = t.status[isErrored ? 'failed' : isRunning ? 'running' : 'done']
914
915 return (
916 <Box flexDirection="row" gap={1}>
917 <Text color={st.color}>{st.icon}</Text>
918 {/* one glyph means status; only a workflow adds one for what it is */}
919 {tool === 'Workflow' ? <Text>{t.kind.workflow}</Text> : null}
920 <Text bold wrap="truncate-end">{label}</Text>
921 <Text dimColor>· {kind} · details in the Agents pane</Text>
922 </Box>
923 )
924 })
925
926 // The view asks for a file's diff when it opens one, and lets it go when it closes it.
927 // It asks for a run's trace the same way: which run, how close, where it reads.
928 on('ui.message', async ($, e, next) => {
929 const data = e.data as { type?: unknown; path?: unknown; run?: unknown; zoom?: unknown; offset?: unknown; regenerate?: unknown; lens?: unknown; focus?: unknown; lane?: unknown; query?: unknown } | null
930 if (e.requestId !== PANE) return next(e)
931 if (data?.type === 'diff') {
932 diffPath = typeof data.path === 'string' ? data.path : null
933 return { props: await viewProps($) }
934 }
935 if (data?.type === 'trace') {
936 await askTrace($, data)
937 return { props: await viewProps($) }
938 }
939 if (data?.type === 'export' && typeof data.run === 'string') {
940 const lens = data.lens === 'trace' ? 'trace' : 'timeline'
941 const zoom: TraceZoom = ZOOMS.includes(data.zoom as TraceZoom) ? (data.zoom as TraceZoom) : 'story'
942 void exportPicture($, data.run, lens, zoom, typeof data.focus === 'string' ? data.focus : undefined).catch(() => note($, 'Could not draw the picture.'))
943 return { props: await viewProps($) }
944 }
945 // Explain this run and patterns are Sonnet's, on Full only: the view says how to turn them on
946 if (data?.type === 'explain' && typeof data.run === 'string' && aiAllows(aiMode, 'sonnet') && !explaining.has(data.run)) {
947 explaining.add(data.run)
948 void explainRun($, data.run).catch(() => undefined)
949 return { props: await viewProps($) }
950 }
951 if (data?.type === 'patterns' && aiAllows(aiMode, 'sonnet') && !patternsBusy) {
952 patternsBusy = true
953 void writePatterns($).catch(() => undefined)
954 return { props: await viewProps($) }
955 }
956 return next(e)
957 })
958
959 // The pane's rows are the view's own, so the engine has nothing to scroll:
960 // each wheel tick is handed to the view, which moves its selection or text.
961 on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
962 // a drawing taller than the pane (the desktop's) scrolls as the engine scrolls it
963 if (e.origin.kind !== 'person' || e.contentRows > e.bodyRows) return next(e)
964 await update($, wheel, w => ({ seq: (w?.seq ?? 0) + 1, by: e.by }))
965 return {}
966 })
967
968 // A load failure is the module itself, so a fresh instance would fail the same way.
969 on('ui.fault', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
970 const r = await next(e)
971 const now = await $.clock.now()
972 faultsAt = faultsAt.filter(t => now - t < FAULT_WINDOW)
973 if (e.element === viewKey() && e.phase !== 'load' && faultsAt.length < FAULT_RETRIES) {
974 faultsAt.push(now)
975 viewGen++
976 $.ui.invalidate('ui.render')
977 }
978 return r
979 })
980
981 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
982 const els = $.ui.resolve(e)
983 // phase 6: the desktop draws its own native view; presses write the desk state
984 if (e.surface === 'desktop') {
985 const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 120
986 return drawDesktop(els, await viewProps($), deskUi(await read($, desk)), {
987 set: change => void update($, desk, s => ({ ...deskUi(s), ...change })),
988 openDiff: path => {
989 diffPath = path
990 void update($, desk, s => ({ ...deskUi(s) }))
991 },
992 // a trail that could not be read leaves the view as it was
993 askTrace: (run, zoom, offset) => void askTrace($, run ? { run, zoom, offset } : {})
994 .then(() => update($, desk, s => ({ ...deskUi(s) })))
995 .catch(() => undefined),
996 // the same Sonnet jobs as the terminal's e and g, on Full only
997 explain: run => {
998 if (!aiAllows(aiMode, 'sonnet') || explaining.has(run)) return
999 explaining.add(run)
1000 void update($, desk, s => ({ ...deskUi(s) }))
1001 void explainRun($, run).catch(() => undefined)
1002 },
1003 patterns: () => {
1004 if (!aiAllows(aiMode, 'sonnet') || patternsBusy) return
1005 patternsBusy = true
1006 void update($, desk, s => ({ ...deskUi(s) }))
1007 void writePatterns($).catch(() => undefined)
1008 },
1009 exportPic: (run, lens, zoom, focus) => void exportPicture($, run, lens, zoom, focus).catch(() => note($, 'Could not draw the picture.')),
1010 }, columns)
1011 }
1012 // the pane body's own height: the viewport is the whole terminal, frame and all
1013 const rows = Math.max(8, e.props.scroll?.bodyRows ?? (e.viewport?.rows ?? 24) - 4)
1014 if (!('Client' in els)) return <els.Text dimColor>The Agents pane needs the terminal or desktop.</els.Text>
1015 const { Client } = els
1016
1017 return <Client key={viewKey()} module="./view.tsx" props={await viewProps($)} width="100%" height={rows} />
1018 })
1019}
1020
1021async function viewProps($: Engine): Promise<ViewProps> {
1022 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
1023 // read so a trace read again, or an AI block written to the store, redraws the pane
1024 await read($, traceSeq)
1025 await read($, aiSeq)
1026 const patterns = await patternsDoc($)
1027 const ai = { ai: aiMode, aiWeek: await aiWeek($), explaining: [...explaining], patternsBusy, ...(patterns ? { patterns } : {}), ...(exported ? { exported } : {}) }
1028 const trace = traceReq && traceSnap ? { trace: traceSnap } : {}
1029 const live = await read($, nodes)
1030 const runs = { nodes: live, history, at: await $.clock.now() }
1031 const rest = { ...await repoProp($), theme: themeName, wheel: await read($, wheel), ...trace, ...ai }
1032 if (!diffPath) return fitView(runs, rest)
1033 await backfill($, diffPath, [...history, ...live])
1034 const pastEdits = ((await $.store.get(EDITS)) as EditRecord[] | undefined) ?? []
1035 const seen = new Set<string>()
1036 const forFile = [...pastEdits, ...(await read($, edits))]
1037 .filter(r => r.path === diffPath && !seen.has(r.id) && seen.add(r.id))
1038 .sort((a, b) => a.at - b.at)
1039 // the open file's edits are measured with the rest, before the runs take what is left
1040 return fitView(runs, { ...rest, diff: { path: diffPath, edits: forFile } })
1041}
1042
1043// Agents that changed this file but left no edit records (runs from before edits
1044// were kept) get theirs rebuilt from their transcripts, once, and stored.
1045async function backfill($: Engine, path: string, all: AgentNode[]) {
1046 const stored = ((await $.store.get(EDITS)) as EditRecord[] | undefined) ?? []
1047 const live = await read($, edits)
1048 const has = new Set([...stored, ...live].filter(r => r.path === path).map(r => r.agentId))
1049 const byId = new Map(all.map(n => [n.id, n]))
1050 const todo = [...byId.values()].filter(n => n.changes?.[path] && !has.has(n.id) && !backfilled.has(n.id))
1051 if (todo.length === 0) return
1052 const now = await $.fs.read(path).catch(() => undefined)
1053 const found: EditRecord[] = []
1054 for (const n of todo) {
1055 backfilled.add(n.id)
1056 const dir = n.parentId ? byId.get(n.parentId)?.transcriptDir : undefined
1057 const sessionAgents = subagentsDir ?? dir?.replace(/\/workflows\/[^/]+$/, '')
1058 // a trace may already have found it, in this session's folder or another's
1059 const file = transcriptAt.get(n.id) ?? (dir ? `${dir}/agent-${n.id}.jsonl` : sessionAgents ? `${sessionAgents}/agent-${n.id}.jsonl` : undefined)
1060 if (!file) continue
1061 const text = await $.fs.read(file).catch(() => '')
1062 found.push(...transcriptEdits(text, n.id, now).filter(r => r.path === path)
1063 .map(r => ({ ...r, old: r.old.slice(0, 2500), new: r.new.slice(0, 2500) })))
1064 }
1065 if (found.length === 0) return
1066 const known = new Set(stored.map(r => r.id))
1067 await $.store.set(EDITS, [...stored, ...found.filter(r => !known.has(r.id))].slice(-EDITS_KEPT))
1068}
1069
1070// ── the trace: read from transcripts when the view asks, never on a redraw ────
1071
1072// The view asks for a run's trace (or lets it go). A new run or zoom is read now;
1073// a new place to read only moves the window. A live run is read again every 2 s.
1074async function askTrace($: Engine, data: { run?: unknown; zoom?: unknown; offset?: unknown; lane?: unknown; query?: unknown }) {
1075 const run = typeof data.run === 'string' ? data.run : null
1076 if (!run) {
1077 traceReq = null
1078 traceSnap = undefined
1079 traceBuilt = undefined
1080 tracer?.cancel()
1081 tracer = undefined
1082 return
1083 }
1084 const zoom: TraceZoom = ZOOMS.includes(data.zoom as TraceZoom) ? (data.zoom as TraceZoom) : 'story'
1085 const offset = typeof data.offset === 'number' && Number.isFinite(data.offset) ? Math.max(0, Math.floor(data.offset)) : 0
1086 const isNew = !traceReq || traceReq.run !== run || traceReq.zoom !== zoom
1087 const lane = typeof data.lane === 'string' && data.lane ? data.lane : undefined
1088 const query = typeof data.query === 'string' && data.query.trim() ? data.query.slice(0, 80) : undefined
1089 traceReq = { run, zoom, offset, ...(lane ? { lane } : {}), ...(query ? { query } : {}) }
1090 const isLive = await buildRunTrace($, isNew)
1091 if (isLive) tracer ??= $.clock.every(2000, () => void refreshTrace($))
1092}
1093
1094async function refreshTrace($: Engine) {
1095 if (!traceReq) { tracer?.cancel(); tracer = undefined; return }
1096 const isLive = await buildRunTrace($, true)
1097 await update($, traceSeq, s => ({ seq: (s?.seq ?? 0) + 1 }))
1098 // a run that has ended is read once more, then left alone
1099 if (!isLive) { tracer?.cancel(); tracer = undefined }
1100}
1101
1102// Builds the asked run's trace (all rows when `force` or new), then its window.
1103// Resolves whether the run is still going.
1104async function buildRunTrace($: Engine, force: boolean): Promise<boolean> {
1105 const req = traceReq
1106 if (!req) return false
1107 const now = await $.clock.now()
1108 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
1109 // a finished run can sit in both lists for a moment: the live copy wins
1110 const byId = new Map<string, AgentNode>()
1111 for (const n of [...history, ...(await read($, nodes))]) byId.set(n.id, n)
1112 const all = [...byId.values()]
1113 const run = byId.get(req.run)
1114 if (!run) { traceSnap = undefined; return false }
1115 const scope = scopeNodes(all, { kind: 'node', id: run.id })
1116 const isLive = scope.some(n => n.status === 'running')
1117 const key = `${req.run}|${req.zoom}`
1118 if (force || !traceBuilt || traceBuilt.key !== key) traceBuilt = { key, at: now, ...await runTrace($, run, scope, all, req.zoom, now) }
1119 // one lane only, when asked: its rows and the arrows into and out of it
1120 const laneAt = req.lane ? traceBuilt.lanes.findIndex(L => L.id === req.lane) : -1
1121 const cut = laneAt >= 0 ? onlyLane(traceBuilt.rows, traceBuilt.lanes, laneAt) : { rows: traceBuilt.rows, lanes: traceBuilt.lanes }
1122 const win = traceWindow(cut.rows, req.offset, TRACE_WINDOW)
1123 traceSnap = {
1124 run: run.id, zoom: req.zoom, lanes: cut.lanes, total: cut.rows.length, offset: win.offset, rows: win.rows.map(trimRow), missing: traceBuilt.missing,
1125 ...(traceBuilt.storyBy ? { storyBy: traceBuilt.storyBy } : {}),
1126 ...(laneAt >= 0 ? { lane: req.lane } : {}),
1127 marks: traceMarks(cut.rows),
1128 ...(req.query ? { query: req.query, hits: traceHits(cut.rows, req.query) } : {}),
1129 }
1130 return isLive
1131}
1132
1133// A run's whole trace at a zoom, read from its agents' transcripts.
1134async function runTrace($: Engine, run: AgentNode, scope: AgentNode[], all: AgentNode[], zoom: TraceZoom, now: number) {
1135 const agents = scope.filter(n => n.kind === 'agent')
1136 await locateTranscripts($, agents, all)
1137 const events = new Map<string, TraceEvent[]>()
1138 for (const a of agents) {
1139 const path = transcriptAt.get(a.id)
1140 const got = path ? await transcriptEvents($, a.id, path, a.status === 'running', now) : undefined
1141 if (got) events.set(a.id, got)
1142 }
1143 const stories = new Map(agents.flatMap(a => (a.story?.steps.length ? [[a.id, a.story.steps] as [string, string[]]] : [])))
1144 const storyTokens = agents.reduce((sum, a) => sum + (a.story?.tokens ?? 0), 0)
1145 const storyBy = zoom === 'story' && stories.size ? `${TIER_NAME.haiku}${storyTokens ? ` · ${kTokens(storyTokens)} tokens` : ''}` : undefined
1146 return { ...buildTrace(run, scope, events, now, zoom, stories), ...(storyBy ? { storyBy } : {}) }
1147}
1148
1149// ── x: a run's timeline or trace, saved as a picture ──────────────────────────
1150// SVG always; PNG beside it when rsvg-convert is installed. ImageMagick is not used:
1151// a build without Freetype drops the text of an SVG.
1152const PICTURE_W = 1100
1153let exported: { seq: number; text: string } | undefined
1154
1155async function exportPicture($: Engine, runId: string, lens: 'timeline' | 'trace', zoom: TraceZoom, focus?: string) {
1156 const now = await $.clock.now()
1157 const history = ((await $.store.get(HISTORY)) as AgentNode[] | undefined) ?? []
1158 const byId = new Map<string, AgentNode>()
1159 for (const n of [...history, ...(await read($, nodes))]) byId.set(n.id, n)
1160 const all = [...byId.values()]
1161 const run = byId.get(runId)
1162 if (!run) return
1163 const t = DESK[themeName]
1164 const scope = scopeNodes(all, { kind: 'node', id: run.id })
1165 const agents = scope.filter(n => n.kind === 'agent')
1166 const end = Math.max(run.endedAt ?? now, ...agents.map(a => (a.status === 'running' ? now : a.endedAt ?? now)))
1167 const when = new Date(run.startedAt)
1168 const stamp = `${when.getFullYear()}-${String(when.getMonth() + 1).padStart(2, '0')}-${String(when.getDate()).padStart(2, '0')}-${String(when.getHours()).padStart(2, '0')}${String(when.getMinutes()).padStart(2, '0')}`
1169 const subtitle = `${when.toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })} · ${agents.length} agent${agents.length === 1 ? '' : 's'} · ${pictureDuration(end - run.startedAt)}`
1170 let svg: string
1171 if (lens === 'timeline') {
1172 const path = criticalPath(agents, now)
1173 const idle = idleGaps(agents, now)
1174 const onPath = new Set(path?.ids ?? [])
1175 const bars: TimeBar[] = timelineRows(run, all, [], 'all').map(r => (r.kind === 'label'
1176 ? { label: r.text, start: 0, end: 0, status: 'done' as const, isHeader: true }
1177 : { label: r.node.label, start: r.node.startedAt, end: r.node.status === 'running' ? now : r.node.endedAt ?? now, status: r.node.status, isCritical: onPath.has(r.node.id) }))
1178 const real = bars.filter(b => !b.isHeader)
1179 if (!real.length) return note($, 'Nothing to draw: this run has no agents.')
1180 const from = Math.min(...real.map(b => b.start))
1181 const to = Math.max(...real.map(b => b.end))
1182 const inner = timelineSvg(t, bars, from, to, PICTURE_W, { idle: idle.gaps })
1183 const legend = [...(path && path.ids.length ? [`outlined: critical path (${path.ids.length})`] : []), ...(idle.ms ? [`shaded: idle ${pictureDuration(idle.ms)}`] : [])]
1184 svg = pictureSvg(t, `${run.label} — timeline`, subtitle, legend, inner, PICTURE_W, timelineHeight(bars.length))
1185 } else {
1186 const built = await runTrace($, run, scope, all, zoom, now)
1187 if (!built.rows.length) return note($, 'Nothing to draw: no steps were recorded for this run.')
1188 const timed = built.rows.filter(r => r.at > 0)
1189 const from = Math.min(...timed.map(r => r.at))
1190 const to = Math.max(...timed.map(r => r.end ?? r.at))
1191 const marks = built.rows.map(r => ({ lane: r.lane, ...(r.to !== undefined ? { to: r.to } : {}), at: r.at || from, kind: r.kind, text: r.text }))
1192 const at = focus ? built.lanes.findIndex(L => L.id === focus) : -1
1193 const inner = traceSvg(t, built.lanes, marks, from, to, PICTURE_W, at >= 0 ? at : undefined)
1194 svg = pictureSvg(t, `${run.label} — trace`, `${subtitle} · ${zoom} zoom`, ['● call · ◆ edit · ✕ ended', 'arrow: started or handed back', 'dashed arrow: message'], inner, PICTURE_W, 24 + built.lanes.length * 40 + 8)
1195 }
1196 const home = await $.env.get('HOME')
1197 const base = `${home ?? '.'}/Downloads/agent-tree/${slug(run.label)}-${lens}-${stamp}`
1198 try {
1199 await $.fs.write(`${base}.svg`, svg)
1200 } catch {hooks/theme.ts 199 lines1import type { AgentNode, NodeStatus } from '../types'
2
3// Four looks, chosen in /config: minimal works on every terminal (plain Unicode,
4// one accent); kitty, fish and dog are playful (emoji, which take two cells), each
5// telling one small story: cats out exploring, lines cast for a catch, dogs on walks.
6// Running wears the theme's accent and done is calm, so a live run looks like its theme;
7// warn means "needs a look". Every status has its own icon, so none rests on red vs green.
8export type ThemeName = 'kitty' | 'fish' | 'dog' | 'minimal'
9export const THEME_NAMES: readonly ThemeName[] = ['minimal', 'kitty', 'fish', 'dog']
10
11export type Palette = {
12 ink: string; soft: string; muted: string; faint: string; rule: string; frame: string
13 accent: string; selBg: string; ok: string; warn: string; bad: string; add: string; del: string
14}
15
16export type Theme = {
17 name: ThemeName
18 c: Palette
19 status: Record<NodeStatus, { icon: string; word: string; color: string }>
20 // the running glyph's second frame, so a live row breathes
21 runningAlt: string
22 // One glyph per row means status. A second one appears only for what holds
23 // others (a workflow, a cluster) and for files; a plain agent gets none.
24 kind: { workflow: string; group: string; file: string }
25 bar: { full: string; empty: string }
26 // the mark on a warning: a quiet agent, a file two agents edited
27 warn: string
28 fold: { open: string; closed: string }
29 cursor: string
30 words: { live: string; history: string; emptyLive: string; emptyHistory: string; emptyHint: string }
31 // A trace's lanes: one hue per agent, kept apart from the status colours, which mean state.
32 lanes: string[]
33 // the mark a failed agent leaves in its trace lane (kitty's takes two cells)
34 traceFail: string
35 // the words a quiet gap reads in a trace
36 quiet: string
37}
38
39const MINIMAL: Theme = {
40 name: 'minimal',
41 c: {
42 ink: '#d4d7de', soft: '#b3b8c3', muted: '#8a909c', faint: '#5c626d', rule: '#3a3f48', frame: '#4a505b',
43 accent: '#7aa2f7', selBg: '#2a2f38', ok: '#9ece6a', warn: '#e0af68', bad: '#f7768e', add: '#9ece6a', del: '#f7768e',
44 },
45 status: {
46 running: { icon: '●', word: 'Running', color: '#7aa2f7' },
47 done: { icon: '✓', word: 'Done', color: '#8a909c' },
48 failed: { icon: '✗', word: 'Failed', color: '#f7768e' },
49 killed: { icon: '■', word: 'Stopped', color: '#8a909c' },
50 },
51 runningAlt: '○',
52 kind: { workflow: '◆', group: '◇', file: '·' },
53 bar: { full: '▰', empty: '▱' },
54 warn: '⚠',
55 fold: { open: '▾', closed: '▸' },
56 cursor: '▌',
57 words: {
58 live: 'Running', history: 'Finished',
59 emptyLive: 'Nothing is running right now.', emptyHistory: 'No finished runs yet.',
60 emptyHint: 'Subagents and workflows appear here while they run, then move to History.',
61 },
62 lanes: ['#7aa2f7', '#bb9af7', '#7dcfff', '#73daca', '#ff9e64', '#c0caf5'],
63 traceFail: '✗',
64 quiet: 'quiet',
65}
66
67const KITTY: Theme = {
68 name: 'kitty',
69 c: {
70 ink: '#f4e4d8', soft: '#e3c9b8', muted: '#b8968a', faint: '#7a5f62', rule: '#4a3346', frame: '#ff8f70',
71 accent: '#ff8f70', selBg: '#3d2838', ok: '#a6d189', warn: '#f5c27a', bad: '#f38ba8', add: '#a6d189', del: '#f38ba8',
72 },
73 status: {
74 running: { icon: '🐱', word: 'Running', color: '#ff8f70' },
75 done: { icon: '😺', word: 'Done', color: '#b8968a' },
76 failed: { icon: '😿', word: 'Failed', color: '#f38ba8' },
77 killed: { icon: '🙀', word: 'Stopped', color: '#b8968a' },
78 },
79 runningAlt: '🐈',
80 kind: { workflow: '🧶', group: '🐾', file: '🧾' },
81 bar: { full: '▰', empty: '▱' },
82 warn: '⚠',
83 fold: { open: '▾', closed: '▸' },
84 cursor: '▌',
85 words: {
86 live: 'Out exploring', history: 'Back home',
87 emptyLive: 'ᓚᘏᗢ zzz · No cats out.', emptyHistory: 'No cats have come home yet.',
88 emptyHint: 'Subagents and workflows (🧶) appear here while they run, then move to History.',
89 },
90 lanes: ['#ff8f70', '#c9a0dc', '#89dceb', '#94e2d5', '#fab387', '#f5e0dc'],
91 traceFail: '😿',
92 quiet: 'ᓚᘏᗢ zzz',
93}
94
95// Lines cast for a catch: lake blues, a fin-orange frame. A failure got away.
96const FISH: Theme = {
97 name: 'fish',
98 c: {
99 ink: '#dcebf3', soft: '#b5cfdc', muted: '#86a5b5', faint: '#56748a', rule: '#22394b', frame: '#4fb3d9',
100 accent: '#4fb3d9', selBg: '#173042', ok: '#8bd5a0', warn: '#f2c26b', bad: '#f28b82', add: '#8bd5a0', del: '#f28b82',
101 },
102 status: {
103 running: { icon: '🎣', word: 'Running', color: '#4fb3d9' },
104 done: { icon: '🐟', word: 'Done', color: '#86a5b5' },
105 failed: { icon: '🐡', word: 'Failed', color: '#f28b82' },
106 killed: { icon: '🪝', word: 'Stopped', color: '#86a5b5' },
107 },
108 runningAlt: '🌊',
109 kind: { workflow: '🛶', group: '🐠', file: '🧾' },
110 bar: { full: '▰', empty: '▱' },
111 warn: '⚠',
112 fold: { open: '▾', closed: '▸' },
113 cursor: '▌',
114 words: {
115 live: 'Out fishing', history: 'The catch',
116 emptyLive: '><(((º> · Lines are dry.', emptyHistory: 'Nothing in the bucket yet.',
117 emptyHint: 'Subagents and workflows (🛶) appear here while they run, then move to History.',
118 },
119 lanes: ['#4fb3d9', '#b4a0f0', '#7fdbd0', '#f29b38', '#e6a5c8', '#c9d6df'],
120 traceFail: '🐡',
121 quiet: '><> zzz',
122}
123
124// Dogs out on walks, back with what they fetched: golden tan and warm browns.
125const DOG: Theme = {
126 name: 'dog',
127 c: {
128 ink: '#f3e6d6', soft: '#dcc6ad', muted: '#b09a82', faint: '#77634f', rule: '#43352a', frame: '#e6a85a',
129 accent: '#e6a85a', selBg: '#3a2d22', ok: '#a6d189', warn: '#f5d76e', bad: '#f08a7a', add: '#a6d189', del: '#f08a7a',
130 },
131 status: {
132 running: { icon: '🐕', word: 'Running', color: '#e6a85a' },
133 done: { icon: '🐶', word: 'Done', color: '#b09a82' },
134 failed: { icon: '🥺', word: 'Failed', color: '#f08a7a' },
135 killed: { icon: '🦴', word: 'Stopped', color: '#b09a82' },
136 },
137 runningAlt: '🦮',
138 kind: { workflow: '🎾', group: '🐾', file: '🧾' },
139 bar: { full: '▰', empty: '▱' },
140 warn: '⚠',
141 fold: { open: '▾', closed: '▸' },
142 cursor: '▌',
143 words: {
144 live: 'Out on walks', history: 'Fetched',
145 emptyLive: 'U・ᴥ・U zzz · No dogs out.', emptyHistory: 'No dogs are back from walks yet.',
146 emptyHint: 'Subagents and workflows (🎾) appear here while they run, then move to History.',
147 },
148 lanes: ['#e6a85a', '#9fb7e8', '#7fcfb8', '#d9a0c8', '#c8e04a', '#d6c8b8'],
149 traceFail: '🥺',
150 quiet: 'U-ᴥ-U zzz',
151}
152
153export const THEMES: Record<ThemeName, Theme> = { minimal: MINIMAL, kitty: KITTY, fish: FISH, dog: DOG }
154// An unknown name (an old setting, a typo) falls back to minimal.
155export const themeNameOf = (name: unknown): ThemeName =>
156 THEME_NAMES.includes(name as ThemeName) ? (name as ThemeName) : 'minimal'
157export const themeOf = (name: unknown): Theme => THEMES[themeNameOf(name)]
158
159// The glyph a row shows for what a node is: only what holds others has one.
160export function kindGlyph(t: Theme, n: Pick<AgentNode, 'kind'>): string {
161 if (n.kind === 'workflow') return t.kind.workflow
162 if (n.kind === 'group') return t.kind.group
163 return ''
164}
165
166// ── display width: how many terminal cells a string takes ──────────────────
167const ZERO = (cp: number) => (cp >= 0x300 && cp <= 0x36f) || cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f)
168const WIDE = (cp: number) =>
169 cp >= 0x1f000 ||
170 (cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) ||
171 (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) || (cp >= 0xffe0 && cp <= 0xffe6)
172
173export function cellWidth(s: string): number {
174 let w = 0
175 for (const ch of s) {
176 const cp = ch.codePointAt(0)!
177 w += ZERO(cp) ? 0 : WIDE(cp) ? 2 : 1
178 }
179 return w
180}
181
182// Cut to a width in cells, ending with … when anything was cut.
183export function fit(s: string, width: number): string {
184 if (width <= 0) return ''
185 if (cellWidth(s) <= width) return s
186 let out = ''
187 let w = 0
188 for (const ch of s) {
189 const cw = cellWidth(ch)
190 if (w + cw > width - 1) break
191 out += ch
192 w += cw
193 }
194 return out + '…'
195}
196
197export const padEnd = (s: string, width: number) => s + ' '.repeat(Math.max(0, width - cellWidth(s)))
198export const padStart = (s: string, width: number) => ' '.repeat(Math.max(0, width - cellWidth(s))) + s
199hooks/list.ts 681 lines1import type { Act, AgentNode, EditRecord } from '../types'
2
3// Subagents are cats, workflow agents sea creatures, a workflow its lead creature.
4export type Species = 'cat' | 'sea' | 'school'
5export const speciesOf = (n: Pick<AgentNode, 'kind'>, inWorkflow: boolean): Species =>
6 n.kind !== 'agent' ? 'school' : inWorkflow ? 'sea' : 'cat'
7
8const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
9const baseName = (p: string) => p.split('/').filter(Boolean).pop() ?? p
10const firstLine = (s: string) => s.split('\n')[0]?.trim() ?? ''
11const hostOf = (url: string) => /^[a-z]+:\/\/([^/]+)/i.exec(url)?.[1] ?? url
12const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
13
14// What a tool call is doing, as a sentence a person reads, and the prop the icon holds.
15export function describeTool(tool: string, input: Record<string, unknown>): { act: Act; activity: string } {
16 const s = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : '')
17 switch (tool) {
18 case 'Read': return { act: 'read', activity: `Reading ${baseName(s('file_path'))}` }
19 case 'Grep': return { act: 'read', activity: `Searching the code for "${clip(s('pattern'), 32)}"` }
20 case 'Glob': return { act: 'read', activity: `Looking for files matching ${clip(s('pattern'), 32)}` }
21 case 'LS': return { act: 'read', activity: `Listing ${baseName(s('path'))}` }
22 case 'ToolSearch': return { act: 'read', activity: 'Looking up tools' }
23 case 'LSP': return { act: 'read', activity: 'Asking the language server' }
24 case 'Edit':
25 case 'MultiEdit': return { act: 'write', activity: `Editing ${baseName(s('file_path'))}` }
26 case 'Write': return { act: 'write', activity: `Writing ${baseName(s('file_path'))}` }
27 case 'NotebookEdit': return { act: 'write', activity: `Editing ${baseName(s('notebook_path'))}` }
28 // a Bash call's own description says what it does in words; the command is the fallback
29 case 'Bash': return { act: 'run', activity: s('description') ? clip(s('description'), 60) : `Running ${clip(firstLine(s('command')), 40)}` }
30 case 'Monitor': return { act: 'run', activity: 'Watching a process' }
31 case 'Agent':
32 case 'Task': return { act: 'run', activity: `Handing off: ${clip(s('description'), 36)}` }
33 case 'Workflow': return { act: 'run', activity: 'Starting a workflow' }
34 case 'WebFetch': return { act: 'web', activity: `Reading ${hostOf(s('url'))}` }
35 case 'WebSearch': return { act: 'web', activity: `Searching the web for "${clip(s('query'), 30)}"` }
36 }
37 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
38 if (mcp) return { act: 'web', activity: `Calling ${mcp[1]?.replace(/^claude_ai_/, '')} · ${mcp[2]?.replace(/_/g, ' ')}` }
39 return { act: 'think', activity: `Using ${tool}` }
40}
41
42const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
43export const editedPath = (tool: string, input: Record<string, unknown>): string | undefined => {
44 if (!EDIT_TOOLS.has(tool)) return undefined
45 const p = input.file_path ?? input.notebook_path
46 return typeof p === 'string' ? p : undefined
47}
48
49// "Read 3 files, edited 1, ran 2 commands": what an agent did, from its tool counts.
50export function workSummary(n: Pick<AgentNode, 'work' | 'changes' | 'tools'>): string {
51 const w = n.work ?? {}
52 const edited = Object.keys(n.changes ?? {}).length
53 const parts = [
54 w.read ? `read ${plural(w.read, 'file')}` : '',
55 edited ? `edited ${plural(edited, 'file')}` : '',
56 w.run ? `ran ${plural(w.run, 'command')}` : '',
57 w.web ? `${plural(w.web, 'web call')}` : '',
58 ].filter(Boolean)
59 if (parts.length === 0) return n.tools ? plural(n.tools, 'tool call') : 'No tools used'
60 const s = parts.join(', ')
61 return s[0]!.toUpperCase() + s.slice(1)
62}
63
64const lineCount = (s: unknown) => (typeof s === 'string' && s.length > 0 ? s.split('\n').length : 0)
65
66// What one edit did to one file, in lines, like a diffstat.
67export function editStats(tool: string, input: Record<string, unknown>): { path: string; added: number; removed: number } | undefined {
68 const path = editedPath(tool, input)
69 if (!path) return undefined
70 if (tool === 'Edit') return { path, added: lineCount(input.new_string), removed: lineCount(input.old_string) }
71 if (tool === 'MultiEdit') {
72 const edits = Array.isArray(input.edits) ? (input.edits as { old_string?: unknown; new_string?: unknown }[]) : []
73 return { path, added: edits.reduce((a, e) => a + lineCount(e.new_string), 0), removed: edits.reduce((a, e) => a + lineCount(e.old_string), 0) }
74 }
75 if (tool === 'Write') return { path, added: lineCount(input.content), removed: 0 }
76 return { path, added: lineCount(input.new_source), removed: 0 }
77}
78
79export type FileRow = { path: string; added: number; removed: number; edits: number; by: { node: AgentNode; added: number; removed: number; edits: number }[] }
80
81// Every file the given agents changed, with who changed it: the trail from a file back to its agents.
82export function fileRows(scope: AgentNode[]): FileRow[] {
83 const rows = new Map<string, FileRow>()
84 for (const n of scope) {
85 for (const [path, c] of Object.entries(n.changes ?? {})) {
86 const row = rows.get(path) ?? { path, added: 0, removed: 0, edits: 0, by: [] }
87 row.added += c.added
88 row.removed += c.removed
89 row.edits += c.edits
90 row.by.push({ node: n, ...c })
91 rows.set(path, row)
92 }
93 }
94 return [...rows.values()].sort((a, b) => b.added + b.removed - (a.added + a.removed) || a.path.localeCompare(b.path))
95}
96
97// Paths shown relative to what they share, so "hooks/view.tsx", not a 90-column absolute path.
98export function shortPaths(paths: string[]): Map<string, string> {
99 const split = paths.map(p => p.split('/'))
100 let common = 0
101 if (split.length > 0) {
102 const first = split[0]!
103 while (common < first.length - 1 && split.every(s => s.length - 1 > common && s[common] === first[common])) common++
104 }
105 // keep one directory of context when every file sits in the same folder
106 const keep = Math.max(0, Math.min(common, ...split.map(s => s.length - 2)))
107 return new Map(paths.map((p, i) => [p, split[i]!.slice(paths.length === 1 ? Math.max(0, split[i]!.length - 2) : keep).join('/')]))
108}
109
110export const diffstat = (added: number, removed: number) => `+${added} −${removed}`
111
112export type DiffLine = { op: ' ' | '+' | '-'; text: string; oldNo?: number; newNo?: number }
113
114// A line diff of one edit's before and after, numbered from where it sits in the
115// file: a longest-common-subsequence walk, as `diff` does, so context lines the edit
116// repeated are context, not a removal and an addition.
117export function lineDiff(before: string, after: string, start = 1): DiffLine[] {
118 const a = before ? before.split('\n') : []
119 const b = after ? after.split('\n') : []
120 const out: DiffLine[] = []
121 if (a.length * b.length > 400_000) {
122 a.forEach((text, i) => out.push({ op: '-', text, oldNo: start + i }))
123 b.forEach((text, i) => out.push({ op: '+', text, newNo: start + i }))
124 return out
125 }
126 const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0))
127 for (let i = a.length - 1; i >= 0; i--) {
128 for (let j = b.length - 1; j >= 0; j--) {
129 lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!)
130 }
131 }
132 let i = 0
133 let j = 0
134 while (i < a.length || j < b.length) {
135 if (i < a.length && j < b.length && a[i] === b[j]) { out.push({ op: ' ', text: a[i]!, oldNo: start + i, newNo: start + j }); i++; j++ }
136 // removals before additions, as diff prints them
137 else if (i < a.length && (j >= b.length || lcs[i + 1]![j]! >= lcs[i]![j + 1]!)) { out.push({ op: '-', text: a[i]!, oldNo: start + i }); i++ }
138 else { out.push({ op: '+', text: b[j]!, newNo: start + j }); j++ }
139 }
140 return out
141}
142
143export const diffCounts = (lines: DiffLine[]) => ({
144 added: lines.filter(l => l.op === '+').length,
145 removed: lines.filter(l => l.op === '-').length,
146})
147
148// What one tool call wrote, as before/after text and where it sits: one record per
149// change, so a file's diff can be told edit by edit, each with the agent that made it.
150export function editRecords(tool: string, input: Record<string, unknown>, before: string | undefined, after: string | undefined): { path: string; old: string; new: string; line: number; isNew?: boolean }[] {
151 const path = editedPath(tool, input)
152 if (!path) return []
153 const lineOf = (text: string) => {
154 const at = after && text ? after.indexOf(text) : -1
155 return at < 0 ? 1 : after!.slice(0, at).split('\n').length
156 }
157 const str = (x: unknown) => (typeof x === 'string' ? x : '')
158 if (tool === 'Edit') return [{ path, old: str(input.old_string), new: str(input.new_string), line: lineOf(str(input.new_string)) }]
159 if (tool === 'MultiEdit') {
160 const edits = Array.isArray(input.edits) ? (input.edits as { old_string?: unknown; new_string?: unknown }[]) : []
161 return edits.map(e => ({ path, old: str(e.old_string), new: str(e.new_string), line: lineOf(str(e.new_string)) }))
162 }
163 if (tool === 'Write') return [{ path, old: before ?? '', new: str(input.content), line: 1, isNew: before === undefined }]
164 return [{ path, old: '', new: str(input.new_source), line: 1 }]
165}
166
167// "Draft 2 done → Refine 1 running": a workflow's phases in words.
168export function phaseWords(p: { phase: string; total: number; running: number; done: number; failed: number; stopped: number }): string {
169 const parts = [
170 p.running ? `${p.running} running` : '',
171 p.done ? `${p.done} done` : '',
172 p.failed ? `${p.failed} failed` : '',
173 p.stopped ? `${p.stopped} stopped` : '',
174 ].filter(Boolean)
175 return parts.join(', ') || 'waiting'
176}
177
178// The heading over a run's own answer: it says so when the pane keeps only its start.
179export function reportHeading(n: AgentNode): string {
180 const whole = n.kind === 'workflow' ? 'Final result' : 'Full report'
181 const shown = n.result?.length ?? 0
182 if (!n.resultLength || n.resultLength <= shown) return whole
183 return `${n.kind === 'workflow' ? 'Final result' : 'Report'} (first ${shown} of ${n.resultLength.toLocaleString('en-US')} characters)`
184}
185
186// A workflow's return value is often JSON: its strings, joined, read better than its braces.
187export function readableResult(s: string | undefined): string {
188 if (!s) return ''
189 const t = s.trim()
190 if (!t.startsWith('{') && !t.startsWith('[')) return plain(t)
191 try {
192 const strings: string[] = []
193 const walk = (v: unknown) => {
194 if (typeof v === 'string') strings.push(v)
195 else if (Array.isArray(v)) v.forEach(walk)
196 else if (v && typeof v === 'object') Object.values(v).forEach(walk)
197 }
198 walk(JSON.parse(t))
199 return plain(strings.join(' '))
200 } catch { return plain(t) }
201}
202
203export function changesLine(rows: readonly FileRow[]): string {
204 if (rows.length === 0) return 'No files changed'
205 const added = rows.reduce((a, r) => a + r.added, 0)
206 const removed = rows.reduce((a, r) => a + r.removed, 0)
207 return `Changed ${plural(rows.length, 'file')} (${diffstat(added, removed)})`
208}
209
210// A workflow's phases in order with their agents' counts: "Explore ✓3 → Verify ●2 ✓1".
211export function pipeline(wf: AgentNode, nodes: AgentNode[]) {
212 const kids = nodes.filter(n => n.parentId === wf.id)
213 const order = [...(wf.phases ?? [])]
214 for (const k of kids) if (!order.includes(k.phase ?? 'Agents')) order.push(k.phase ?? 'Agents')
215 return order.map(phase => ({ phase, ...counts(kids.filter(k => (k.phase ?? 'Agents') === phase)) }))
216}
217
218// The agents a scope covers: a run with everything under it, one phase, or one agent and its own subagents.
219export function scopeNodes(nodes: AgentNode[], scope: { kind: 'node'; id: string } | { kind: 'phase'; wfId: string; phase: string }): AgentNode[] {
220 if (scope.kind === 'phase') return nodes.filter(n => n.parentId === scope.wfId && (n.phase ?? 'Agents') === scope.phase)
221 const under = (id: string): AgentNode[] => nodes.filter(n => n.parentId === id).flatMap(k => [k, ...under(k.id)])
222 const root = nodes.find(n => n.id === scope.id)
223 return root ? [root, ...under(root.id)] : []
224}
225
226// ── emoji: a cat for a subagent; a workflow agent's own sea creature, fixed by its id ──
227const SEA = ['🐡', '🐠', '🐙', '🐟']
228const hash = (s: string) => {
229 let h = 2166136261
230 for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619)
231 return h >>> 0
232}
233export const markFor = (n: Pick<AgentNode, 'id' | 'kind'>, inWorkflow: boolean): string =>
234 n.kind === 'workflow' ? '🌊' : n.kind === 'group' ? '🐾' : inWorkflow ? SEA[hash(n.id) % SEA.length]! : '🐱'
235
236// Markdown to one plain line: headings, emphasis, code marks, links and list bullets go.
237export function plain(s: string | undefined): string {
238 return (s ?? '')
239 .replace(/```[\s\S]*?```/g, ' ')
240 .replace(/^\s{0,3}#{1,6}\s+/gm, '')
241 .replace(/^\s*[-*+]\s+/gm, '')
242 .replace(/^\s*\d+\.\s+/gm, '')
243 .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
244 .replace(/(\*\*|__|\*|_|`)/g, '')
245 .replace(/\s+/g, ' ')
246 .trim()
247}
248
249export const firstSentence = (s: string | undefined, max = 140) => {
250 const p = plain(s)
251 const m = /^(.+?[.!?])(\s|$)/.exec(p)
252 return clip(m?.[1] ?? p, max)
253}
254
255export function prettyModel(m: string | undefined): string | undefined {
256 if (!m) return undefined
257 const x = /(haiku|sonnet|opus|fable)(?:-(\d+)-(\d+))?/i.exec(m)
258 if (!x) return m
259 const name = x[1]![0]!.toUpperCase() + x[1]!.slice(1).toLowerCase()
260 return x[2] ? `${name} ${x[2]}.${x[3]}` : name
261}
262
263export function prettyType(n: Pick<AgentNode, 'kind' | 'type'>, inWorkflow: boolean): string {
264 if (n.kind === 'workflow') return 'Workflow'
265 if (n.kind === 'group') return 'Agent group'
266 const t = n.type
267 if (!t) return inWorkflow ? 'Workflow agent' : 'Agent'
268 const name = t.includes(':') ? t.split(':').pop()! : t
269 const words = name.replace(/[-_]/g, ' ')
270 return `${words[0]!.toUpperCase()}${words.slice(1)} agent`
271}
272
273export const whereLabel = (w: AgentNode['where']) =>
274 w === 'worktree' ? 'Own worktree' : w === 'remote' ? 'Remote' : 'Main checkout'
275
276export type JournalEntry = { agentId: string; label?: string; phase?: string; isDone: boolean }
277
278// A workflow run's journal.jsonl: a `started` line per agent (id, label, phase), a `result` line as each ends.
279export function parseJournal(text: string): JournalEntry[] {
280 const byId = new Map<string, JournalEntry>()
281 for (const line of text.split('\n')) {
282 if (!line.trim()) continue
283 let row: { type?: unknown; agentId?: unknown; label?: unknown; phase?: unknown }
284 try { row = JSON.parse(line) } catch { continue }
285 if (typeof row.agentId !== 'string') continue
286 const cur = byId.get(row.agentId) ?? { agentId: row.agentId, isDone: false }
287 if (row.type === 'started') {
288 if (typeof row.label === 'string') cur.label = row.label
289 if (typeof row.phase === 'string') cur.phase = row.phase
290 } else if (row.type === 'result') {
291 cur.isDone = true
292 }
293 byId.set(row.agentId, cur)
294 }
295 return [...byId.values()]
296}
297
298// The task an agent was given. A workflow agent's transcript opens with harness
299// frames: the relayed user request (skipped: it is the user's, not the agent's
300// task) and the computed task, whose text follows "follows:" indented two spaces.
301export function firstPrompt(jsonl: string): string | undefined {
302 for (const line of jsonl.split('\n').slice(0, 20)) {
303 let row: { message?: { role?: unknown; content?: unknown } }
304 try { row = JSON.parse(line) } catch { continue }
305 const m = row.message
306 if (m?.role !== 'user') continue
307 const text = typeof m.content === 'string'
308 ? m.content
309 : Array.isArray(m.content)
310 ? m.content.map(b => (b && typeof b === 'object' && 'text' in b ? String(b.text) : '')).join('\n').trim()
311 : ''
312 if (!text) continue
313 if (text.startsWith('[Workflow harness — user request]')) continue
314 if (text.startsWith('[Workflow harness')) {
315 const body = text.split(/follows:\s*\n/)[1]
316 return body ? body.split('\n').map(l => l.replace(/^ {2}/, '')).join('\n').trim() : undefined
317 }
318 return text
319 }
320 return undefined
321}
322
323// A digest reply: JSON with an outcome sentence and up to three points, tolerating fences and chatter.
324export function parseDigest(raw: string): { outcome?: string; points?: string[] } | undefined {
325 const json = /\{[\s\S]*\}/.exec(raw)?.[0]
326 if (!json) return undefined
327 try {
328 const d = JSON.parse(json) as { outcome?: unknown; points?: unknown }
329 const outcome = typeof d.outcome === 'string' ? plain(d.outcome).slice(0, 300) : undefined
330 const points = Array.isArray(d.points) ? d.points.filter((p): p is string => typeof p === 'string').map(p => plain(p).slice(0, 120)).slice(0, 3) : undefined
331 return { outcome, points }
332 } catch { return undefined }
333}
334
335// The report an agent handed back. Agents that end with a SubagentHandback call
336// leave no final text, so their report is that call's message; otherwise it is
337// the last text the agent wrote.
338export function handbackOf(transcript: string): string | undefined {
339 const lines = transcript.split('\n').filter(Boolean)
340 let lastText: string | undefined
341 for (let i = lines.length - 1; i >= 0; i--) {
342 let row: { message?: { role?: string; content?: unknown } }
343 try { row = JSON.parse(lines[i]!) } catch { continue }
344 const content = row.message?.role === 'assistant' && Array.isArray(row.message.content) ? row.message.content : []
345 for (const b of content as { type?: string; name?: string; text?: string; input?: { message?: unknown } }[]) {
346 if (b.type === 'tool_use' && b.name === 'SubagentHandback' && typeof b.input?.message === 'string') return b.input.message
347 if (b.type === 'text' && b.text?.trim() && lastText === undefined) lastText = b.text
348 }
349 }
350 return lastText
351}
352
353// A root folder as Claude Code names its projects folder: every character
354// that is not a letter or digit becomes '-'. Runs compare by this key.
355export const folderKey = (path: string) => path.replace(/[^a-zA-Z0-9]/g, '-')
356export const runKey = (n: { repo?: string; repoKey?: string }) => n.repoKey ?? (n.repo ? folderKey(n.repo) : undefined)
357
358// Why a finished agent has no report, in words, instead of a bare "No report".
359export function noReportReason(n: { status: string }): string {
360 if (n.status === 'running') return 'Still working.'
361 if (n.status === 'failed') return 'Stopped with an error before it reported.'
362 if (n.status === 'killed') return 'Stopped before it reported.'
363 return 'Finished without a written report.'
364}
365
366// Task text as a person reads it: runs recorded before the harness-aware reader kept the frames.
367export function taskText(prompt: string | undefined): string {
368 if (!prompt) return ''
369 if (prompt.startsWith('[Workflow harness — user request]')) return ''
370 if (prompt.startsWith('[Workflow harness')) return plain(prompt.split(/follows:\s*/)[1] ?? '')
371 return plain(prompt)
372}
373
374export function cleanTitle(raw: string): string | undefined {
375 const t = firstLine(raw).replace(/^["'`*#\s]+|["'`*.\s]+$/g, '').replace(/^title:\s*/i, '')
376 return t && t.length <= 80 ? t : undefined
377}
378
379export type Filter = 'all' | 'running' | 'failed'
380export type Group = 'none' | 'type' | 'where' | 'status'
381export const GROUPS: Group[] = ['none', 'type', 'where', 'status']
382export const GROUP_NAMES: Record<Group, string> = { none: 'no grouping', type: 'by type', where: 'by worktree', status: 'by status' }
383
384// A row of the run list or of a run's tree. `guide` is the tree's drawing to the
385// left of the row (├─ └─ │), `fold` a row that holds others and can open or close.
386export type Fold = { key: string; isOpen: boolean }
387export type Item =
388 | { kind: 'node'; node: AgentNode; species: Species; depth: number; guide?: string; fold?: Fold }
389 | { kind: 'phase'; key: string; wfId: string; phase: string; isOpen: boolean; total: number; done: number; failed: number; running: number; stopped: number; guide?: string }
390 | { kind: 'more'; key: string; count: number; guide?: string }
391 // a heading over rows; History's day headings carry a note and Older folds
392 | { kind: 'header'; text: string; count?: number; note?: string; isOpen?: boolean }
393 // a line under a cluster's row: its aspects, a file overlap, its combined outcome
394 | { kind: 'info'; tone: 'chips' | 'warn' | 'outcome'; nodeId: string; guide: string }
395 // a line of a pattern card on the History page: its title, evidence or what to try
396 | { kind: 'pattern'; tone: 'title' | 'evidence' | 'try'; text: string }
397
398export const isSelectable = (it: Item | undefined) => it !== undefined && it.kind !== 'header' && it.kind !== 'info' && it.kind !== 'pattern'
399
400// Live and History as one list. A run that just finished is in both, so each id
401// is kept once, and the live copy wins: it is the newer one.
402export function joinNodes(live: AgentNode[], history: AgentNode[]): AgentNode[] {
403 const seen = new Set(live.map(n => n.id))
404 return [...live, ...history.filter(n => !seen.has(n.id))]
405}
406
407export function childrenOf(nodes: AgentNode[], id: string) {
408 return nodes.filter(n => n.parentId === id)
409}
410
411export function counts(kids: AgentNode[]) {
412 const c = { total: kids.length, running: 0, done: 0, failed: 0, stopped: 0 }
413 for (const k of kids) {
414 if (k.status === 'running') c.running++
415 else if (k.status === 'failed') c.failed++
416 else if (k.status === 'killed') c.stopped++
417 else c.done++
418 }
419 return c
420}
421
422export const passes = (n: AgentNode, kids: AgentNode[], f: Filter) =>
423 f === 'all' ||
424 (f === 'running' && (n.status === 'running' || kids.some(k => k.status === 'running'))) ||
425 (f === 'failed' && (n.status === 'failed' || kids.some(k => k.status === 'failed')))
426
427const DAY = 86_400_000
428export const dayLabel = (t: number, now: number) => {
429 const startOf = (x: number) => { const d = new Date(x); d.setHours(0, 0, 0, 0); return d.getTime() }
430 const diff = Math.round((startOf(now) - startOf(t)) / DAY)
431 if (diff === 0) return 'Today'
432 if (diff === 1) return 'Yesterday'
433 return new Date(t).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })
434}
435
436const STATUS_GROUP: Record<AgentNode['status'], string> = { running: 'Running', failed: 'Failed', done: 'Done', killed: 'Stopped' }
437const groupOf = (n: AgentNode, g: Group, now: number): string =>
438 g === 'type' ? prettyType(n, false).replace(/ agent$/, '') + (n.kind !== 'agent' ? 's' : ' agents')
439 : g === 'where' ? whereLabel(n.where)
440 : g === 'status' ? STATUS_GROUP[n.status]
441 : dayLabel(n.startedAt, now)
442
443// The top level: one row per subagent or workflow; a subagent's own subagents sit under it.
444// Live holds what is still running; a finished run moves to History. Rows sit under
445// group headers: the chosen grouping, or the day in History when there is none.
446export function topItems(
447 nodes: AgentNode[], filter: Filter, isHistory: boolean, now: number, group: Group = 'none',
448 flipped: readonly string[] = [], showDone: readonly string[] = [],
449): Item[] {
450 const ids = new Set(nodes.map(n => n.id))
451 const tops = nodes.filter(n => !n.parentId || !ids.has(n.parentId))
452 const sorted = isHistory
453 ? [...tops].sort((a, b) => b.startedAt - a.startedAt)
454 : [...tops].sort((a, b) => a.startedAt - b.startedAt)
455 const shown = sorted.filter(n => {
456 const kids = childrenOf(nodes, n.id)
457 if (!isHistory && n.status !== 'running' && !kids.some(k => k.status === 'running')) return false
458 return passes(n, kids, filter)
459 })
460 const useHeaders = group !== 'none' || isHistory
461 const buckets = new Map<string, AgentNode[]>()
462 for (const n of shown) {
463 const key = useHeaders ? groupOf(n, group, now) : ''
464 buckets.set(key, [...(buckets.get(key) ?? []), n])
465 }
466 const out: Item[] = []
467 for (const [key, list] of buckets) {
468 if (useHeaders) out.push({ kind: 'header', text: key, count: list.length })
469 // folded by default: the run list stays one row per run until one is opened
470 for (const n of list) emitTree(n, nodes, { filter, flipped, showDone }, out, { guide: '', prefix: '', depth: 0, defaultOpen: false })
471 }
472 return out
473}
474
475// ── the tree: a run and everything under it, with guide lines ─────────────
476
477type TreeOpts = { filter: Filter; flipped: readonly string[]; showDone: readonly string[] }
478type At = { guide: string; prefix: string; depth: number; defaultOpen: boolean }
479
480const isOpenNow = (key: string, byDefault: boolean, flipped: readonly string[]) => byDefault !== flipped.includes(key)
481const visibleKids = (nodes: AgentNode[], id: string, f: Filter) =>
482 childrenOf(nodes, id).filter(k => passes(k, childrenOf(nodes, k.id), f)).sort((a, b) => a.startedAt - b.startedAt)
483const branch = (prefix: string, isLast: boolean) => ({ guide: `${prefix}${isLast ? '└─ ' : '├─ '}`, prefix: `${prefix}${isLast ? ' ' : '│ '}` })
484
485// One node, then (when open) its cluster lines and its children: a group's members,
486// a workflow's phases and their agents, an agent's own subagents.
487function emitTree(n: AgentNode, nodes: AgentNode[], o: TreeOpts, out: Item[], at: At): void {
488 const isWorkflow = n.kind === 'workflow'
489 const kids = isWorkflow ? [] : visibleKids(nodes, n.id, o.filter)
490 const hasKids = isWorkflow ? childrenOf(nodes, n.id).length > 0 : kids.length > 0
491 // closed-by-default rows (the run list) and open-by-default rows (inside a run) keep separate keys
492 const key = `${at.defaultOpen ? 'o' : 'c'}:${n.id}`
493 const isOpen = hasKids && isOpenNow(key, at.defaultOpen, o.flipped)
494 out.push({ kind: 'node', node: n, species: speciesOf(n, !!n.phase), depth: at.depth, guide: at.guide, ...(hasKids ? { fold: { key, isOpen } } : {}) })
495 if (!isOpen) return
496 const more = hasKids ? `${at.prefix}│ ` : `${at.prefix} `
497 if (n.kind === 'group') {
498 // no aspect chips here: the members are the rows right below
499 if (overlaps(scopeNodes(nodes, { kind: 'node', id: n.id }).filter(k => k.id !== n.id)).length) out.push({ kind: 'info', tone: 'warn', nodeId: n.id, guide: more })
500 if (n.summary && n.status !== 'running') out.push({ kind: 'info', tone: 'outcome', nodeId: n.id, guide: more })
501 }
502 if (isWorkflow) return emitPhases(n, nodes, o, out, at)
503 kids.forEach((k, i) => emitTree(k, nodes, o, out, { ...branch(at.prefix, i === kids.length - 1), depth: at.depth + 1, defaultOpen: true }))
504}
505
506// A workflow's phases: one folding row each; a phase with nothing running or failed
507// folds to its row, and finished agents past the first few fold to a "… N done" row.
508function emitPhases(wf: AgentNode, nodes: AgentNode[], o: TreeOpts, out: Item[], at: At): void {
509 const kids = childrenOf(nodes, wf.id).sort((a, b) => a.startedAt - b.startedAt)
510 const order = [...(wf.phases ?? [])]
511 for (const k of kids) if (!order.includes(k.phase ?? 'Agents')) order.push(k.phase ?? 'Agents')
512 const phases = order
513 .map(phase => ({ phase, list: kids.filter(k => (k.phase ?? 'Agents') === phase && passes(k, [], o.filter)) }))
514 .filter(p => p.list.length > 0)
515 phases.forEach(({ phase, list }, pi) => {
516 const c = counts(list)
517 const key = `${wf.id}:${phase}`
518 const isOpen = (c.running > 0 || c.failed > 0) !== o.flipped.includes(key)
519 const b = branch(at.prefix, pi === phases.length - 1)
520 out.push({ kind: 'phase', key, wfId: wf.id, phase, isOpen, ...c, guide: b.guide })
521 if (!isOpen) return
522 const failed = list.filter(k => k.status === 'failed')
523 const running = list.filter(k => k.status === 'running')
524 const done = list.filter(k => k.status !== 'running' && k.status !== 'failed').sort((a, z) => (z.endedAt ?? 0) - (a.endedAt ?? 0))
525 const doneShown = o.showDone.includes(key) || done.length <= SHOWN_DONE + 1 ? done : done.slice(0, SHOWN_DONE)
526 const rows = [...failed, ...running, ...doneShown]
527 const hidden = done.length - doneShown.length
528 rows.forEach((n, i) => emitTree(n, nodes, o, out, { ...branch(b.prefix, i === rows.length - 1 && hidden === 0), depth: at.depth + 2, defaultOpen: true }))
529 if (hidden > 0) out.push({ kind: 'more', key, count: hidden, guide: branch(b.prefix, true).guide })
530 })
531}
532
533// Inside an opened run: the run's own row first, then its whole tree, open.
534export function runTree(run: AgentNode, nodes: AgentNode[], filter: Filter, flipped: readonly string[], showDone: readonly string[]): Item[] {
535 const out: Item[] = []
536 emitTree(run, nodes, { filter, flipped, showDone }, out, { guide: '', prefix: '', depth: 0, defaultOpen: true })
537 return out
538}
539
540// Files two or more agents of a scope edited: where parallel work can collide.
541export function overlaps(scope: AgentNode[]): { path: string; by: AgentNode[] }[] {
542 return fileRows(scope)
543 .map(r => ({ path: r.path, by: [...new Map(r.by.map(b => [b.node.id, b.node])).values()] }))
544 .filter(r => r.by.length >= 2)
545}
546
547// The agents a run or a top-level view covers, for the board, the timeline and the insights.
548export const leafAgents = (scope: AgentNode[]) => scope.filter(n => n.kind === 'agent')
549
550const SHOWN_DONE = 3
551
552// Inside a workflow: agents grouped by phase. A phase with nothing running or failed
553// folds to its header; finished agents past the first few fold to a "… N done" row.
554export function workflowItems(
555 wf: AgentNode, nodes: AgentNode[], filter: Filter, flipped: readonly string[], showDone: readonly string[],
556): Item[] {
557 const kids = childrenOf(nodes, wf.id).sort((a, b) => a.startedAt - b.startedAt)
558 const order = [...(wf.phases ?? [])]
559 for (const k of kids) if (!order.includes(k.phase ?? 'Agents')) order.push(k.phase ?? 'Agents')
560 const out: Item[] = []
561 for (const phase of order) {
562 const inPhase = kids.filter(k => (k.phase ?? 'Agents') === phase && passes(k, [], filter))
563 if (inPhase.length === 0) continue
564 const c = counts(inPhase)
565 const key = `${wf.id}:${phase}`
566 const isOpen = (c.running > 0 || c.failed > 0) !== flipped.includes(key)
567 out.push({ kind: 'phase', key, wfId: wf.id, phase, isOpen, ...c })
568 if (!isOpen) continue
569 const failed = inPhase.filter(k => k.status === 'failed')
570 const running = inPhase.filter(k => k.status === 'running')
571 const done = inPhase.filter(k => k.status !== 'running' && k.status !== 'failed')
572 .sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
573 const doneShown = showDone.includes(key) || done.length <= SHOWN_DONE + 1 ? done : done.slice(0, SHOWN_DONE)
574 for (const n of [...failed, ...running, ...doneShown]) out.push({ kind: 'node', node: n, species: 'sea', depth: 1 })
575 if (doneShown.length < done.length) out.push({ kind: 'more', key, count: done.length - doneShown.length })
576 }
577 return out
578}
579
580// Inside a run: a workflow's phases and agents, or a subagent with its own subagents.
581export function runItems(
582 run: AgentNode, nodes: AgentNode[], filter: Filter, flipped: readonly string[], showDone: readonly string[],
583): Item[] {
584 if (run.kind === 'workflow') return workflowItems(run, nodes, filter, flipped, showDone)
585 const out: Item[] = []
586 const walk = (n: AgentNode, depth: number) => {
587 out.push({ kind: 'node', node: n, species: 'cat', depth })
588 for (const k of childrenOf(nodes, n.id)) walk(k, depth + 1)
589 }
590 // a group lists its members in the order they started, each with its own subagents
591 if (run.kind === 'group') for (const k of childrenOf(nodes, run.id).filter(k => passes(k, [], filter)).sort((a, b) => a.startedAt - b.startedAt)) walk(k, 1)
592 else walk(run, 0)
593 return out
594}
595
596// Keep the client's props under the tree bound: drop bulky text first, then this session's
597// finished runs that History holds, then the oldest history, then any finished run left.
598export function fitProps<T extends { nodes: AgentNode[]; history: AgentNode[] }>(p: T, limit = 90_000): T {
599 const size = (x: unknown) => JSON.stringify(x).length
600 if (size(p) <= limit) return p
601 // a missing prompt or result stays missing: props that hold undefined are refused
602 const slim = (n: AgentNode): AgentNode => ({
603 ...n, ...(n.prompt !== undefined ? { prompt: n.prompt.slice(0, 160) } : {}),
604 ...(n.result !== undefined ? { result: n.result.slice(0, 300), ...(n.result.length > 300 ? { resultLength: n.resultLength ?? n.result.length } : {}) } : {}),
605 })
606 let next = { ...p, nodes: p.nodes.map(n => (n.status === 'running' ? n : slim(n))), history: p.history.map(slim) }
607 // A long session can pass the bound on its own runs. The live list does not show
608 // finished runs, History does: the ones it holds go first, and History keeps them.
609 const held = new Set(next.history.map(n => n.id))
610 next = dropFinished(next, limit, top => held.has(top.id))
611 while (size(next) > limit && next.history.length > 0) next = { ...next, history: next.history.slice(Math.ceil(next.history.length / 4)) }
612 return dropFinished(next, limit, () => true)
613}
614
615// This session's oldest finished runs go, whole, until the props fit, so no agent
616// loses its parent; running work stays. `may` says which runs can go.
617function dropFinished<T extends { nodes: AgentNode[] }>(p: T, limit: number, may: (top: AgentNode) => boolean): T {
618 const size = (x: unknown) => JSON.stringify(x).length
619 let over = size(p) - limit
620 if (over <= 0) return p
621 const byId = new Map(p.nodes.map(n => [n.id, n]))
622 const topOf = (n: AgentNode) => { let x = n; while (x.parentId && byId.has(x.parentId)) x = byId.get(x.parentId)!; return x }
623 const runs = new Map<AgentNode, AgentNode[]>()
624 for (const n of p.nodes) { const top = topOf(n); runs.set(top, [...(runs.get(top) ?? []), n]) }
625 const finished = [...runs].filter(([top, run]) => may(top) && run.every(n => n.status !== 'running')).sort(([a], [b]) => a.startedAt - b.startedAt)
626 const gone = new Set<AgentNode>()
627 for (const [top, run] of finished) {
628 if (over <= 0) break
629 gone.add(top)
630 over -= run.reduce((sum, n) => sum + size(n) + 1, 0)
631 }
632 return gone.size ? { ...p, nodes: p.nodes.filter(n => !gone.has(topOf(n))) } : p
633}
634
635// The engine refuses a Client whose props serialize past 100,000 characters, and the
636// pane then draws empty. The slack covers any difference in how the engine counts.
637export const PROPS_BOUND = 98_000
638
639// The view's whole props: everything beside the runs is measured, and the runs take
640// the room it leaves. An open file's own edits take at most half: its oldest go first.
641export function fitView<T extends { nodes: AgentNode[]; history: AgentNode[]; at: number }, R extends { diff?: { path: string; edits: EditRecord[] }; [key: string]: unknown }>(runs: T, rest: R, bound = PROPS_BOUND): T & R {
642 const size = (x: unknown) => JSON.stringify(x).length
643 let fixed = rest
644 if (rest.diff && size(rest.diff) > bound / 2) {
645 let over = size(rest.diff) - bound / 2
646 let cut = 0
647 while (over > 0 && cut < rest.diff.edits.length) over -= size(rest.diff.edits[cut++]) + 1
648 fixed = { ...rest, diff: { ...rest.diff, edits: rest.diff.edits.slice(cut) } }
649 }
650 const empty = { nodes: [], history: [], at: runs.at }
651 const room = bound - (size({ ...empty, ...fixed }) - size(empty))
652 return { ...fitProps(runs, room), ...fixed }
653}
654
655// An agent's transcript keeps every edit call it made, so a run recorded before
656// edits were kept can still show its diffs. Failed calls are left out; lines are
657// placed against the file as it is now, which is right unless a later edit moved them.
658export function transcriptEdits(text: string, agentId: string, now: string | undefined): EditRecord[] {
659 const calls: { id: string; tool: string; input: Record<string, unknown>; at: number }[] = []
660 const failed = new Set<string>()
661 for (const line of text.split('\n')) {
662 if (!line.trim()) continue
663 let row: { timestamp?: string; message?: { content?: unknown } }
664 try { row = JSON.parse(line) } catch { continue }
665 const content = Array.isArray(row.message?.content) ? (row.message!.content as Record<string, unknown>[]) : []
666 const at = row.timestamp ? Date.parse(row.timestamp) || 0 : 0
667 for (const b of content) {
668 if (b.type === 'tool_use' && typeof b.id === 'string' && typeof b.name === 'string' && b.input && typeof b.input === 'object')
669 calls.push({ id: b.id, tool: b.name, input: b.input as Record<string, unknown>, at })
670 if (b.type === 'tool_result' && b.is_error === true && typeof b.tool_use_id === 'string') failed.add(b.tool_use_id)
671 }
672 }
673 return calls
674 .filter(c => !failed.has(c.id) && editedPath(c.tool, c.input))
675 // A transcript can not tell whether a Write made a new file, so isNew is left out
676 // (never set to undefined: props that hold undefined are refused).
677 .flatMap(c => editRecords(c.tool, c.input, undefined, now).map(({ isNew: _unknown, ...r }, i) => ({
678 ...r, id: `${c.id}:${i}`, agentId, at: c.at,
679 })))
680}
681hooks/report.ts 192 lines1import type { AgentNode, Report } from '../types'
2import { childrenOf, counts, fileRows, firstSentence, noReportReason, phaseWords, pipeline, plain, readableResult, scopeNodes, type FileRow } from './list'
3
4// The short report a person reads when work finishes. The model writes the words
5// (result, done, decisions, problems, next); what changed and the totals come from
6// the mod's own records, so they are exact. Reports are written bottom-up: an agent
7// from its own report, a workflow phase from its agents' reports, a run from its
8// part reports. Each call reads one level down and is capped, so none grows with the run.
9
10// Simplified Technical English, about 60% of the way: what every report prompt says.
11export const REPORT_RULES = [
12 'Write in Simplified Technical English, about 60% of the way:',
13 '- One idea per sentence. At most 15 words in a sentence.',
14 '- Use active voice and plain words.',
15 '- Name files, agents and numbers exactly as the input gives them.',
16 '- Lead with the main point. No hedging, no filler, no praise.',
17 '- Keep linking words (because, so, only when) so the reader can follow the logic.',
18 '- Use only facts that are in the input. Do not invent. Write "unknown" when the input does not say.',
19 '- At most 3 items in each list. At most 120 words in total.',
20].join('\n')
21
22export const REPORT_SYSTEM = [
23 'You write the short report a person reads when AI agents finish a piece of work.',
24 REPORT_RULES,
25 'Reply with JSON only, no markdown:',
26 '{"result": "the verdict, then at most 1 more sentence", "done": ["what was done"],',
27 ' "decisions": [{"text": "a design choice the agents made", "source": "the agent or phase it came from"}],',
28 ' "problems": [{"text": "what is wrong or still open, and where", "source": "the agent or phase it came from"}],',
29 ' "next": "1 sentence: the next step, or empty"}',
30 'The first sentence of result is the verdict: at most 12 words, with the key number. A reader who stops there knows the outcome. Example: "Found 1 real error; 8 of 9 claims are overstated."',
31 'Each problem names the item it is about (a file, claim or agent) and what is wrong with it.',
32 'Use [] for an empty list. Decisions are only design choices the input states. Leave out files and line counts: the dashboard adds them from its own records.',
33 'A line "[… N characters left out by the dashboard …]" marks text the dashboard cut, not the agent. Never report that gap as missing, unfinished or unread work.',
34].join('\n')
35
36// The caps that keep every report call bounded, however big the run.
37export const CAP_EACH = 400
38export const CAP_ALL = 4000
39export const CAP_FINAL = 1500
40export const CAP_TASK = 500
41// Output caps: a report's JSON, with its lists and sources, runs past 400 tokens.
42export const REPORT_TOKENS = 800
43export const PART_TOKENS = 600
44// A report kept as raw JSON: its reply was cut, and the old parser kept the text.
45export const isRawReport = (s: string | undefined) => !!s && /^\s*(json\b|```|\{)/.test(s)
46
47// A model's reply as a report: tolerant of fences and chatter, and of the older
48// {outcome, points} digest shape. Fields it cannot read are left out, never undefined.
49export function parseReport(raw: string): Report | undefined {
50 const json = /\{[\s\S]*\}/.exec(raw)?.[0]
51 let d: Record<string, unknown>
52 try { d = JSON.parse(json ?? '') as Record<string, unknown> } catch {
53 // a reply cut at its token cap still holds its verdict: the result string comes first
54 const result = /"result"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(raw)?.[1]
55 let text: unknown
56 try { text = result ? JSON.parse(result) : undefined } catch { text = undefined }
57 const t = typeof text === 'string' ? plain(text).slice(0, 300) : ''
58 return t ? { result: t } : undefined
59 }
60 const str = (x: unknown, n: number) => {
61 const t = typeof x === 'string' ? plain(x) : ''
62 return t ? t.slice(0, n) : undefined
63 }
64 const tagged = (x: unknown) => (Array.isArray(x) ? x : []).flatMap(i => {
65 const text = str(typeof i === 'string' ? i : (i as { text?: unknown } | null)?.text, 200)
66 if (!text) return []
67 const source = i && typeof i === 'object' ? str((i as { source?: unknown }).source, 60) : undefined
68 return [source ? { text, source } : { text }]
69 }).slice(0, 3)
70 const doneRaw = Array.isArray(d.done) ? d.done : Array.isArray(d.points) ? d.points : []
71 const done = doneRaw.map(p => str(typeof p === 'string' ? p : (p as { text?: unknown } | null)?.text, 160)).filter((p): p is string => !!p).slice(0, 3)
72 const out: Report = {}
73 const result = str(d.result, 300) ?? str(d.outcome, 300)
74 if (result) out.result = result
75 if (done.length) out.done = done
76 const decisions = tagged(d.decisions)
77 if (decisions.length) out.decisions = decisions
78 const problems = tagged(d.problems)
79 if (problems.length) out.problems = problems
80 const next = str(d.next, 200)
81 if (next) out.next = next
82 return Object.keys(out).length ? out : undefined
83}
84
85// The report a node shows: its own, else one shaped from what an older run kept
86// (summary as the result, points as what was done). No model call.
87export function reportOf(n: AgentNode): Report | undefined {
88 if (n.report) return n.report
89 const result = n.summary || (n.kind === 'workflow' ? firstSentence(readableResult(n.result), 300) : firstSentence(n.result, 300))
90 const out: Report = {}
91 if (result) out.result = result
92 if (n.points?.length) out.done = n.points.slice(0, 3)
93 return Object.keys(out).length ? out : undefined
94}
95
96const STATUS_WORD: Record<AgentNode['status'], string> = { running: 'running', done: 'done', failed: 'failed', killed: 'stopped' }
97
98// One line per part for the level above: its result and its problems, never its raw text.
99export function partLine(n: AgentNode): string {
100 const r = reportOf(n)
101 const problems = r?.problems?.map(p => p.text).join(' ') ?? ''
102 return `- ${n.label} [${STATUS_WORD[n.status]}]: ${r?.result ?? noReportReason(n)}${problems ? ` Problems: ${problems}` : ''}`.slice(0, CAP_EACH)
103}
104
105// Lines joined until the cap, so the input never grows with the run.
106export function capLines(lines: string[], cap = CAP_ALL): string {
107 let out = ''
108 for (const l of lines) {
109 if (out.length + l.length + 1 > cap) { out += `${out ? '\n' : ''}- … ${lines.length - out.split('\n').length} more not shown`; break }
110 out += `${out ? '\n' : ''}${l}`
111 }
112 return out
113}
114
115// A workflow phase's part report reads its agents' reports.
116export function partInput(wf: AgentNode, phase: string, nodes: AgentNode[]): string {
117 const agents = childrenOf(nodes, wf.id).filter(k => (k.phase ?? 'Agents') === phase).sort((a, b) => a.startedAt - b.startedAt)
118 return [
119 `Workflow: ${wf.label.slice(0, 200)}`,
120 `Part: the ${phase} phase, ${agents.length} agent${agents.length === 1 ? '' : 's'} (${phaseWords({ phase, ...counts(agents) })})`,
121 '',
122 'Agent reports:',
123 capLines(agents.map(partLine)),
124 ].join('\n')
125}
126
127// A long report keeps its start and its end, since agents put the verdict last.
128// The gap is named, so a cut text never reads as unfinished work. `whole` is the
129// length of the text before it was cut, when only a kept copy is at hand.
130const gapLine = (n: number) => `[… ${n.toLocaleString('en-US')} characters left out by the dashboard …]`
131export function cutReport(text: string, cap: number, whole = text.length): string {
132 if (text.length <= cap) return whole > text.length ? `${text}\n${gapLine(whole - text.length)}` : text
133 const tail = Math.floor(cap / 5)
134 const head = cap - tail
135 return `${text.slice(0, head)}\n${gapLine(whole - head - tail)}\n${text.slice(-tail)}`
136}
137
138// A run's report reads one level down: a single agent its own report text; a
139// cluster its members' reports; a workflow its phases' part reports. `full` is the
140// whole answer when it is at hand; else the kept copy is read, its cut named.
141export function runInput(n: AgentNode, nodes: AgentNode[], full?: string): string {
142 const source = full ?? n.result ?? ''
143 const lost = full === undefined && n.resultLength && n.result ? Math.max(0, n.resultLength - n.result.length) : 0
144 const task = `Task: ${(n.prompt ?? n.label).slice(0, CAP_TASK)}`
145 if (n.kind === 'group') {
146 const kids = childrenOf(nodes, n.id).sort((a, b) => a.startedAt - b.startedAt)
147 return [task, '', `Part reports, one per member (${kids.length}):`, capLines(kids.map(partLine))].join('\n')
148 }
149 if (n.kind === 'workflow') {
150 const parts = pipeline(n, nodes).map(p => {
151 const pr = n.partReports?.[p.phase]
152 const problems = pr?.problems?.map(x => `${x.text}${x.source ? ` [${x.source}]` : ''}`).join(' ') ?? ''
153 return `- ${p.phase} phase [${phaseWords(p)}]: ${pr?.result ?? 'unknown'}${problems ? ` Problems: ${problems}` : ''}`.slice(0, CAP_EACH)
154 })
155 const readable = readableResult(source)
156 const final = readable ? cutReport(readable, CAP_FINAL, readable.length + lost) : ''
157 return [task, '', `Part reports, one per phase (${parts.length}):`, capLines(parts), ...(final ? ['', `Final result: ${final}`] : [])].join('\n')
158 }
159 return [task, '', 'Report:', source ? cutReport(source, CAP_ALL, source.length + lost) : ''].join('\n')
160}
161
162// ── facts from records: what changed and the totals, never from the model ────
163export type Facts = {
164 files: FileRow[]
165 added: number
166 removed: number
167 agents: number
168 phases: number
169 ms: number
170 tokens: number
171}
172
173export function reportFacts(nodes: AgentNode[], scope: { kind: 'node'; id: string } | { kind: 'phase'; wfId: string; phase: string }, now: number): Facts {
174 const list = scopeNodes(nodes, scope)
175 const agents = list.filter(n => n.kind === 'agent')
176 const files = fileRows(list)
177 const root = scope.kind === 'node' ? nodes.find(n => n.id === scope.id) : undefined
178 const starts = list.map(n => n.startedAt).filter(Number.isFinite)
179 const ends = list.map(n => n.endedAt ?? now)
180 return {
181 files,
182 added: files.reduce((a, f) => a + f.added, 0),
183 removed: files.reduce((a, f) => a + f.removed, 0),
184 agents: agents.length,
185 phases: root?.kind === 'workflow' ? pipeline(root, nodes).length : 0,
186 ms: starts.length ? Math.max(0, Math.max(...ends) - Math.min(...starts)) : 0,
187 tokens: agents.reduce((a, n) => a + (n.tokens ?? 0), 0),
188 }
189}
190
191export const kTokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n))
192hooks/trace.ts 426 lines1import type { AgentNode, TraceLane, TraceRow, TraceZoom } from '../types'
2import { describeTool, editedPath } from './list'
3import { treeOrder } from './lens'
4
5// The trail behind a run: what each agent did, in order, and how the agents
6// handed work to each other. Read from transcripts when a trace opens; pure here.
7
8export type TraceKind = 'spawn' | 'tool' | 'edit' | 'message' | 'handback' | 'report' | 'fail' | 'quiet' | 'note' | 'step'
9
10export type TraceEvent = {
11 agentId: string
12 at: number
13 kind: TraceKind
14 // the tool's name for a tool call, else the kind
15 name: string
16 summary: string
17 input?: string
18 output?: string
19 tokens?: number
20 // a spawn's child (its agent id when the result names it, else its description), a message's recipient
21 to?: string
22 // a message's sender, when it arrived from another agent or session
23 from?: string
24 path?: string
25 added?: number
26 removed?: number
27 error?: boolean
28}
29
30export const ZOOMS: TraceZoom[] = ['story', 'steps', 'raw']
31export const ZOOM_NAMES: Record<TraceZoom, string> = { story: 'Story', steps: 'Steps', raw: 'Raw' }
32export const QUIET_GAP = 120_000
33const EXCERPT = 160
34
35const oneLine = (s: string) => s.replace(/\s+/g, ' ').trim()
36export const excerpt = (s: unknown, n = EXCERPT): string | undefined => {
37 if (typeof s !== 'string') return undefined
38 const t = oneLine(s)
39 if (!t) return undefined
40 return t.length > n ? `${t.slice(0, n - 1)}…` : t
41}
42const baseName = (p: string) => p.split('/').filter(Boolean).pop() ?? p
43const lines = (s: unknown) => (typeof s === 'string' && s.length ? s.split('\n').length : 0)
44
45// The text of a tool result: a string, or text blocks.
46function resultText(content: unknown): string {
47 if (typeof content === 'string') return content
48 if (Array.isArray(content)) return content.map(b => (b && typeof b === 'object' && typeof (b as { text?: unknown }).text === 'string' ? (b as { text: string }).text : '')).join('\n')
49 return ''
50}
51
52// The few input fields a person reads, not the whole input.
53function inputText(name: string, input: Record<string, unknown>): string | undefined {
54 const s = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : '')
55 if (name === 'Bash') return excerpt(s('command'))
56 if (name === 'Read' || name === 'Write' || name === 'Edit' || name === 'MultiEdit') return excerpt(s('file_path'))
57 if (name === 'Grep' || name === 'Glob') return excerpt([s('pattern'), s('path')].filter(Boolean).join(' in '))
58 if (name === 'WebFetch') return excerpt(s('url'))
59 if (name === 'WebSearch') return excerpt(s('query'))
60 if (name === 'Agent' || name === 'Task') return excerpt(s('prompt'))
61 if (name === 'SendMessage') return excerpt(s('message') || s('content'))
62 if (name === 'SubagentHandback') return excerpt(s('message'))
63 const first = Object.entries(input).find(([, v]) => typeof v === 'string')
64 return first ? excerpt(String(first[1])) : undefined
65}
66
67// What a message that arrived says: who sent it and its first words.
68const INCOMING = /<(cross-session-message|agent-message)\b([^>]*)>([\s\S]*?)(?:<\/\1>|$)/g
69function incoming(text: string): { from: string; body: string }[] {
70 const out: { from: string; body: string }[] = []
71 for (const m of text.matchAll(INCOMING)) {
72 const attrs = m[2] ?? ''
73 const from = /from-name="([^"]*)"/.exec(attrs)?.[1] ?? /from="([^"]*)"/.exec(attrs)?.[1] ?? 'another session'
74 out.push({ from, body: m[3] ?? '' })
75 }
76 return out
77}
78
79type Row = { type?: string; timestamp?: string; message?: { role?: string; content?: unknown; usage?: Record<string, unknown> } }
80type Block = { type?: string; id?: string; name?: string; input?: Record<string, unknown>; text?: string; tool_use_id?: string; content?: unknown; is_error?: boolean }
81
82// A parse that can take a transcript in pieces: whole lines in, events out.
83export type Parse = { agentId: string; events: TraceEvent[]; pending: Map<string, number>; lastText?: { at: number; text: string }; handedBack: boolean; sawTask: boolean; lastAt: number; beforeTask: boolean }
84
85export const newParse = (agentId: string): Parse => ({ agentId, events: [], pending: new Map(), handedBack: false, sawTask: false, lastAt: 0, beforeTask: false })
86
87export function parseLines(p: Parse, text: string): Parse {
88 for (const line of text.split('\n')) {
89 if (!line.trim()) continue
90 let row: Row
91 try { row = JSON.parse(line) as Row } catch { continue }
92 const at = row.timestamp ? Date.parse(row.timestamp) : p.lastAt
93 if (Number.isFinite(at) && at > 0) p.lastAt = at
94 const content = row.message?.content
95 // A fork's transcript opens with the parent's own call that started it; its
96 // work begins at the first text it is given (the directive).
97 if (row.type === 'fork-context-ref') { p.beforeTask = true; continue }
98 if (p.beforeTask) {
99 const text = row.type === 'user' && (typeof content === 'string' || (Array.isArray(content) && (content as Block[]).some(b => b.type === 'text')))
100 if (text) { p.beforeTask = false; p.sawTask = true }
101 continue
102 }
103 if (row.type === 'assistant' && Array.isArray(content)) {
104 const u = row.message?.usage ?? {}
105 const num = (k: string) => (typeof u[k] === 'number' ? (u[k] as number) : 0)
106 let tokens: number | undefined = num('input_tokens') + num('cache_creation_input_tokens') + num('output_tokens') || undefined
107 for (const b of content as Block[]) {
108 if (b.type === 'text' && b.text?.trim()) p.lastText = { at: p.lastAt, text: b.text }
109 if (b.type !== 'tool_use' || !b.name) continue
110 const ev = toolEvent(p.agentId, p.lastAt, b.name, b.input ?? {})
111 if (tokens) { ev.tokens = tokens; tokens = undefined }
112 if (ev.kind === 'handback') p.handedBack = true
113 if (b.id) p.pending.set(b.id, p.events.length)
114 p.events.push(ev)
115 }
116 } else if (row.type === 'user') {
117 const blocks: Block[] = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? (content as Block[]) : []
118 for (const b of blocks) {
119 if (b.type === 'tool_result' && b.tool_use_id) {
120 const i = p.pending.get(b.tool_use_id)
121 if (i === undefined) continue
122 p.pending.delete(b.tool_use_id)
123 const ev = p.events[i]!
124 const out = resultText(b.content)
125 const o = excerpt(out)
126 if (o) ev.output = o
127 if (b.is_error) ev.error = true
128 // a background spawn's result names the agent it started
129 const child = ev.kind === 'spawn' ? /agentId:\s*([a-z0-9]{8,})/i.exec(out)?.[1] : undefined
130 if (child) ev.to = child
131 } else if (b.type === 'text' && b.text) {
132 // the first user text is the task this agent was given, not a message
133 if (!p.sawTask) { p.sawTask = true; continue }
134 for (const m of incoming(b.text)) {
135 p.events.push({ agentId: p.agentId, at: p.lastAt, kind: 'message', name: 'message', summary: excerpt(m.body, 80) ?? 'a message', from: m.from, ...(excerpt(m.body) ? { input: excerpt(m.body) } : {}) })
136 }
137 }
138 }
139 }
140 }
141 return p
142}
143
144function toolEvent(agentId: string, at: number, name: string, input: Record<string, unknown>): TraceEvent {
145 const s = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : '')
146 const base = { agentId, at, name, ...(inputText(name, input) ? { input: inputText(name, input) } : {}) }
147 if (name === 'Agent' || name === 'Task') return { ...base, kind: 'spawn', summary: `started ${s('description') || s('name') || 'a subagent'}`, to: s('description') || s('name') }
148 if (name === 'SendMessage') return { ...base, kind: 'message', summary: excerpt(s('summary') || s('message') || s('content'), 80) ?? 'a message', to: s('to') || s('recipient') }
149 if (name === 'SubagentHandback') return { ...base, kind: 'handback', summary: excerpt(s('message').split('\n').find(l => l.trim()) ?? 'its report', 80) ?? 'its report' }
150 const path = editedPath(name, input)
151 if (path) {
152 const added = name === 'Write' ? lines(input.content) : lines(input.new_string)
153 const removed = name === 'Write' ? 0 : lines(input.old_string)
154 return { ...base, kind: 'edit', summary: `${name === 'Write' ? 'wrote' : 'edited'} ${baseName(path)}`, path, added, removed }
155 }
156 return { ...base, kind: 'tool', summary: describeTool(name, input).activity }
157}
158
159// The end of a parse: an agent that wrote a last text and handed nothing back reported that text.
160export function finishParse(p: Parse): TraceEvent[] {
161 const out = [...p.events]
162 if (!p.handedBack && p.lastText) {
163 out.push({ agentId: p.agentId, at: p.lastText.at, kind: 'report', name: 'report', summary: excerpt(p.lastText.text.split('\n').find(l => l.trim()) ?? '', 80) ?? 'its report', ...(excerpt(p.lastText.text) ? { input: excerpt(p.lastText.text) } : {}) })
164 }
165 return out
166}
167
168export const parseTranscript = (text: string, agentId: string): TraceEvent[] => finishParse(parseLines(newParse(agentId), text))
169
170// ── zoom: steps group runs of like tool calls; a story keeps a few beats ──────
171
172type Cls = 'read' | 'search' | 'run' | 'web' | 'other'
173const clsOf = (e: TraceEvent): Cls => {
174 if (e.name === 'Read' || e.name === 'LS') return 'read'
175 if (e.name === 'Grep' || e.name === 'Glob' || e.name === 'ToolSearch' || e.name === 'LSP') return 'search'
176 if (e.name === 'Bash' || e.name === 'Monitor') return 'run'
177 if (e.name === 'WebFetch' || e.name === 'WebSearch' || e.name.startsWith('mcp__')) return 'web'
178 return 'other'
179}
180const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
181// the folder most of the paths share, for "read 6 files in src/auth"
182function commonDir(paths: string[]): string {
183 const parts = paths.map(p => p.split('/').filter(Boolean).slice(0, -1))
184 if (!parts.length) return ''
185 let n = 0
186 while (parts.every(ps => ps[n] !== undefined && ps[n] === parts[0]![n])) n++
187 const dir = parts[0]!.slice(0, n)
188 return dir.slice(-2).join('/')
189}
190function groupText(cls: Cls, list: TraceEvent[]): string {
191 if (cls === 'read') {
192 const dir = commonDir(list.map(e => e.input ?? ''))
193 return `read ${plural(list.length, 'file')}${dir ? ` in ${dir}` : ''}`
194 }
195 if (cls === 'search') return `searched ${plural(list.length, 'time')}`
196 if (cls === 'run') return `ran ${plural(list.length, 'command')}`
197 if (cls === 'web') return plural(list.length, 'web call')
198 return `used ${plural(list.length, 'tool')}`
199}
200
201export type Step = TraceEvent & { count?: number; end?: number; error?: boolean }
202
203// Steps: consecutive tool calls of one kind become one row; edits to one file become one row.
204export function stepsOf(events: TraceEvent[]): Step[] {
205 const out: Step[] = []
206 for (const e of events) {
207 const last = out[out.length - 1]
208 if (last && last.agentId === e.agentId && e.kind === 'tool' && last.kind === 'tool' && clsOf(last) === clsOf(e)) {
209 const members = [...((last as Step & { members?: TraceEvent[] }).members ?? [last]), e]
210 Object.assign(last, { count: members.length, end: e.at, summary: groupText(clsOf(e), members), members, error: last.error || e.error,
211 tokens: (last.tokens ?? 0) + (e.tokens ?? 0) || undefined, output: e.output ?? last.output })
212 continue
213 }
214 if (last && last.agentId === e.agentId && e.kind === 'edit' && last.kind === 'edit' && last.path === e.path) {
215 const count = (last.count ?? 1) + 1
216 Object.assign(last, { count, end: e.at, summary: `${last.summary.split(' ×')[0]} ×${count}`, added: (last.added ?? 0) + (e.added ?? 0), removed: (last.removed ?? 0) + (e.removed ?? 0),
217 tokens: (last.tokens ?? 0) + (e.tokens ?? 0) || undefined })
218 continue
219 }
220 out.push({ ...e })
221 }
222 return out.map(({ ...s }) => { delete (s as { members?: unknown }).members; return s })
223}
224
225// A story: per agent, its own beats (spawns, edits, messages, hand-backs, reports)
226// stay, and its tool work folds into at most a few beats between them.
227export function storyOf(events: TraceEvent[], maxBeats = 8): Step[] {
228 const steps = stepsOf(events)
229 const byAgent = new Map<string, Step[]>()
230 for (const s of steps) byAgent.set(s.agentId, [...(byAgent.get(s.agentId) ?? []), s])
231 const out: Step[] = []
232 for (const agentId of [...new Set(steps.map(s => s.agentId))]) {
233 const list: Step[] = byAgent.get(agentId) ?? []
234 const keep = list.filter((s: Step) => s.kind !== 'tool')
235 const room = Math.max(3, maxBeats - keep.length)
236 // tool steps fold into `room` buckets of neighbours
237 const tools: Step[] = list.filter((s: Step) => s.kind === 'tool')
238 const size = Math.max(1, Math.ceil(tools.length / room))
239 const buckets: Step[] = []
240 for (let i = 0; i < tools.length; i += size) {
241 const part = tools.slice(i, i + size)
242 if (part.length === 1) { buckets.push(part[0]!); continue }
243 // a step keeps its first call's tool name, and steps group one class each
244 const tally = (c: Cls) => part.filter(t => clsOf(t) === c).reduce((a, t) => a + (t.count ?? 1), 0)
245 const bits = [
246 tally('read') ? `read ${plural(tally('read'), 'file')}` : '',
247 tally('search') ? `searched ${plural(tally('search'), 'time')}` : '',
248 tally('run') ? `ran ${plural(tally('run'), 'command')}` : '',
249 tally('web') ? plural(tally('web'), 'web call') : '',
250 tally('other') ? `used ${plural(tally('other'), 'other tool')}` : '',
251 ].filter(Boolean)
252 buckets.push({ ...part[0]!, summary: bits.join(', ') || `used ${plural(part.length, 'tool')}`, count: part.reduce((a, t) => a + (t.count ?? 1), 0), end: part[part.length - 1]!.end ?? part[part.length - 1]!.at,
253 error: part.some(t => t.error), tokens: part.reduce((a, t) => a + (t.tokens ?? 0), 0) || undefined })
254 }
255 out.push(...[...keep, ...buckets].sort((a, b) => a.at - b.at))
256 }
257 return out.sort((a, b) => a.at - b.at)
258}
259
260export const zoomed = (events: TraceEvent[], zoom: TraceZoom): Step[] => (zoom === 'raw' ? events.map(e => ({ ...e })) : zoom === 'steps' ? stepsOf(events) : storyOf(events))
261
262// ── lanes: one per agent, the main session first; rows in time order ─────────
263
264// Two letters a lane is known by: "review:bugs" → RB, "Fix cart totals" → FC.
265export function chipOf(label: string): string {
266 const words = label.split(/[^A-Za-z0-9]+/).filter(Boolean)
267 if (words.length >= 2) return (words[0]![0]! + words[1]![0]!).toUpperCase()
268 return (words[0] ?? label).slice(0, 2).toUpperCase().padEnd(2, ' ')
269}
270
271export const MAIN = 'main'
272
273// Builds a run's trace: its lanes, and its rows at a zoom.
274// `events` holds what each agent's transcript gave; an agent missing from it has no
275// transcript on disk, and its lane is built from what its node holds.
276// `stories`: agents whose steps a model wrote; at the story zoom those steps stand in for
277// their tool calls, spread over the time the agent ran, between its real edits and hand-backs.
278export function buildTrace(run: AgentNode, scope: AgentNode[], events: Map<string, TraceEvent[]>, now: number, zoom: TraceZoom, stories?: Map<string, string[]>): { lanes: TraceLane[]; rows: TraceRow[]; missing: number } {
279 // lanes in tree order: each agent, then the agents it spawned, so a child's lane sits by its parent's
280 const ordered = run.kind === 'agent'
281 ? [{ node: run, depth: 0 }, ...treeOrder(scope, run.id).map(r => ({ ...r, depth: r.depth + 1 }))]
282 : treeOrder(scope, run.id)
283 const seen = new Set(ordered.map(r => r.node.id))
284 for (const n of scope.filter(x => x.kind === 'agent' && !seen.has(x.id)).sort((a, b) => a.startedAt - b.startedAt)) ordered.push({ node: n, depth: 0 })
285 const agents = ordered.map(r => r.node)
286 const depthOf = new Map(ordered.map(r => [r.node.id, r.depth]))
287 const isAgent = new Set(agents.map(a => a.id))
288 const parentLane = (n: AgentNode) => (n.parentId && isAgent.has(n.parentId) ? n.parentId : MAIN)
289 const hasMain = agents.some(a => parentLane(a) === MAIN)
290 const laneIds = [...(hasMain ? [MAIN] : []), ...agents.map(a => a.id)]
291 const laneOf = new Map(laneIds.map((id, i) => [id, i]))
292 const all: TraceEvent[] = []
293 let missing = 0
294 // copies: linking a spawn to its child's lane must not change what the cache holds
295 const copies = new Map<string, TraceEvent[]>()
296 for (const a of agents) { const own = events.get(a.id); if (own) copies.set(a.id, own.map(e => ({ ...e }))) }
297 // which spawn events of a parent are linked to a child lane already
298 const linked = new Set<TraceEvent>()
299 for (const a of agents) {
300 const own = copies.get(a.id)
301 const parent = parentLane(a)
302 // the arrow into this lane: from its parent's own spawn call when that is in a transcript, else from the main session
303 const parentEvents = parent === MAIN ? undefined : copies.get(parent)
304 const spawn = parentEvents?.find(e => e.kind === 'spawn' && !linked.has(e) && (e.to === a.id || e.to === a.label))
305 if (spawn) { linked.add(spawn); spawn.to = a.id }
306 else all.push({ agentId: parent, at: a.startedAt, kind: 'spawn', name: 'spawn', summary: `started ${a.label}`, to: a.id, ...(excerpt(a.prompt) ? { input: excerpt(a.prompt) } : {}) })
307 // a story outlives its transcript: its steps show even when the file is gone
308 const story = zoom === 'story' ? stories?.get(a.id) : undefined
309 if (story?.length) {
310 const t0 = a.startedAt
311 const t1 = Math.max(t0 + story.length, a.endedAt ?? now)
312 story.forEach((text, i) => all.push({ agentId: a.id, at: Math.round(t0 + ((t1 - t0) * (i + 0.5)) / story.length), kind: 'step', name: 'step', summary: text }))
313 }
314 if (own && story?.length) {
315 all.push(...own.filter(e => e.kind !== 'tool'))
316 } else if (own) {
317 all.push(...own)
318 } else {
319 missing++
320 all.push({ agentId: a.id, at: a.startedAt, kind: 'note', name: 'note', summary: 'transcript no longer on disk' })
321 const said = a.report?.result ?? a.summary ?? a.result
322 if (said && a.status !== 'running') all.push({ agentId: a.id, at: a.endedAt ?? a.startedAt, kind: 'report', name: 'report', summary: excerpt(said, 80) ?? said, ...(excerpt(said) ? { input: excerpt(said) } : {}) })
323 }
324 if (a.status === 'failed' || a.status === 'killed') {
325 all.push({ agentId: a.id, at: a.endedAt ?? now, kind: 'fail', name: 'fail', summary: a.status === 'failed' ? 'failed' : 'stopped' })
326 }
327 }
328 // a hand-back or a last report goes to the lane that started the agent
329 for (const e of all) {
330 if ((e.kind === 'handback' || e.kind === 'report') && laneOf.has(e.agentId)) {
331 const a = agents.find(x => x.id === e.agentId)
332 if (a) e.to = parentLane(a)
333 }
334 // a spawn the parent made that matches no lane stays a plain row
335 if (e.kind === 'spawn' && e.to && !laneOf.has(e.to)) e.to = undefined
336 }
337 all.sort((a, b) => a.at - b.at)
338 const steps = zoomed(all, zoom)
339 // quiet gaps: a lane that called nothing for two minutes or more, while it ran
340 const withQuiet: Step[] = []
341 const lastAt = new Map<string, number>()
342 for (const s of steps) {
343 const prev = lastAt.get(s.agentId)
344 if (prev !== undefined && s.at - prev >= QUIET_GAP && s.agentId !== MAIN) {
345 withQuiet.push({ agentId: s.agentId, at: prev, kind: 'quiet', name: 'quiet', summary: `quiet ${mins(s.at - prev)}` })
346 }
347 lastAt.set(s.agentId, s.end ?? s.at)
348 withQuiet.push(s)
349 }
350 for (const a of agents) {
351 const prev = lastAt.get(a.id)
352 if (a.status === 'running' && prev !== undefined && now - prev >= QUIET_GAP) {
353 withQuiet.push({ agentId: a.id, at: prev, kind: 'quiet', name: 'quiet', summary: `quiet ${mins(now - prev)} so far` })
354 }
355 }
356 withQuiet.sort((a, b) => a.at - b.at)
357 const rows: TraceRow[] = withQuiet.map(s => compact(s, laneOf))
358 const lanes: TraceLane[] = laneIds.map((id, i) => {
359 const a = agents.find(x => x.id === id)
360 const idx = rows.flatMap((r, k) => (r.lane === i || r.to === i ? [k] : []))
361 return {
362 id, label: a ? a.label : 'Main session', chip: a ? chipOf(a.label) : 'MS', depth: a ? depthOf.get(a.id) ?? 0 : 0,
363 status: a ? a.status : run.status === 'running' ? 'running' : 'done',
364 from: idx.length ? Math.min(...idx) : 0, to: idx.length ? Math.max(...idx) : 0,
365 }
366 })
367 return { lanes, rows, missing }
368}
369
370const mins = (ms: number) => (ms < 60_000 ? `${Math.round(ms / 1000)}s` : `${Math.round(ms / 60_000)}m`)
371
372// A row as the view gets it: short keys, nothing undefined.
373function compact(s: Step, laneOf: Map<string, number>): TraceRow {
374 const r: TraceRow = { kind: s.kind, lane: laneOf.get(s.agentId) ?? 0, at: s.at, text: s.summary }
375 if (s.to !== undefined && laneOf.has(s.to)) r.to = laneOf.get(s.to)!
376 else if (s.to) r.target = s.to
377 if (s.from) r.from = s.from
378 if (s.count && s.count > 1) r.count = s.count
379 if (s.end && s.end !== s.at) r.end = s.end
380 if (s.input) r.input = s.input
381 if (s.output) r.output = s.output
382 if (s.tokens) r.tokens = s.tokens
383 if (s.path) r.path = s.path
384 if (s.added !== undefined && s.kind === 'edit') r.added = s.added
385 if (s.removed !== undefined && s.kind === 'edit') r.removed = s.removed
386 if (s.error) r.error = true
387 if (s.kind === 'tool' || s.kind === 'edit') r.name = s.name
388 return r
389}
390
391export const TRACE_WINDOW = 160
392
393// The rows the view gets: a window around where it reads, so props stay small.
394export function traceWindow(rows: TraceRow[], offset: number, size = TRACE_WINDOW): { offset: number; rows: TraceRow[] } {
395 const at = Math.max(0, Math.min(offset, Math.max(0, rows.length - size)))
396 return { offset: at, rows: rows.slice(at, at + size) }
397}
398
399// ── reading a trace: one lane only, the rows worth a look, and a search ──────
400
401// The rows of one lane: what it did, and the arrows into and out of it. The lanes
402// keep their places (and so their colours); their spans are measured again.
403export function onlyLane(rows: TraceRow[], lanes: TraceLane[], lane: number): { rows: TraceRow[]; lanes: TraceLane[] } {
404 const kept = rows.filter(r => r.lane === lane || r.to === lane)
405 return {
406 rows: kept,
407 lanes: lanes.map((L, i) => {
408 const idx = kept.flatMap((r, k) => (r.lane === i || r.to === i ? [k] : []))
409 return { ...L, from: idx.length ? Math.min(...idx) : 0, to: idx.length ? Math.max(...idx) : -1 }
410 }),
411 }
412}
413
414export const MARKS_KEPT = 400
415
416// Rows worth a look: a failure, a call that errored, a quiet gap.
417export const traceMarks = (rows: TraceRow[]): number[] =>
418 rows.flatMap((r, i) => (r.kind === 'fail' || r.error || r.kind === 'quiet' ? [i] : [])).slice(0, MARKS_KEPT)
419
420// Rows whose words hold the search, any case: the row's text, its tool, what went in and out.
421export function traceHits(rows: TraceRow[], query: string): number[] {
422 const q = query.trim().toLowerCase()
423 if (!q) return []
424 return rows.flatMap((r, i) => ([r.text, r.name, r.input, r.output, r.path, r.from, r.target].some(t => t?.toLowerCase().includes(q)) ? [i] : [])).slice(0, MARKS_KEPT)
425}
426hooks/ai.ts 235 lines1import type { AgentNode, Brief, PatternCard } from '../types'
2import { REPORT_RULES, capLines, reportOf } from './report'
3import { childrenOf, fileRows, plain, prettyModel, scopeNodes } from './list'
4import type { Step } from './trace'
5
6// The AI layer: who may write what, the prompts, what each call reads (capped, so
7// no call grows with the run or the history), and how each reply is read back.
8// Pure: the hooks make the calls, the view draws what comes back.
9
10// What the /config setting allows: nothing, Haiku only, or Haiku and Sonnet on demand.
11export type AiMode = 'off' | 'cheap' | 'full'
12export const AI_MODES: AiMode[] = ['off', 'cheap', 'full']
13export type Tier = 'haiku' | 'sonnet'
14export const aiAllows = (mode: AiMode, tier: Tier) => mode === 'full' || (mode === 'cheap' && tier === 'haiku')
15export const TIER_NAME: Record<Tier, string> = { haiku: 'Haiku', sonnet: 'Sonnet' }
16
17// The caps: one line, a whole input, how many rows a call reads.
18export const STORY_STEPS_IN = 40
19export const STORY_CAP = 3000
20export const EXPLAIN_CAP = 6000
21export const PATTERN_RUNS = 50
22export const PATTERNS_CAP = 8000
23const LINE = 300
24
25const clip = (s: string | undefined, n = LINE) => plain(s ?? '').slice(0, n)
26
27// ── story steps: what one agent did, in a few short steps ─────────────────────
28
29export const STORY_SYSTEM = [
30 'You turn the tool log of one AI agent into the few steps a person reads to follow what it did.',
31 REPORT_RULES,
32 'Write 3 to 8 steps, in the order they happened. Each step is one sentence that starts with a verb in the past tense.',
33 'Group many small calls into one step. Name files and commands as the log gives them.',
34 'Reply with JSON only, no markdown: {"steps": ["..."]}',
35].join('\n')
36
37// Each call in its own words (a shell call's own description), repeats folded, the beats
38// that are not tool calls always kept, and the rest sampled evenly: at most 40 lines.
39// A shell call with no description of its own reads as its command, not its first 40 characters.
40const said = (e: Step) => (e.kind === 'tool' && e.summary.startsWith('Running ') && e.input ? `ran ${clip(e.input, 140)}` : e.summary)
41
42export function storyLines(events: Step[], max = STORY_STEPS_IN): { lines: Step[]; dropped: number } {
43 const folded: Step[] = []
44 for (const e0 of events) {
45 const e = { ...e0, summary: said(e0) }
46 const last = folded[folded.length - 1]
47 if (last && last.kind === e.kind && last.summary === e.summary) { last.count = (last.count ?? 1) + (e.count ?? 1); last.error = last.error || e.error; continue }
48 folded.push({ ...e })
49 }
50 if (folded.length <= max) return { lines: folded, dropped: 0 }
51 const beats = folded.filter(e => e.kind !== 'tool')
52 const tools = folded.filter(e => e.kind === 'tool')
53 const room = Math.max(0, max - beats.length)
54 const every = tools.length / Math.max(1, room)
55 const kept = new Set(Array.from({ length: Math.min(room, tools.length) }, (_, i) => tools[Math.floor(i * every)]!))
56 const lines = folded.filter(e => e.kind !== 'tool' || kept.has(e)).slice(0, max)
57 return { lines, dropped: folded.length - lines.length }
58}
59
60// The agent's task, its calls in their own words (at most 40), and what it reported, capped.
61export function storyInput(n: AgentNode, events: Step[]): string {
62 const { lines, dropped } = storyLines(events)
63 const shown = lines.map(s => `- ${s.kind === 'tool' ? '' : `[${s.kind}] `}${clip(s.summary, 160)}${s.count && s.count > 1 ? ` (×${s.count})` : ''}${s.error ? ' [failed]' : ''}`)
64 const more = dropped ? [`- … ${dropped} more calls not shown`] : []
65 const said = reportOf(n)?.result ?? clip(n.result)
66 return [
67 `Agent: ${clip(n.label, 120)}`,
68 `Task: ${clip(n.prompt)}`,
69 '',
70 'Tool log:',
71 capLines([...shown, ...more], STORY_CAP),
72 ...(said ? ['', `It reported: ${clip(said)}`] : []),
73 ].join('\n')
74}
75
76const jsonOf = (raw: string): Record<string, unknown> | undefined => {
77 const json = /\{[\s\S]*\}/.exec(raw)?.[0]
78 if (!json) return undefined
79 try { return JSON.parse(json) as Record<string, unknown> } catch { return undefined }
80}
81const texts = (x: unknown, n: number, max: number): string[] =>
82 (Array.isArray(x) ? x : []).map(i => clip(typeof i === 'string' ? i : '', n)).filter(Boolean).slice(0, max)
83
84// A reply as story steps: the JSON asked for, else its bulleted or numbered lines.
85export function parseStory(raw: string): string[] | undefined {
86 const d = jsonOf(raw)
87 const fromJson = d ? texts(d.steps, 160, 8) : []
88 if (fromJson.length) return fromJson
89 const lines = raw.split('\n').map(l => /^\s*(?:[-*•]|\d+[.)])\s+(.+)$/.exec(l)?.[1]).filter((l): l is string => !!l).map(l => clip(l, 160)).slice(0, 8)
90 return lines.length ? lines : undefined
91}
92
93// ── explain this run: how the work hung together ─────────────────────────────
94
95export const EXPLAIN_SYSTEM = [
96 'You explain one finished or running piece of AI agent work to the person who asked for it.',
97 'Write in Simplified Technical English, about 60% of the way:',
98 '- One idea per sentence. At most 15 words in a sentence.',
99 '- Use active voice and plain words. Name agents, files and numbers exactly as the input gives them.',
100 '- No hedging, no filler, no praise. Use only facts in the input; write "unknown" when it does not say.',
101 '- At most 250 words in total. At most 5 items in each list.',
102 'Reply with JSON only, no markdown:',
103 '{"goal": "1 sentence: what the work set out to do",',
104 ' "who": [{"agent": "agent name", "did": "1 sentence"}],',
105 ' "connected": "1 or 2 sentences: how the parts fed each other",',
106 ' "outcome": "1 or 2 sentences: what it achieved",',
107 ' "open": ["what is still open or wrong"]}',
108 'The pane shows outcome first, as a heading. Its first sentence is the verdict: at most 12 words, with the key number.',
109].join('\n')
110
111// The run's own report, its part reports, each agent's steps or result, and what needs a look.
112export function explainInput(run: AgentNode, nodes: AgentNode[], insights: string[]): string {
113 const r = reportOf(run)
114 const scope = scopeNodes(nodes, { kind: 'node', id: run.id })
115 const agents = scope.filter(n => n.kind === 'agent').sort((a, b) => a.startedAt - b.startedAt)
116 const parts = Object.entries(run.partReports ?? {}).map(([phase, p]) => `- ${phase} phase: ${clip(p.result) || 'unknown'}${p.problems?.length ? ` Problems: ${p.problems.map(x => x.text).join(' ')}` : ''}`)
117 const agentLines = agents.map(a => {
118 const steps = a.story?.steps?.length ? a.story.steps.join(' ') : reportOf(a)?.result ?? clip(a.result) ?? ''
119 const parent = a.parentId && a.parentId !== run.id ? scope.find(p => p.id === a.parentId)?.label : undefined
120 return `- ${a.label} [${a.status}${a.phase ? `, ${a.phase} phase` : ''}${parent ? `, started by ${parent}` : ''}]: ${clip(steps) || 'no report'}`
121 })
122 const files = fileRows(scope).map(f => `${f.path} (+${f.added} −${f.removed})`)
123 return [
124 `Run: ${clip(run.label, 200)} (${run.kind}, ${run.status})`,
125 `Task: ${clip(run.prompt)}`,
126 '',
127 'Run report:',
128 capLines([
129 ...(r?.result ? [`- Result: ${clip(r.result)}`] : []),
130 ...(r?.decisions ?? []).map(d => `- Decision: ${clip(d.text)}${d.source ? ` [${d.source}]` : ''}`),
131 ...(r?.problems ?? []).map(p => `- Problem: ${clip(p.text)}${p.source ? ` [${p.source}]` : ''}`),
132 ...(r?.next ? [`- Next: ${clip(r.next)}`] : []),
133 ], 1500) || '- none',
134 ...(parts.length ? ['', 'Part reports:', capLines(parts, 1500)] : []),
135 '',
136 `Agents (${agents.length}):`,
137 capLines(agentLines, EXPLAIN_CAP - 3000),
138 ...(files.length ? ['', `Files changed: ${capLines(files.map(f => `- ${f}`), 600)}`] : []),
139 ...(insights.length ? ['', 'Needs a look:', capLines(insights.map(t => `- ${clip(t)}`), 600)] : []),
140 ].join('\n').slice(0, EXPLAIN_CAP)
141}
142
143// A reply as a brief. Fields it cannot read are left out, never undefined.
144export function parseBrief(raw: string): Omit<Brief, 'model' | 'at'> | undefined {
145 const d = jsonOf(raw)
146 if (!d) return undefined
147 const out: Omit<Brief, 'model' | 'at'> = {}
148 const goal = clip(typeof d.goal === 'string' ? d.goal : '')
149 if (goal) out.goal = goal
150 const who = (Array.isArray(d.who) ? d.who : []).flatMap(w => {
151 if (typeof w === 'string') return clip(w) ? [clip(w)] : []
152 const x = w as { agent?: unknown; did?: unknown } | null
153 const did = clip(typeof x?.did === 'string' ? x.did : '')
154 const agent = clip(typeof x?.agent === 'string' ? x.agent : '', 80)
155 return did ? [agent ? `${agent}: ${did}` : did] : []
156 }).slice(0, 5)
157 if (who.length) out.who = who
158 const connected = clip(typeof d.connected === 'string' ? d.connected : '')
159 if (connected) out.connected = connected
160 const outcome = clip(typeof d.outcome === 'string' ? d.outcome : '')
161 if (outcome) out.outcome = outcome
162 const open = texts(d.open, LINE, 5)
163 if (open.length) out.open = open
164 return Object.keys(out).length ? out : undefined
165}
166
167// ── patterns across runs ─────────────────────────────────────────────────────
168
169export const PATTERNS_SYSTEM = [
170 'You read a list of past AI agent runs and find what repeats: failures with one cause, files many runs change, costly agent types, slow phases.',
171 'Write in Simplified Technical English, about 60% of the way: one idea per sentence, at most 15 words, active voice, plain words, exact names and numbers.',
172 'Use only facts in the input. Each pattern must rest on at least 2 runs. No hedging, no filler.',
173 'Write 2 to 4 patterns. Each has a short title, one evidence sentence with numbers, one concrete thing to try, and the exact names of the runs it rests on.',
174 'Reply with JSON only, no markdown:',
175 '{"patterns": [{"title": "", "evidence": "", "try": "", "runs": ["run name"]}]}',
176].join('\n')
177
178const durationText = (ms: number) => (ms < 60_000 ? `${Math.round(ms / 1000)}s` : `${Math.round(ms / 60_000)}m`)
179
180// One compact row per run, newest first, at most 50 runs and 8,000 characters.
181export function patternsInput(runs: AgentNode[], nodes: AgentNode[]): string {
182 const rows = runs.slice(0, PATTERN_RUNS).map(run => {
183 const scope = scopeNodes(nodes, { kind: 'node', id: run.id })
184 const agents = scope.filter(n => n.kind === 'agent')
185 const r = reportOf(run)
186 const files = fileRows(scope)
187 const models = [...new Set(agents.map(a => prettyModel(a.model)).filter(Boolean))].join('/')
188 const tokens = agents.reduce((a, n) => a + (n.tokens ?? 0), 0) || run.tokens || 0
189 const failed = agents.filter(a => a.status === 'failed' || a.status === 'killed').map(a => `${a.label} (${a.status === 'failed' ? 'failed' : 'stopped'}${reportOf(a)?.result ? `: ${clip(reportOf(a)!.result, 80)}` : ''})`)
190 return clip([
191 `- "${clip(run.label, 100)}" [${run.status}] ${run.kind}${run.kind !== 'agent' ? `, ${childrenOf(nodes, run.id).length} parts` : ''}`,
192 models && `models ${models}`,
193 tokens && `${Math.round(tokens / 1000)}k tokens`,
194 run.endedAt && `${durationText(run.endedAt - run.startedAt)}`,
195 files.length && `files ${files.slice(0, 4).map(f => f.path.split('/').pop()).join(', ')}${files.length > 4 ? ` +${files.length - 4}` : ''}`,
196 r?.result && `result: ${clip(r.result, 120)}`,
197 r?.problems?.length && `problems: ${r.problems.map(p => clip(p.text, 80)).join('; ')}`,
198 failed.length && `failed: ${failed.join('; ')}`,
199 ].filter(Boolean).join(' · '), LINE + 120)
200 })
201 const more = runs.length > PATTERN_RUNS ? [`- … ${runs.length - PATTERN_RUNS} older runs not shown`] : []
202 return [`Runs, newest first (${Math.min(runs.length, PATTERN_RUNS)} of ${runs.length}):`, capLines([...rows, ...more], PATTERNS_CAP)].join('\n')
203}
204
205// A reply as pattern cards: each card keeps only the runs it names that exist, by id.
206export function parsePatterns(raw: string, runs: AgentNode[]): PatternCard[] | undefined {
207 const d = jsonOf(raw)
208 if (!d) return undefined
209 const byLabel = new Map(runs.map(r => [r.label.trim().toLowerCase(), r]))
210 const cards = (Array.isArray(d.patterns) ? d.patterns : []).flatMap(p => {
211 const x = p as { title?: unknown; evidence?: unknown; try?: unknown; runs?: unknown } | null
212 const title = clip(typeof x?.title === 'string' ? x.title : '', 90)
213 if (!title) return []
214 const card: PatternCard = { title, runs: [] }
215 const evidence = clip(typeof x?.evidence === 'string' ? x.evidence : '')
216 if (evidence) card.evidence = evidence
217 const tryIt = clip(typeof x?.try === 'string' ? x.try : '')
218 if (tryIt) card.try = tryIt
219 for (const name of texts(x?.runs, 200, 8)) {
220 const hit = byLabel.get(name.trim().toLowerCase().replace(/^"|"$/g, ''))
221 if (hit && !card.runs.some(r => r.id === hit.id)) card.runs.push({ id: hit.id, label: hit.label })
222 }
223 return [card]
224 }).slice(0, 4)
225 return cards.length ? cards : undefined
226}
227
228// "just now", "12m ago", "3h ago", "2d ago": how old an AI-written block is.
229export function ago(ms: number): string {
230 if (ms < 60_000) return 'just now'
231 if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`
232 if (ms < 48 * 3_600_000) return `${Math.round(ms / 3_600_000)}h ago`
233 return `${Math.round(ms / 86_400_000)}d ago`
234}
235hooks/lens.ts 285 lines1import type { AgentNode } from '../types'
2import { childrenOf, counts, firstSentence, overlaps, passes, pipeline, scopeNodes, type Filter } from './list'
3
4// Four ways to look at the same runs: their shape (tree), where they stand
5// (board), where the time went (timeline), and, inside a run, the trail of what
6// each agent did and handed to the others (trace). Pure: the view draws what these return.
7export type Lens = 'tree' | 'board' | 'timeline' | 'trace'
8export const LENSES: Lens[] = ['tree', 'board', 'timeline', 'trace']
9export const LENS_NAMES: Record<Lens, string> = { tree: 'Tree', board: 'Board', timeline: 'Timeline', trace: 'Trace' }
10// The lenses a place offers: a trace needs a run open.
11export const lensesFor = (hasRun: boolean): Lens[] => (hasRun ? LENSES : LENSES.filter(l => l !== 'trace'))
12
13export type Column = 'running' | 'done' | 'failed'
14export const COLUMNS: Column[] = ['running', 'done', 'failed']
15export const columnOf = (n: Pick<AgentNode, 'status'>): Column => (n.status === 'running' ? 'running' : n.status === 'done' ? 'done' : 'failed')
16
17export type Lane = { key: string; title: string; kind: 'phase' | 'cluster' | 'workflow' | 'agent' | 'singles'; cards: AgentNode[] }
18
19const byStart = (a: AgentNode, b: AgentNode) => a.startedAt - b.startedAt
20const agentsUnder = (nodes: AgentNode[], id: string) => scopeNodes(nodes, { kind: 'node', id }).filter(n => n.kind === 'agent')
21
22// The board's swimlanes. Inside a workflow: one lane per phase. Inside a cluster:
23// one lane for its members. Inside a subagent: one lane, it and its own subagents.
24// On the run list: one lane per workflow or cluster, and one for single agents.
25export function boardLanes(run: AgentNode | undefined, nodes: AgentNode[], tops: AgentNode[], filter: Filter): Lane[] {
26 const keep = (list: AgentNode[]) => list.filter(n => passes(n, [], filter)).sort(byStart)
27 if (run) {
28 if (run.kind === 'workflow') {
29 return pipeline(run, nodes)
30 .map(p => ({ key: `${run.id}:${p.phase}`, title: p.phase, kind: 'phase' as const, cards: keep(childrenOf(nodes, run.id).filter(k => (k.phase ?? 'Agents') === p.phase).flatMap(k => agentsUnder(nodes, k.id))) }))
31 .filter(l => l.cards.length > 0)
32 }
33 const kind = run.kind === 'group' ? 'cluster' : 'agent'
34 return [{ key: run.id, title: run.label, kind, cards: keep(agentsUnder(nodes, run.id).filter(n => run.kind === 'agent' || n.id !== run.id)) }]
35 }
36 const lanes: Lane[] = []
37 const singles: AgentNode[] = []
38 for (const t of tops) {
39 if (t.kind === 'agent') { singles.push(...agentsUnder(nodes, t.id)); continue }
40 const cards = keep(agentsUnder(nodes, t.id))
41 if (cards.length) lanes.push({ key: t.id, title: t.label, kind: t.kind === 'group' ? 'cluster' : 'workflow', cards })
42 }
43 if (singles.length) lanes.push({ key: 'singles', title: 'Single agents', kind: 'singles', cards: keep(singles) })
44 return lanes
45}
46
47// depth: how far under the run's own agents a bar sits (0 = spawned by the run).
48// hidden: a folded bar's agents not shown.
49export type TimeRow = { kind: 'bar'; node: AgentNode; depth?: number; hidden?: number } | { kind: 'label'; text: string }
50
51// Agents in tree order: each agent, then the agents it spawned, each level by start.
52// Clusters and workflows in between hold agents but are not rows themselves.
53// `folded` ids keep their agents out and count them on the folded row.
54export function treeOrder(nodes: AgentNode[], rootId: string, folded: ReadonlySet<string> = new Set()): { node: AgentNode; depth: number; hidden?: number }[] {
55 const out: { node: AgentNode; depth: number; hidden?: number }[] = []
56 const walk = (id: string, depth: number) => {
57 for (const k of childrenOf(nodes, id).sort(byStart)) {
58 if (k.kind !== 'agent') { walk(k.id, depth); continue }
59 if (folded.has(k.id)) {
60 const n = agentsUnder(nodes, k.id).filter(x => x.id !== k.id).length
61 out.push({ node: k, depth, ...(n ? { hidden: n } : {}) })
62 continue
63 }
64 out.push({ node: k, depth })
65 walk(k.id, depth + 1)
66 }
67 }
68 walk(rootId, 0)
69 return out
70}
71
72const foldedSet = (keys: readonly string[]) => new Set(keys.filter(k => k.startsWith('tl:')).map(k => k.slice(3)))
73const asBars = (list: { node: AgentNode; depth: number; hidden?: number }[]): TimeRow[] =>
74 list.map(r => ({ kind: 'bar' as const, node: r.node, depth: r.depth, ...(r.hidden ? { hidden: r.hidden } : {}) }))
75
76// The timeline's rows: on the run list one bar per run; inside a workflow its agents
77// under phase labels; inside a cluster or a subagent every agent under it.
78export function timelineRows(run: AgentNode | undefined, nodes: AgentNode[], tops: AgentNode[], filter: Filter, folds: readonly string[] = []): TimeRow[] {
79 if (!run) return tops.filter(n => passes(n, childrenOf(nodes, n.id), filter)).map(node => ({ kind: 'bar' as const, node }))
80 if (run.kind === 'workflow') {
81 const out: TimeRow[] = []
82 for (const p of pipeline(run, nodes)) {
83 // each of the phase's agents, then the agents it spawned under it
84 const folded = foldedSet(folds)
85 const list = childrenOf(nodes, run.id).filter(k => (k.phase ?? 'Agents') === p.phase && passes(k, [], filter)).sort(byStart)
86 .flatMap(k => (k.kind !== 'agent'
87 ? treeOrder(nodes, k.id, folded)
88 : folded.has(k.id)
89 ? [{ node: k, depth: 0, ...(agentsUnder(nodes, k.id).length > 1 ? { hidden: agentsUnder(nodes, k.id).length - 1 } : {}) }]
90 : [{ node: k, depth: 0 }, ...treeOrder(nodes, k.id, folded).map(r => ({ ...r, depth: r.depth + 1 }))]))
91 if (!list.length) continue
92 out.push({ kind: 'label', text: p.phase })
93 out.push(...asBars(list))
94 }
95 return out
96 }
97 // a run that is an agent leads with its own bar; its sub-agents sit under it
98 const folded = foldedSet(folds)
99 const under = treeOrder(nodes, run.id, folded).filter(r => passes(r.node, [], filter))
100 return asBars(run.kind === 'agent' ? [{ node: run, depth: 0 }, ...under.map(r => ({ ...r, depth: r.depth + 1 }))] : under)
101}
102
103// A live run's agents as status groups: running, then failed or stopped, then done;
104// each group by start time.
105const GROUP_ORDER = ['running', 'failed', 'killed', 'done'] as const
106export function liveGroups(nodes: AgentNode[], runId: string): { status: AgentNode['status']; nodes: AgentNode[] }[] {
107 const agents = agentsUnder(nodes, runId).filter(n => n.id !== runId).sort(byStart)
108 return GROUP_ORDER.map(status => ({ status, nodes: agents.filter(n => n.status === status) })).filter(g => g.nodes.length)
109}
110
111// The run list's timeline, opened up: each run as a heading with its agents under
112// it, newest runs first (at most `maxRuns`), so the picture shows who ran when.
113// A run that is one agent stays one bar, with no heading.
114export function listTimelineRows(nodes: AgentNode[], tops: AgentNode[], maxRuns = 8): { rows: TimeRow[]; runs: number; hidden: number } {
115 const shown = [...tops].sort((a, b) => b.startedAt - a.startedAt).slice(0, maxRuns).sort(byStart)
116 const rows: TimeRow[] = []
117 for (const top of shown) {
118 if (top.kind === 'agent' && !childrenOf(nodes, top.id).length) { rows.push({ kind: 'bar', node: top }); continue }
119 rows.push({ kind: 'label', text: top.label })
120 for (const node of agentsUnder(nodes, top.id).filter(n => n.id !== top.id || top.kind === 'agent').sort(byStart)) rows.push({ kind: 'bar', node })
121 }
122 return { rows, runs: shown.length, hidden: Math.max(0, tops.length - shown.length) }
123}
124
125// ── insights: what needs a look, each pointing at the item it names ─────────
126
127export const QUIET_MS = 120_000
128export type Insight = { kind: 'quiet' | 'overlap' | 'failed' | 'slow' | 'tokens'; text: string; target?: string; tone: 'warn' | 'bad' | 'info' }
129
130const mins = (ms: number) => (ms < 60_000 ? `${Math.max(1, Math.round(ms / 1000))}s` : `${Math.round(ms / 60_000)}m`)
131const short = (p: string) => p.split('/').filter(Boolean).pop() ?? p
132const kTok = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
133const list2 = (names: string[]) => (names.length <= 2 ? names.join(', ') : `${names.slice(0, 2).join(', ')} +${names.length - 2}`)
134
135// The scope is every node the view shows (a run's subtree, or the tab's runs).
136export function insights(scope: AgentNode[], all: AgentNode[], now: number): Insight[] {
137 const agents = scope.filter(n => n.kind === 'agent')
138 const out: Insight[] = []
139 for (const n of agents) {
140 if (n.status !== 'running') continue
141 const since = now - (n.lastToolAt ?? n.startedAt)
142 if (since >= QUIET_MS) out.push({ kind: 'quiet', tone: 'warn', target: n.id, text: `${n.label} made no tool call for ${mins(since)}.` })
143 }
144 for (const o of overlaps(agents)) {
145 out.push({ kind: 'overlap', tone: 'warn', target: o.by[0]!.id, text: `${o.by.length} agents edited ${short(o.path)}: ${list2(o.by.map(b => b.label))}.` })
146 }
147 const failed = agents.filter(n => n.status === 'failed')
148 if (failed.length) out.push({ kind: 'failed', tone: 'bad', target: failed[0]!.id, text: `${failed.length} agent${failed.length === 1 ? '' : 's'} failed: ${list2(failed.map(f => f.label))}.` })
149 // the slowest phase of each workflow in scope, when it took most of the time
150 for (const wf of scope.filter(n => n.kind === 'workflow')) {
151 const spans = pipeline(wf, all).map(p => {
152 const list = childrenOf(all, wf.id).filter(k => (k.phase ?? 'Agents') === p.phase)
153 const start = Math.min(...list.map(k => k.startedAt))
154 const end = Math.max(...list.map(k => k.endedAt ?? now))
155 return { phase: p.phase, ms: Math.max(0, end - start) }
156 }).filter(p => Number.isFinite(p.ms))
157 if (spans.length < 2 || spans.some(p => p.ms <= 0)) continue
158 const total = spans.reduce((a, p) => a + p.ms, 0)
159 const top = [...spans].sort((a, b) => b.ms - a.ms)[0]!
160 const share = total > 0 ? Math.round((top.ms / total) * 100) : 0
161 if (share >= 60 && total >= 10_000) out.push({ kind: 'slow', tone: 'info', target: wf.id, text: `The ${top.phase} phase took ${share}% of the time.` })
162 }
163 const spent = agents.filter(n => (n.tokens ?? 0) > 0)
164 if (spent.length >= 2) {
165 const total = spent.reduce((a, n) => a + (n.tokens ?? 0), 0)
166 const top = [...spent].sort((a, b) => (b.tokens ?? 0) - (a.tokens ?? 0))[0]!
167 out.push({ kind: 'tokens', tone: 'info', target: top.id, text: `${top.label} used ${Math.round(((top.tokens ?? 0) / total) * 100)}% of the tokens (${kTok(top.tokens ?? 0)} of ${kTok(total)}).` })
168 }
169 return out
170}
171
172// A cluster's aspects: what each member covers, with how it went.
173export const aspects = (nodes: AgentNode[], groupId: string) =>
174 childrenOf(nodes, groupId).sort(byStart).map(k => ({ node: k, text: firstSentence(k.label, 40) }))
175
176// Done of total, for a roll-up: finished (done, failed or stopped) out of all.
177export const rollup = (list: AgentNode[]) => {
178 const c = counts(list)
179 return { ...c, finished: c.total - c.running }
180}
181
182// ── where the time went: the chain that set the end time, and the idle time ──
183
184// Agents count as one after another when the later one starts within this of the earlier one's end.
185const SLACK_MS = 3000
186const endOf = (n: AgentNode, now: number) => (n.status === 'running' ? now : n.endedAt ?? now)
187
188export type CriticalPath = { ids: string[]; ms: number; span: number }
189
190// The critical path: the agent that ended last, then, going back in time, the agent
191// that ended last before it started, and so on. Shortening any of them shortens the
192// run; the others ran beside them. Needs two agents or more.
193export function criticalPath(agents: AgentNode[], now: number): CriticalPath | undefined {
194 const list = agents.filter(n => n.kind === 'agent')
195 if (list.length < 2) return undefined
196 const t0 = Math.min(...list.map(n => n.startedAt))
197 const t1 = Math.max(...list.map(n => endOf(n, now)))
198 const latest = (xs: AgentNode[]) => xs.reduce((a, b) => (endOf(b, now) > endOf(a, now) || (endOf(b, now) === endOf(a, now) && b.startedAt < a.startedAt) ? b : a))
199 const chain: AgentNode[] = [latest(list)]
200 for (;;) {
201 const cur = chain[chain.length - 1]!
202 const before = list.filter(n => !chain.includes(n) && endOf(n, now) <= cur.startedAt + SLACK_MS)
203 if (!before.length) break
204 chain.push(latest(before))
205 }
206 chain.reverse()
207 return { ids: chain.map(n => n.id), ms: chain.reduce((a, n) => a + Math.max(0, endOf(n, now) - n.startedAt), 0), span: t1 - t0 }
208}
209
210export type Gap = { from: number; to: number }
211
212// Stretches inside a run when none of its agents ran: the main session thinking,
213// or waiting for the person. Short gaps are noise and are left out.
214export function idleGaps(agents: AgentNode[], now: number): { gaps: Gap[]; ms: number } {
215 const spans = agents.filter(n => n.kind === 'agent').map(n => ({ from: n.startedAt, to: endOf(n, now) })).sort((a, b) => a.from - b.from)
216 if (spans.length < 2) return { gaps: [], ms: 0 }
217 const span = Math.max(...spans.map(s => s.to)) - spans[0]!.from
218 const least = Math.max(5000, span * 0.03)
219 const gaps: Gap[] = []
220 let reach = spans[0]!.to
221 for (const s of spans.slice(1)) {
222 if (s.from - reach >= least) gaps.push({ from: reach, to: s.from })
223 reach = Math.max(reach, s.to)
224 }
225 return { gaps, ms: gaps.reduce((a, g) => a + g.to - g.from, 0) }
226}
227
228// ── cost: tokens by model family ─────────────────────────────────────────────
229
230const FAMILIES = ['Fable', 'Opus', 'Sonnet', 'Haiku'] as const
231export const modelFamily = (m: string | undefined): string => FAMILIES.find(f => m?.toLowerCase().includes(f.toLowerCase())) ?? (m ? 'Other' : 'Unknown')
232
233// What the agents of a scope spent, per model family, most first.
234export function spendByModel(scope: AgentNode[]): { model: string; tokens: number; agents: number }[] {
235 const by = new Map<string, { model: string; tokens: number; agents: number }>()
236 for (const n of scope) {
237 if (n.kind !== 'agent' || !n.tokens) continue
238 const model = modelFamily(n.model)
239 const cur = by.get(model) ?? { model, tokens: 0, agents: 0 }
240 cur.tokens += n.tokens
241 cur.agents += 1
242 by.set(model, cur)
243 }
244 return [...by.values()].sort((a, b) => b.tokens - a.tokens)
245}
246
247// Tokens a node and everything under it spent.
248export const tokensUnder = (nodes: AgentNode[], n: AgentNode) =>
249 n.kind === 'agent' ? n.tokens ?? 0 : scopeNodes(nodes, { kind: 'node', id: n.id }).filter(k => k.kind === 'agent').reduce((a, k) => a + (k.tokens ?? 0), 0) || (n.tokens ?? 0)
250
251// ── flags: an insight, shown on the row it is about ──────────────────────────
252
253export type Flag = { tone: 'warn' | 'bad' | 'info'; text: string }
254
255// A short tag per row that needs a look: agents that edited a file another agent
256// also edited, the agent that spent the most, a workflow's slowest phase, and the
257// agent that ended last on the critical path. Keys: node ids, "phase:<wf>:<phase>".
258export function rowFlags(scope: AgentNode[], all: AgentNode[], now: number): Map<string, Flag> {
259 const out = new Map<string, Flag>()
260 const agents = scope.filter(n => n.kind === 'agent')
261 for (const o of overlaps(agents)) for (const b of o.by) if (!out.has(b.id)) out.set(b.id, { tone: 'warn', text: `⚠ shares ${short(o.path)}` })
262 const spent = agents.filter(n => (n.tokens ?? 0) > 0)
263 if (spent.length >= 3) {
264 const total = spent.reduce((a, n) => a + (n.tokens ?? 0), 0)
265 const top = [...spent].sort((a, b) => (b.tokens ?? 0) - (a.tokens ?? 0))[0]!
266 const share = Math.round(((top.tokens ?? 0) / total) * 100)
267 if (share >= 40 && !out.has(top.id)) out.set(top.id, { tone: 'info', text: `▲ ${share}% of tokens` })
268 }
269 for (const wf of scope.filter(n => n.kind === 'workflow')) {
270 const spans = pipeline(wf, all).map(p => {
271 const list = childrenOf(all, wf.id).filter(k => (k.phase ?? 'Agents') === p.phase)
272 return { phase: p.phase, ms: Math.max(...list.map(k => endOf(k, now))) - Math.min(...list.map(k => k.startedAt)) }
273 }).filter(p => Number.isFinite(p.ms) && p.ms > 0)
274 if (spans.length < 2) continue
275 const total = spans.reduce((a, p) => a + p.ms, 0)
276 const top = [...spans].sort((a, b) => b.ms - a.ms)[0]!
277 const share = Math.round((top.ms / total) * 100)
278 if (share >= 50) out.set(`phase:${wf.id}:${top.phase}`, { tone: 'info', text: `slowest · ${share}% of time` })
279 }
280 const path = criticalPath(agents, now)
281 const last = path && path.ids.length >= 2 ? path.ids[path.ids.length - 1]! : undefined
282 if (last && !out.has(last)) out.set(last, { tone: 'info', text: '◆ ended last' })
283 return out
284}
285hooks/desktop/svg.ts 334 lines1import type { NodeStatus } from '../../types'
2import type { ThemeName } from '../theme'
3import { ART, type ArtSet, type Slot } from './sprites'
4
5// Every picture the desktop view draws, as SVG source strings. An Svg element is
6// drawn as an image, where currentColor means nothing, so every colour is written
7// out from the desk tokens. Sizes are CSS pixels.
8
9// The desktop can not tell its light or dark mode to a plugin, so these tokens are
10// mid-tone hues that read on both; text and grounds stay the surface's own.
11export type DeskTokens = {
12 name: ThemeName
13 // the pixel art drawn in place of line icons; minimal has none
14 art?: ArtSet
15 // the empty states' titles, and what the empty Live scene shows (its alt text)
16 words: { emptyLive: string; emptyHistory: string; scene: string }
17 accent: string
18 ok: string
19 warn: string
20 bad: string
21 stop: string
22 muted: string
23 rule: string
24 add: string
25 del: string
26 lanes: string[]
27}
28
29export const DESK: Record<ThemeName, DeskTokens> = {
30 minimal: {
31 name: 'minimal', accent: '#3b82f6', ok: '#16a34a', warn: '#d97706', bad: '#dc2626', stop: '#6b7280',
32 muted: '#6b7280', rule: '#9ca3af', add: '#16a34a', del: '#dc2626',
33 lanes: ['#3b82f6', '#8b5cf6', '#0891b2', '#0d9488', '#ea580c', '#64748b'],
34 words: { emptyLive: 'Nothing is running right now.', emptyHistory: 'No finished runs yet.', scene: '' },
35 },
36 kitty: {
37 name: 'kitty', accent: '#e8735a', ok: '#4d9e5c', warn: '#d9893b', bad: '#d9566e', stop: '#9b7f86',
38 muted: '#9b7f86', rule: '#d8b8a8', add: '#4d9e5c', del: '#d9566e',
39 lanes: ['#e8735a', '#a874c4', '#3aa6c4', '#3ea58f', '#d9893b', '#9b7f86'],
40 art: ART.kitty,
41 words: { emptyLive: 'No cats out.', emptyHistory: 'No cats have come home yet.', scene: 'A cat asleep on a keyboard' },
42 },
43 fish: {
44 name: 'fish', accent: '#2f8fc4', ok: '#2f9e6a', warn: '#d9973b', bad: '#d9566e', stop: '#7c8fa0',
45 muted: '#7c8fa0', rule: '#a9c3d4', add: '#2f9e6a', del: '#d9566e',
46 lanes: ['#2f8fc4', '#8b6fd6', '#2aa198', '#d9893b', '#c06c9f', '#7c8fa0'],
47 art: ART.fish,
48 words: { emptyLive: 'Lines are dry.', emptyHistory: 'Nothing in the bucket yet.', scene: 'A rod propped on a dock at night, a fish asleep below' },
49 },
50 dog: {
51 name: 'dog', accent: '#c98a3c', ok: '#4d9e5c', warn: '#c99a1f', bad: '#d9566e', stop: '#9b8670',
52 muted: '#9b8670', rule: '#d8c2a8', add: '#4d9e5c', del: '#d9566e',
53 lanes: ['#c98a3c', '#6f8fd6', '#3ea58f', '#c06c9f', '#8fa62a', '#9b8670'],
54 art: ART.dog,
55 words: { emptyLive: 'No dogs out.', emptyHistory: 'No dogs are back from walks yet.', scene: 'A dog asleep by its dog house' },
56 },
57}
58
59// Running wears the theme's own accent (fish water, kitty coral), so a live run looks
60// like its theme; done is calm, so running and failed stand out. Amber (warn) means
61// "needs a look" only. Status never rests on red vs green: a glyph or word goes with it.
62export const statusColor = (t: DeskTokens, s: NodeStatus) =>
63 s === 'running' ? t.accent : s === 'done' ? t.muted : s === 'failed' ? t.bad : t.stop
64
65const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
66
67// ── pixel sprites ────────────────────────────────────────────────────────────
68// One rect per run of same-coloured pixels in a row, so a 16×16 sprite stays a
69// few hundred characters and the 64×40 scene stays far under the 131072 cap.
70function spriteRects(grid: readonly string[], pal: Record<string, string>, dx = 0): string {
71 let out = ''
72 grid.forEach((row, y) => {
73 let x = 0
74 while (x < row.length) {
75 const ch = row[x]!
76 if (ch === '.') { x++; continue }
77 let end = x + 1
78 while (end < row.length && row[end] === ch) end++
79 out += `<rect x="${x + dx}" y="${y}" width="${end - x}" height="1" fill="${pal[ch]}"/>`
80 x = end
81 }
82 })
83 return out
84}
85
86export const SPRITE_FOR: Record<NodeStatus, Slot> = { running: 'walk0', done: 'done', failed: 'failed', killed: 'stopped' }
87
88export function spriteSvg(art: ArtSet, name: Slot, px: number): string {
89 const grid = art.pix[name]
90 const w = grid[0]!.length
91 const h = grid.length
92 const scale = px / Math.max(w, h)
93 return `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(w * scale)}" height="${Math.round(h * scale)}" viewBox="0 0 ${w} ${h}" shape-rendering="crispEdges">${spriteRects(grid, art.pal)}</svg>`
94}
95
96// The running sprite walks one frame per redraw tick (the pane redraws each second).
97// A plain image: an interactive Svg would sit in a sandboxed frame, which drew a white
98// box and blanked on every redraw.
99export const walkSlot = (now: number): Slot => (['walk0', 'walk1', 'walk2', 'walk3'] as const)[Math.floor(now / 1000) % 4]!
100
101// ── minimal: one line-icon set, 16 px grid ───────────────────────────────────
102const ICON: Record<string, string> = {
103 workflow: '<circle cx="3.75" cy="4.25" r="1.75"/><circle cx="12.25" cy="4.25" r="1.75"/><circle cx="8" cy="11.75" r="1.75"/><path d="M4.8 5.7 7.1 10.2M11.2 5.7 8.9 10.2"/>',
104 group: '<rect x="2.5" y="5.5" width="8" height="8" rx="2"/><path d="M5.5 3h5.5a2 2 0 0 1 2 2v5.5"/>',
105 agent: '<circle cx="8" cy="8" r="5.25"/><circle cx="8" cy="8" r="1.6" fill="COLOR" stroke="none"/>',
106 running: '<circle cx="8" cy="8" r="5.75" opacity=".25"/><path d="M8 2.25a5.75 5.75 0 0 1 5.75 5.75"/>',
107 done: '<circle cx="8" cy="8" r="6"/><path d="m5.3 8.2 1.85 1.85L10.8 6.2"/>',
108 failed: '<circle cx="8" cy="8" r="6"/><path d="m5.9 5.9 4.2 4.2m0-4.2-4.2 4.2"/>',
109 killed: '<circle cx="8" cy="8" r="6"/><rect x="6" y="6" width="4" height="4" rx="1" fill="COLOR" stroke="none"/>',
110 quiet: '<circle cx="8" cy="8" r="6"/><path d="M6 6.5h4l-4 3.5h4"/>',
111 worktree: '<circle cx="4.5" cy="3.5" r="1.5"/><circle cx="4.5" cy="12.5" r="1.5"/><circle cx="11.5" cy="5" r="1.5"/><path d="M4.5 5v6M11.5 6.5c0 3-7 1.8-7 4.5"/>',
112 file: '<path d="M4 2.25h5l3 3v8.5H4Z"/><path d="M9 2.25v3h3"/>',
113 warn: '<path d="M8 2.5 14 13H2Z"/><path d="M8 6.5v3M8 11.2v.1"/>',
114 info: '<circle cx="8" cy="8" r="6"/><path d="M8 7.5v3.5M8 5v.1"/>',
115 empty: '<circle cx="8" cy="8" r="6" stroke-dasharray="2 2"/>',
116}
117
118export function iconSvg(name: string, color: string, px = 16): string {
119 const body = (ICON[name] ?? ICON.agent!).replace(/COLOR/g, color)
120 return `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 16 16" fill="none" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`
121}
122
123// ── small charts ─────────────────────────────────────────────────────────────
124
125// A bar split by status: done, running, failed, stopped, then the empty track.
126export function statusBarSvg(t: DeskTokens, c: { done: number; running: number; failed: number; stopped: number; total: number }, w = 96, h = 6): string {
127 const total = Math.max(1, c.total)
128 const parts: [number, string][] = [[c.done, statusColor(t, 'done')], [c.running, statusColor(t, 'running')], [c.failed, statusColor(t, 'failed')], [c.stopped, statusColor(t, 'killed')]]
129 let x = 0
130 let rects = `<rect x="0" y="0" width="${w}" height="${h}" rx="${h / 2}" fill="${t.rule}" opacity=".35"/>`
131 for (const [n, color] of parts) {
132 if (!n) continue
133 const pw = (n / total) * w
134 rects += `<rect x="${x.toFixed(1)}" y="0" width="${pw.toFixed(1)}" height="${h}" fill="${color}"/>`
135 x += pw
136 }
137 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><clipPath id="c"><rect width="${w}" height="${h}" rx="${h / 2}"/></clipPath><g clip-path="url(#c)">${rects}</g></svg>`
138}
139
140// Lines added and removed as two proportional bars, the larger side scaled to `w`.
141export function diffBarSvg(t: DeskTokens, added: number, removed: number, max: number, w = 60, h = 6): string {
142 const m = Math.max(1, max)
143 const a = Math.max(added ? 2 : 0, Math.round((added / m) * w))
144 const r = Math.max(removed ? 2 : 0, Math.round((removed / m) * w))
145 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><rect x="0" y="0" width="${a}" height="${h}" rx="1" fill="${t.add}"/><rect x="${a + (a && r ? 1 : 0)}" y="0" width="${Math.min(r, w - a)}" height="${h}" rx="1" fill="${t.del}"/></svg>`
146}
147
148// Runs per day: bars from a data-derived scale, its extremes labelled.
149export function sparkSvg(t: DeskTokens, perDay: number[], w = 140, h = 34): string {
150 const max = Math.max(1, ...perDay)
151 const n = perDay.length || 1
152 const bw = (w - (n - 1) * 3) / n
153 const chartH = h - 12
154 const bars = perDay.map((v, i) => {
155 const bh = v ? Math.max(2, (v / max) * chartH) : 1
156 const isToday = i === n - 1
157 return `<rect x="${(i * (bw + 3)).toFixed(1)}" y="${(chartH - bh).toFixed(1)}" width="${bw.toFixed(1)}" height="${bh.toFixed(1)}" rx="1.5" fill="${isToday ? t.accent : t.rule}"/>`
158 }).join('')
159 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${bars}<text x="0" y="${h - 1}" font-size="9" font-family="-apple-system, sans-serif" fill="${t.muted}">7 days ago</text><text x="${w}" y="${h - 1}" font-size="9" font-family="-apple-system, sans-serif" fill="${t.muted}" text-anchor="end">today · max ${max}</text></svg>`
160}
161
162// ── the timeline: one bar per agent on a shared ruler ────────────────────────
163export type TimeBar = { label: string; start: number; end: number; status: NodeStatus; isHeader?: boolean; isSelected?: boolean; isCritical?: boolean }
164
165// `idle`: stretches when no agent ran, shaded across every row.
166export type TimelineOpts = { idle?: { from: number; to: number }[] }
167
168// Type sizes for the pictures. An Svg is the one place the pane sets its own type
169// size, so labels match the native text (about 13 px) instead of shrinking below it.
170export const PIC = { body: 13, small: 12, head: 12, rowH: 32, barH: 14, font: 'font-family="-apple-system, BlinkMacSystemFont, sans-serif"' } as const
171// About how many characters of 13 px text fit in a width.
172const fits = (px: number, size: number = PIC.body) => Math.max(6, Math.floor(px / (size * 0.56)))
173// The height a timeline of these rows draws at, for the Svg box.
174export const timelineHeight = (rows: number) => 30 + rows * PIC.rowH + 6
175
176// The pane's timeline draws its labels as native text (they follow the theme and
177// can be pressed), so its pictures are a ruler and one strip per bar.
178const QUARTERS = [0, 0.25, 0.5, 0.75, 1]
179export const STRIP_H = 24
180export function rulerSvg(t: DeskTokens, from: number, to: number, w: number): string {
181 const span = Math.max(1, to - from)
182 const pad = 4
183 const marks = QUARTERS.map(f => {
184 const tx = pad + f * (w - 2 * pad - 56)
185 return `<text x="${tx.toFixed(1)}" y="15" font-size="${PIC.small}" fill="${t.muted}" text-anchor="${f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}" ${PIC.font}>${esc(clockOff(span * f))}</text>`
186 }).join('')
187 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="20" viewBox="0 0 ${w} 20">${marks}</svg>`
188}
189export function stripSvg(t: DeskTokens, b: TimeBar, from: number, to: number, w: number, idleGaps: { from: number; to: number }[] = []): string {
190 const span = Math.max(1, to - from)
191 const pad = 4
192 const plot = w - 2 * pad - 56
193 const x = (at: number) => pad + ((at - from) / span) * plot
194 const h = STRIP_H
195 const mid = h / 2
196 const grid = QUARTERS.map(f => `<line x1="${(pad + f * plot).toFixed(1)}" y1="0" x2="${(pad + f * plot).toFixed(1)}" y2="${h}" stroke="${t.rule}" stroke-opacity=".3"/>`).join('')
197 const idle = idleGaps.map(g => {
198 const x0 = x(Math.max(from, g.from))
199 const x1 = x(Math.min(to, g.to))
200 return x1 - x0 < 1 ? '' : `<rect x="${x0.toFixed(1)}" y="0" width="${(x1 - x0).toFixed(1)}" height="${h}" fill="${t.rule}" opacity=".16"/>`
201 }).join('')
202 const x0 = x(b.start)
203 const x1 = Math.max(x0 + 4, x(b.end))
204 const color = statusColor(t, b.status)
205 const crit = b.isCritical ? ` stroke="${t.accent}" stroke-width="2.5"` : ''
206 const live = b.status === 'running' ? `<rect x="${(x1 - 8).toFixed(1)}" y="${mid - PIC.barH / 2}" width="8" height="${PIC.barH}" fill="${color}" opacity=".5"/>` : ''
207 const bar = `<rect x="${x0.toFixed(1)}" y="${mid - PIC.barH / 2}" width="${(x1 - x0).toFixed(1)}" height="${PIC.barH}" rx="4" fill="${color}" opacity="${b.status === 'running' ? 0.75 : 0.92}"${crit}/>`
208 const dur = `<text x="${(x1 + 6).toFixed(1)}" y="${mid + 4}" font-size="${PIC.small}" fill="${t.muted}" ${PIC.font}>${esc(clockOff(b.end - b.start).slice(1))}</text>`
209 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${idle}${grid}${bar}${live}${dur}</svg>`
210}
211
212export function timelineSvg(t: DeskTokens, bars: TimeBar[], from: number, to: number, w: number, opts: TimelineOpts = {}): string {
213 // labels get their own column; bars never run under them
214 const LABEL = Math.min(300, Math.max(150, Math.round(w * 0.32)))
215 const DUR = 64
216 const plot = Math.max(80, w - LABEL - DUR - 12)
217 const span = Math.max(1, to - from)
218 const rowH = PIC.rowH
219 const top = 30
220 const h = timelineHeight(bars.length)
221 const F = PIC.font
222 const x = (at: number) => LABEL + ((at - from) / span) * plot
223 const ticks = [0, 0.25, 0.5, 0.75, 1].map(f => {
224 const tx = LABEL + f * plot
225 return `<line x1="${tx}" y1="${top - 6}" x2="${tx}" y2="${h}" stroke="${t.rule}" stroke-opacity=".3"/><text x="${tx}" y="16" font-size="${PIC.small}" fill="${t.muted}" text-anchor="${f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}" ${F}>${esc(clockOff(span * f))}</text>`
226 }).join('')
227 const idle = (opts.idle ?? []).map(g => {
228 const x0 = x(Math.max(from, g.from))
229 const x1 = x(Math.min(to, g.to))
230 return x1 - x0 < 1 ? '' : `<rect x="${x0.toFixed(1)}" y="${top - 6}" width="${(x1 - x0).toFixed(1)}" height="${h - top + 6}" fill="${t.rule}" opacity=".16"><title>idle ${esc(clockOff(g.to - g.from).slice(1))}</title></rect>`
231 }).join('')
232 const rows = bars.map((b, i) => {
233 const y = top + i * rowH
234 const mid = y + rowH / 2
235 if (b.isHeader) {
236 // a run or phase heading: full width, with a rule above it
237 return `<line x1="0" y1="${y + 2}" x2="${w}" y2="${y + 2}" stroke="${t.rule}" stroke-opacity=".45"/><text x="0" y="${mid + 6}" font-size="${PIC.head}" font-weight="700" fill="${t.muted}" ${F}>${esc(clip(b.label, fits(w, PIC.head)))}</text>`
238 }
239 const x0 = x(b.start)
240 const x1 = Math.max(x0 + 4, x(b.end))
241 const color = statusColor(t, b.status)
242 const sel = b.isSelected ? `<rect x="0" y="${y + 2}" width="${w}" height="${rowH - 4}" fill="${t.accent}" opacity=".14" rx="5"/>` : ''
243 const live = b.status === 'running' ? `<rect x="${x1 - 8}" y="${mid - PIC.barH / 2}" width="8" height="${PIC.barH}" fill="${color}" opacity=".5"/>` : ''
244 // the critical path: an accent outline, and the label in bold
245 const crit = b.isCritical ? ` stroke="${t.accent}" stroke-width="2.5"` : ''
246 const weight = b.isCritical ? ' font-weight="600"' : ''
247 const label = `<text x="12" y="${mid + 5}" font-size="${PIC.body}" fill="${t.muted}"${weight} ${F}>${esc(clip(b.label, fits(LABEL - 20)))}<title>${esc(b.label)}</title></text>`
248 const bar = `<rect x="${x0.toFixed(1)}" y="${mid - PIC.barH / 2}" width="${(x1 - x0).toFixed(1)}" height="${PIC.barH}" rx="4" fill="${color}" opacity="${b.status === 'running' ? 0.75 : 0.92}"${crit}/>`
249 const dur = `<text x="${(x1 + 6).toFixed(1)}" y="${mid + 4}" font-size="${PIC.small}" fill="${t.muted}" ${F}>${esc(clockOff(b.end - b.start).slice(1))}</text>`
250 return `${sel}${label}${bar}${live}${dur}`
251 }).join('')
252 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${idle}${ticks}${rows}</svg>`
253}
254
255// ── the trace: lanes on a shared time axis, arrows between them ──────────────
256export type TraceMark = { lane: number; to?: number; at: number; kind: string; text: string; isSelected?: boolean }
257
258// `focus`: the lane of the agent picked elsewhere; the other lanes draw faint.
259export function traceSvg(t: DeskTokens, lanes: { label: string; chip: string; status: NodeStatus; depth?: number }[], marks: TraceMark[], from: number, to: number, w: number, focus?: number): string {
260 const LABEL = Math.min(240, Math.max(140, Math.round(w * 0.28)))
261 const plot = Math.max(80, w - LABEL - 20)
262 const span = Math.max(1, to - from)
263 const laneH = 40
264 const h = 24 + lanes.length * laneH + 8
265 const x = (at: number) => LABEL + ((at - from) / span) * plot
266 const yOf = (lane: number) => 24 + lane * laneH + laneH / 2
267 const color = (lane: number) => t.lanes[lane % t.lanes.length]!
268 const ruler = [0, 0.5, 1].map(f => `<text x="${LABEL + f * plot}" y="14" font-size="${PIC.small}" fill="${t.muted}" text-anchor="${f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}" font-family="-apple-system, sans-serif">${esc(clockOff(span * f))}</text>`).join('')
269 const faint = (lane: number) => (focus !== undefined && focus >= 0 && lane !== focus ? ' opacity=".3"' : '')
270 const laneRows = lanes.map((l, i) => {
271 const y = yOf(i)
272 // a sub-agent's lane is indented under the lane that spawned it
273 const dx = Math.min(3, l.depth ?? 0) * 12
274 return `<g${faint(i)}><circle cx="${8 + dx}" cy="${y}" r="4" fill="${statusColor(t, l.status)}"/><text x="${18 + dx}" y="${y + 5}" font-size="${PIC.body}" fill="${t.muted}" font-family="-apple-system, sans-serif">${esc(clip(l.label, fits(LABEL - 26 - dx)))}</text><line x1="${LABEL}" y1="${y}" x2="${LABEL + plot}" y2="${y}" stroke="${color(i)}" stroke-opacity=".35" stroke-width="2"/></g>`
275 }).join('')
276 const arrows = marks.filter(m => m.to !== undefined && m.to !== m.lane).map(m => {
277 const x0 = x(m.at)
278 const y0 = yOf(m.lane)
279 const y1 = yOf(m.to!)
280 const dash = m.kind === 'message' ? ' stroke-dasharray="4 3"' : m.kind === 'handback' ? ' stroke-dasharray="1.5 3"' : ''
281 return `<path d="M${x0.toFixed(1)} ${y0} L${x0.toFixed(1)} ${y1 + (y1 > y0 ? -5 : 5)}" stroke="${color(m.lane)}" stroke-width="1.5"${dash}/><path d="M${(x0 - 4).toFixed(1)} ${y1 + (y1 > y0 ? -8 : 8)} L${x0.toFixed(1)} ${y1 + (y1 > y0 ? -2 : 2)} L${(x0 + 4).toFixed(1)} ${y1 + (y1 > y0 ? -8 : 8)}" fill="none" stroke="${color(m.lane)}" stroke-width="1.5"/>`
282 }).join('')
283 const dots = marks.map(m => {
284 const cx = x(m.at)
285 const cy = yOf(m.lane)
286 const c = m.kind === 'fail' ? t.bad : color(m.lane)
287 const ring = m.isSelected ? `<circle cx="${cx.toFixed(1)}" cy="${cy}" r="7" fill="none" stroke="${t.accent}" stroke-width="2"/>` : ''
288 const shape = m.kind === 'edit'
289 ? `<rect x="${(cx - 4).toFixed(1)}" y="${cy - 4}" width="8" height="8" transform="rotate(45 ${cx.toFixed(1)} ${cy})" fill="${c}"/>`
290 : m.kind === 'fail'
291 ? `<path d="M${(cx - 4).toFixed(1)} ${cy - 4}l8 8m0-8-8 8" stroke="${c}" stroke-width="2"/>`
292 : m.kind === 'quiet'
293 ? `<rect x="${(cx - 6).toFixed(1)}" y="${cy - 3}" width="12" height="6" fill="${t.rule}" opacity=".6"/>`
294 : `<circle cx="${cx.toFixed(1)}" cy="${cy}" r="3.5" fill="${c}"/>`
295 return `<g${faint(m.lane)}>${ring}${shape}<title>${esc(m.text)}</title></g>`
296 }).join('')
297 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${ruler}${laneRows}${arrows}${dots}</svg>`
298}
299
300// ── a picture to save: a white page with a title, a subtitle and a legend over the drawing ──
301// `inner` is a whole <svg> of `innerH` rows; it is placed as a nested svg, so its own
302// coordinates stay as they are.
303export function pictureSvg(t: DeskTokens, title: string, subtitle: string, legend: string[], inner: string, w: number, innerH: number): string {
304 const PAD = 24
305 const head = 64
306 const foot = legend.length ? 28 : 8
307 const h = head + innerH + foot + PAD
308 const font = 'font-family="-apple-system, Helvetica, Arial, sans-serif"'
309 // legend items one after another, spaced by their own length (about 5.6 px a character at 11 px)
310 let lx = PAD
311 const keys = legend.map(k => {
312 const el = `<text x="${lx}" y="${head + innerH + 22}" font-size="11" fill="${t.muted}" ${font}>${esc(k)}</text>`
313 lx += Math.round(k.length * 5.6) + 28
314 return el
315 }).join('')
316 const body = inner.replace(/^<svg /, `<svg x="${PAD}" y="${head}" `)
317 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w + PAD * 2}" height="${h}" viewBox="0 0 ${w + PAD * 2} ${h}">`
318 + `<rect width="100%" height="100%" fill="#ffffff"/>`
319 + `<text x="${PAD}" y="${PAD + 12}" font-size="17" font-weight="600" fill="#111827" ${font}>${esc(clip(title, 90))}</text>`
320 + `<text x="${PAD}" y="${PAD + 32}" font-size="12" fill="${t.muted}" ${font}>${esc(clip(subtitle, 140))}</text>`
321 + `${body}${keys}</svg>`
322}
323
324// ── helpers ──────────────────────────────────────────────────────────────────
325export const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
326
327function clockOff(ms: number): string {
328 const s = Math.round(ms / 1000)
329 if (s < 60) return `+${s}s`
330 const m = Math.floor(s / 60)
331 if (m < 60) return `+${m}m${s % 60 ? ` ${String(s % 60).padStart(2, '0')}s` : ''}`
332 return `+${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
333}
334hooks/desktop/pane.tsx 941 lines1import type { AgentNode, DeskUi, EditRecord, PatternsDoc, TraceZoom, ViewProps } from '../../types'
2import { HISTORY_FILTERS, HISTORY_FILTER_NAMES, historyItems, historyStats, outcomeOf, runTokens } from '../history'
3import { boardLanes, criticalPath, idleGaps, insights, listTimelineRows, liveGroups, rollup, timelineRows, type Lane } from '../lens'
4import {
5 childrenOf, counts, fileRows, folderKey, joinNodes, lineDiff, noReportReason, overlaps, pipeline, prettyModel, prettyType, runKey,
6 runTree, scopeNodes, shortPaths, topItems, type Item,
7} from '../list'
8import { kTokens, reportFacts, reportOf } from '../report'
9import { ZOOMS, ZOOM_NAMES } from '../trace'
10import { unifiedHunks } from '../view'
11import {
12 BriefBlock, Chip, Empty, Heading, KindMark, PlainHeader, ReportBlock, SectionLabel, StatusMark, STATUS_GLYPH, STATUS_WORD, aiLabel, briefMarkdown, changeTotals, clock, duration, factsOf, metaLine, num,
13 mdText, outputMarkdown, tint, tokensOf, type Els, type Fact, type Part,
14} from './parts'
15import { STRIP_H, clip, diffBarSvg, iconSvg, rulerSvg, sparkSvg, spriteSvg, statusBarSvg, statusColor, stripSvg, traceSvg, walkSlot, type DeskTokens, type TimeBar } from './svg'
16
17// The desktop's own view of agent-tree: native controls, Svg pictures and pixel
18// cats, drawn straight into the pane (a Client's elements have no Svg). It takes
19// the same data the terminal view gets and the desk state; presses call `acts`,
20// which the hooks module turns into $.state writes.
21
22export type DeskActs = {
23 set: (patch: Partial<DeskUi>) => void
24 openDiff: (path: string | null) => void
25 askTrace: (run: string | null, zoom: TraceZoom, offset: number) => void
26 /** Ask Sonnet for a run's brief, or for patterns across runs (the hooks check ai: full again). */
27 explain: (run: string) => void
28 patterns: () => void
29 /** Save a run's timeline or trace as a picture in ~/Downloads/agent-tree (the hooks say where). */
30 exportPic: (run: string, lens: 'timeline' | 'trace', zoom: TraceZoom, focus?: string) => void
31}
32
33// Below this many columns nothing fits well, so the pane says so. The desktop
34// lays panes out in character cells, as the terminal does; a cell is about 7.5 px.
35export const MIN_COLUMNS = 60
36export const WIDE_COLUMNS = 120
37const CELL_PX = 7.5
38
39export function drawDesktop(els: Els, data: ViewProps, ui: DeskUi, acts: DeskActs, columns: number) {
40 const { Box, Text } = els
41 const t = tokensOf(data.theme ?? 'minimal')
42 const now = data.at
43 if (columns < MIN_COLUMNS) {
44 return (
45 <Box flexDirection="column" alignItems="center" paddingY={2}>
46 <Text color={t.muted}>Widen the pane to at least 480 px to see your agents.</Text>
47 </Box>
48 )
49 }
50 const here = data.repo ? folderKey(data.repo) : undefined
51 const history = ui.onlyRepo && here
52 ? (() => {
53 const byId = new Map(data.history.map(n => [n.id, n]))
54 const top = (n: AgentNode) => { let x = n; while (x.parentId && byId.has(x.parentId)) x = byId.get(x.parentId)!; return x }
55 return data.history.filter(n => runKey(top(n)) === here)
56 })()
57 : data.history
58 const pool = ui.tab === 'live' ? data.nodes : history
59 const all = joinNodes(data.nodes, data.history)
60 const run = ui.run ? (pool.find(n => n.id === ui.run) ?? all.find(n => n.id === ui.run)) : undefined
61 const wide = columns >= WIDE_COLUMNS
62 const ctx: Ctx = { els, t, ui, acts, now, all, pool, wide, columns, data }
63
64 return (
65 <Box flexDirection="column" gap={1} paddingX={1} paddingY={1}>
66 {Header(ctx, history, run)}
67 {Insights(ctx, run)}
68 {run ? RunView(ctx, run) : ui.tab === 'live' ? LiveList(ctx) : HistoryPage(ctx, history)}
69 </Box>
70 )
71}
72
73type Ctx = {
74 els: Els; t: DeskTokens; ui: DeskUi; acts: DeskActs; now: number; all: AgentNode[]; pool: AgentNode[]
75 wide: boolean; columns: number; data: ViewProps
76}
77
78const openRun = (c: Ctx, id: string | null) => {
79 c.acts.set({ run: id, sel: null, view: 'overview', file: null, traceOffset: 0, confirm: '', note: '', ...(id === null && c.ui.lens === 'trace' ? { lens: 'tree' as const } : {}) })
80 if (c.ui.file) c.acts.openDiff(null)
81 if (c.ui.lens === 'trace') c.acts.askTrace(id, c.ui.zoom, 0)
82}
83
84// A segmented control: one Button per option, the chosen one drawn as primary.
85function Segmented<T extends string>(c: Ctx, key: string, options: readonly [T, string, string?][], current: T, pick: (v: T) => void) {
86 const { Box, Button } = c.els
87 return (
88 <Box flexDirection="row" gap={0}>
89 {options.map(([v, label, hotkey]) => (
90 <Button key={`${key}:${v}`} label={label} {...(hotkey ? { hotkey } : {})} {...(v === current ? { variant: 'primary' as const } : {})} onPress={() => pick(v)} />
91 ))}
92 </Box>
93 )
94}
95
96// ── header: what you see, where, and how it is going ──────────────────────────
97function Header(c: Ctx, history: AgentNode[], run: AgentNode | undefined) {
98 const { Box, Text, Button, Input, Svg } = c.els
99 const { t, ui } = c
100 const liveTops = c.data.nodes.filter(n => !n.parentId || !c.data.nodes.some(m => m.id === n.parentId))
101 const running = liveTops.filter(n => n.status === 'running').length
102 const histRuns = history.filter(n => !n.parentId || !history.some(m => m.id === n.parentId)).length
103 const cnt = counts(c.pool.filter(n => n.kind === 'agent'))
104 // Board last: it is the view used least
105 const lenses: [DeskUi['lens'], string][] = [['tree', 'Tree'], ['timeline', 'Timeline'], ...(run ? [['trace', 'Trace'] as [DeskUi['lens'], string]] : []), ['board', 'Board']]
106 // a count draws in its colour only when it is not zero, so the eye lands on what is there
107 const tally = (n: number, word: string, color: string) => <Text color={n ? color : t.muted} {...(n ? { bold: true } : {})}>{n} {word}</Text>
108 const lensBar = Segmented(c, 'lens', lenses, ui.lens, v => {
109 c.acts.set({ lens: v, traceOffset: 0 })
110 c.acts.askTrace(v === 'trace' && run ? run.id : null, ui.zoom, 0)
111 })
112 // a run is open: one row of controls, so its summary card sits near the top.
113 // The run's name shows here only when the card below is about a part of it.
114 if (run) {
115 const inPart = !!ui.sel && ui.sel !== run.id
116 return (
117 <Box flexDirection="column" gap={1}>
118 <Box flexDirection="row" columnGap={2} rowGap={1} flexWrap="wrap" alignItems="center">
119 <Button key="back" plain label={`‹ ${ui.tab === 'live' ? 'Live' : 'History'}`} onPress={() => openRun(c, null)} />
120 {lensBar}
121 <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
122 {inPart ? <Button key="crumb" plain dimColor label={`in ${run.label}`} onPress={() => c.acts.set({ sel: null, file: null })} /> : null}
123 </Box>
124 {ExplainButton(c, run)}
125 </Box>
126 {ui.note ? <Text color={t.warn}>{ui.note}</Text> : null}
127 {ui.confirm === 'explain' ? ConfirmRow(c, 'explain', 'Write a new brief? It asks Sonnet again.', () => c.acts.explain(run.id)) : null}
128 </Box>
129 )
130 }
131 return (
132 <Box flexDirection="column" gap={1}>
133 {/* row 1: what you look at */}
134 <Box flexDirection="row" columnGap={2} rowGap={1} flexWrap="wrap" alignItems="center">
135 <Box flexDirection="row" gap={1} alignItems="center">
136 {t.art
137 ? <Svg source={spriteSvg(t.art, 'group', 20)} alt="Agents" width={20} height={20} />
138 : <Svg source={iconSvg('workflow', t.accent, 18)} alt="Agents" width={18} height={18} />}
139 <Text bold>Agents</Text>
140 </Box>
141 {Segmented(c, 'tab', [['live', `Live ${running}`, '1'], ['history', `History ${histRuns}`, '2']], ui.tab, v => {
142 c.acts.set({ tab: v, run: null, sel: null, file: null, view: 'overview', ...(ui.lens === 'trace' ? { lens: 'tree' as const } : {}) })
143 if (ui.lens === 'trace') c.acts.askTrace(null, ui.zoom, 0)
144 })}
145 {Segmented(c, 'scope', [['repo', 'This repo', 'r'], ['all', 'All repos']], ui.onlyRepo ? 'repo' : 'all', v => c.acts.set({ onlyRepo: v === 'repo' }))}
146 </Box>
147 {/* row 2: how you look at it */}
148 <Box flexDirection="row" columnGap={2} rowGap={1} flexWrap="wrap" alignItems="center">
149 {lensBar}
150 {ui.tab === 'history'
151 ? <Box flexGrow={1} minWidth={24}><Input key="search" placeholder="Search names and outcomes" value={ui.query} onInput={(v: string) => c.acts.set({ query: v })} onSubmit={(v: string) => c.acts.set({ query: v })} /></Box>
152 : null}
153 </Box>
154 {/* row 3: one quiet status line */}
155 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
156 {tally(cnt.running, `${STATUS_GLYPH.running} running`, statusColor(t, 'running'))}<Text color={t.muted}>·</Text>
157 {tally(cnt.done, `${STATUS_GLYPH.done} done`, t.muted)}<Text color={t.muted}>·</Text>
158 {tally(cnt.failed + cnt.stopped, `${STATUS_GLYPH.failed} failed or stopped`, t.bad)}<Text color={t.muted}>·</Text>
159 <Text color={t.muted}>{ui.onlyRepo && c.data.repo ? shortHome(c.data.repo) : 'all repos'}</Text><Text color={t.muted}>·</Text>
160 <Text color={c.data.ai === 'off' ? t.muted : t.accent}>AI · {c.data.ai ?? 'cheap'}</Text>
161 <Text color={t.muted}>(change in /config)</Text>
162 </Box>
163 {ui.note ? <Text color={t.warn}>{ui.note}</Text> : null}
164 </Box>
165 )
166}
167
168const shortHome = (p: string) => p.replace(/^\/Users\/[^/]+/, '~')
169
170const isFull = (c: Ctx) => c.data.ai === 'full'
171
172// Explain this run: Sonnet, on Full only; with a brief there it asks first.
173function ExplainButton(c: Ctx, run: AgentNode) {
174 const { Button } = c.els
175 const writing = !!c.data.explaining?.includes(run.id)
176 const label = writing ? 'Writing the brief…' : run.explain ? 'Regenerate brief' : 'Explain this run'
177 return (
178 <Button key="explain" label={label} hotkey="e" {...(isFull(c) ? {} : { dimColor: true })} onPress={() => {
179 if (!isFull(c)) return c.acts.set({ note: 'Explain needs ai: full in /config. It asks Sonnet, on demand.' })
180 if (writing) return
181 if (run.explain) return c.acts.set({ confirm: 'explain', note: '', view: 'overview' })
182 c.acts.set({ confirm: '', note: '', view: 'overview' })
183 c.acts.explain(run.id)
184 }} />
185 )
186}
187
188// A small confirm row for a Sonnet job that would write over what is there.
189function ConfirmRow(c: Ctx, what: 'explain' | 'patterns', question: string, go: () => void) {
190 const { Box, Text, Button } = c.els
191 return (
192 <Box flexDirection="row" gap={2} alignItems="center">
193 <Text color={c.t.warn}>{question}</Text>
194 <Button key={`${what}:yes`} label="Yes, ask Sonnet" variant="primary" onPress={() => { c.acts.set({ confirm: '' }); go() }} />
195 <Button key={`${what}:no`} plain label="Cancel" onPress={() => c.acts.set({ confirm: '' })} />
196 </Box>
197 )
198}
199
200// ── the insights strip: what needs a look, each naming the item it is about ──
201function Insights(c: Ctx, run: AgentNode | undefined) {
202 const { Box, Text, Button, Svg } = c.els
203 const { t } = c
204 if (!run && c.ui.tab === 'history') return null
205 const scope = run ? scopeNodes(c.all, { kind: 'node', id: run.id }) : c.pool
206 const list = insights(scope, c.all, c.now)
207 if (!list.length) return null
208 const go = (it: (typeof list)[number]) => {
209 if (!it.target) return
210 if (run) c.acts.set({ sel: it.target, view: it.kind === 'overlap' ? 'changes' : 'overview' })
211 else {
212 const byId = new Map(c.all.map(n => [n.id, n]))
213 let top = byId.get(it.target)
214 while (top?.parentId && byId.has(top.parentId)) top = byId.get(top.parentId)
215 if (top) c.acts.set({ run: top.id, sel: it.target, view: it.kind === 'overlap' ? 'changes' : 'overview', file: null })
216 }
217 }
218 // one insight per line; warnings and failures in a box, plain notes as a quiet line under it
219 const line = (it: (typeof list)[number], i: number) => (
220 <Box key={`ins-${i}`} flexDirection="row" gap={1} alignItems="center">
221 <Svg source={iconSvg(it.tone === 'bad' ? 'failed' : it.kind === 'quiet' ? 'quiet' : it.tone === 'info' ? 'info' : 'warn', it.tone === 'bad' ? t.bad : it.tone === 'warn' ? t.warn : t.muted, 14)} alt={it.kind} width={14} height={14} />
222 <Box flexShrink={1}><Button key={`insight:${i}`} plain {...(it.tone === 'info' ? { dimColor: true } : {})} label={it.text} onPress={() => go(it)} /></Box>
223 </Box>
224 )
225 const loud = list.map((it, i) => [it, i] as const).filter(([it]) => it.tone !== 'info')
226 const quiet = list.map((it, i) => [it, i] as const).filter(([it]) => it.tone === 'info')
227 return (
228 <Box flexDirection="column" gap={1}>
229 {loud.length
230 ? (
231 <Box flexDirection="column" backgroundColor={tint(loud.some(([it]) => it.tone === 'bad') ? t.bad : t.warn)} paddingX={2} paddingY={1}>
232 <Text bold color={loud.some(([it]) => it.tone === 'bad') ? t.bad : t.warn}>Needs a look ({loud.length})</Text>
233 {loud.map(([it, i]) => line(it, i))}
234 </Box>
235 )
236 : null}
237 {quiet.length ? <Box flexDirection="column">{quiet.map(([it, i]) => line(it, i))}</Box> : null}
238 </Box>
239 )
240}
241
242// ── Live, no run open: one card per running run ──────────────────────────────
243function LiveList(c: Ctx) {
244 const { Box } = c.els
245 const items = topItems(c.data.nodes, 'all', false, c.now).filter((it): it is Extract<Item, { kind: 'node' }> => it.kind === 'node' && it.depth === 0)
246 if (c.ui.lens === 'board') return Board(c, boardLanes(undefined, c.data.nodes, items.map(i => i.node), 'all'), undefined)
247 if (c.ui.lens === 'timeline') return Timeline(c, undefined, items.map(i => i.node))
248 if (!items.length) {
249 return Empty(c.els, c.t, c.t.words.emptyLive, 'Subagents and workflows appear here while they run, then move to History.')
250 }
251 return <Box flexDirection="column" gap={1}>{items.map(it => RunCard(c, it.node, c.data.nodes))}</Box>
252}
253
254// A live run: its name in bold with its counts, then one row per agent grouped by
255// status (running, then failed or stopped, then done, which folds). No tinted box:
256// weight, glyphs and spacing carry the order.
257function RunCard(c: Ctx, n: AgentNode, nodes: AgentNode[]) {
258 const { Box, Text, Button } = c.els
259 const { t, ui } = c
260 const scope = scopeNodes(nodes, { kind: 'node', id: n.id })
261 const agents = scope.filter(k => k.kind === 'agent' && k.id !== n.id)
262 const files = fileRows(scope)
263 const ch = changeTotals(files)
264 const clash = n.kind === 'group' ? overlaps(agents) : []
265 const cn = counts(agents)
266 const sum = [cn.running ? `${cn.running} running` : '', cn.failed + cn.stopped ? `${cn.failed + cn.stopped} failed or stopped` : '', cn.done ? `${cn.done} done` : ''].filter(Boolean).join(' · ')
267 const open = (k: AgentNode) => c.acts.set({ run: n.id, sel: k.id, file: null })
268 const doneKey = `done:${n.id}`
269 const row = (k: AgentNode) => {
270 const step = k.status === 'running' ? (k.activity ?? k.lastTool ?? '') : (reportOf(k)?.result ?? '')
271 const quiet = isQuiet(k, c.now)
272 return (
273 <Box key={`lr-${k.id}`} flexDirection="row" gap={1} alignItems="center" paddingLeft={2} hover={{ backgroundColor: tint(t.accent, '14') }}>
274 {StatusMark(c.els, t, k.status, 14, quiet)}
275 <Box flexShrink={1} minWidth={10} overflow="hidden"><Button key={`lsel:${k.id}`} plain label={clip(k.label, 48)} onPress={() => open(k)} /></Box>
276 <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
277 {quiet
278 ? <Text color={t.warn} wrap="truncate-end">⚑ quiet {duration(c.now - (k.lastToolAt ?? k.startedAt))}</Text>
279 : <Text color={t.muted} wrap="truncate-end">{step ? `· ${step}` : ''}</Text>}
280 </Box>
281 <Box flexShrink={0}><Text color={t.muted}>{duration((k.endedAt ?? c.now) - k.startedAt)}{k.tokens ? ` · ${kTokens(k.tokens)}` : ''}</Text></Box>
282 </Box>
283 )
284 }
285 return (
286 <Box key={`card-${n.id}`} flexDirection="column" paddingBottom={1}>
287 <Box flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
288 {StatusMark(c.els, t, n.status)}
289 {KindMark(c.els, t, n.kind)}
290 <Button key={`run:${n.id}`} plain label={clip(n.label, 70)} onPress={() => openRun(c, n.id)} />
291 <Text color={t.muted}>{sum ? `· ${sum}` : ''}</Text>
292 </Box>
293 <Box paddingLeft={2}><Text color={t.muted}>{metaLine(n, c.now)}{files.length ? ` · ${files.length} file${files.length === 1 ? '' : 's'} +${num(ch.added)} −${num(ch.removed)}` : ''}</Text></Box>
294 {n.kind === 'agent' && !agents.length ? null : liveGroups(nodes, n.id).map(g => {
295 const isDone = g.status === 'done'
296 const isOpen = !isDone || ui.flipped.includes(doneKey)
297 return (
298 <Box key={`lg-${n.id}-${g.status}`} flexDirection="column" paddingTop={1}>
299 <Box flexDirection="row" gap={1} alignItems="center" paddingLeft={2}>
300 {isDone
301 ? <Button key={`fold:${doneKey}`} plain label={`${isOpen ? '▾' : '▸'} ${STATUS_GLYPH.done} DONE ${g.nodes.length}`} onPress={() => c.acts.set({ flipped: toggle(ui.flipped, doneKey) })} />
302 : <Text color={statusColor(t, g.status)} bold>{STATUS_GLYPH[g.status]} {STATUS_WORD[g.status].toUpperCase()} {g.nodes.length}</Text>}
303 </Box>
304 {isOpen ? g.nodes.map(row) : null}
305 </Box>
306 )
307 })}
308 {clash.map(o => <Text key={`clash-${o.path}`} color={t.warn}>⚠ {o.path.split('/').pop()} edited by {o.by.length} members ({o.by.map(b => b.label).join(', ')})</Text>)}
309 </Box>
310 )
311}
312
313// ── History, no run open: numbers, filters, runs by day ──────────────────────
314function HistoryPage(c: Ctx, history: AgentNode[]) {
315 const { Box, Text, Button, Svg } = c.els
316 const { t, ui } = c
317 if (ui.lens === 'board') return Board(c, boardLanes(undefined, history, history.filter(n => !n.parentId || !history.some(m => m.id === n.parentId)), 'all'), undefined)
318 if (ui.lens === 'timeline') return Timeline(c, undefined, history.filter(n => !n.parentId || !history.some(m => m.id === n.parentId)).slice(0, 30))
319 const stats = historyStats(history, c.now)
320 const items = historyItems(history, c.now, { filter: ui.hfilter, query: ui.query, olderOpen: ui.olderOpen })
321 const stat = (value: string, label: string) => (
322 <Box flexDirection="column">
323 <Text bold>{value}</Text>
324 <Text color={t.muted}>{label}</Text>
325 </Box>
326 )
327 return (
328 <Box flexDirection="column" gap={1}>
329 <Box flexDirection="row" gap={4} alignItems="flex-end" flexWrap="wrap">
330 {stat(String(stats.runs), 'runs')}
331 {stat(`${stats.okPct}%`, 'finished OK')}
332 {stat(kTokens(stats.tokens), 'tokens')}
333 <Svg source={sparkSvg(t, stats.perDay)} alt={`Runs per day for 7 days: ${stats.perDay.join(', ')}`} width={140} height={34} />
334 {c.data.ai !== 'off' || c.data.aiWeek ? stat(kTokens(c.data.aiWeek ?? 0), 'AI tokens this week') : null}
335 </Box>
336 <Box flexDirection="row" gap={2} alignItems="center" flexWrap="wrap">
337 {Segmented(c, 'hfilter', HISTORY_FILTERS.map(f => [f, HISTORY_FILTER_NAMES[f].replace(/^./, ch => ch.toUpperCase())] as [typeof f, string]), ui.hfilter, v => c.acts.set({ hfilter: v }))}
338 {ui.query ? <Button key="clear-search" plain label={`Clear “${clip(ui.query, 20)}”`} onPress={() => c.acts.set({ query: '' })} /> : null}
339 </Box>
340 {!ui.query && ui.hfilter === 'all' ? Patterns(c, c.data.patterns) : null}
341 {items.length === 0
342 ? Empty(c.els, t, t.words.emptyHistory, ui.query || ui.hfilter !== 'all' ? 'Nothing matches the search or filter.' : 'Finished runs land here.')
343 : (
344 <Box flexDirection="column">
345 {items.map((it, i) => {
346 if (it.kind === 'header') {
347 return (
348 <Box key={`h-${i}`} flexDirection="row" gap={2} paddingTop={1}>
349 <Text bold>{it.text}</Text>
350 <Text color={t.muted}>{it.note ?? ''}</Text>
351 {it.isOpen === false || (it.text === 'Older')
352 ? <Button key="older" plain label={ui.olderOpen ? 'Hide' : 'Show'} onPress={() => c.acts.set({ olderOpen: !ui.olderOpen })} />
353 : null}
354 </Box>
355 )
356 }
357 if (it.kind !== 'node') return null
358 return HistoryRow(c, it.node, history)
359 })}
360 </Box>
361 )}
362 </Box>
363 )
364}
365
366// Patterns across runs: Sonnet's cards, each with its evidence, one thing to try, and its runs.
367function Patterns(c: Ctx, doc: PatternsDoc | undefined) {
368 const { Box, Text, Button, Svg } = c.els
369 const { t, ui } = c
370 if (!isFull(c) && !doc) return null
371 const busy = !!c.data.patternsBusy
372 const label = busy ? 'writing… (Sonnet)' : doc ? aiLabel(doc, c.now) : 'Sonnet looks for what repeats across your runs.'
373 const press = () => {
374 if (!isFull(c)) return c.acts.set({ note: 'Patterns need ai: full in /config. They ask Sonnet, on demand.' })
375 if (busy) return
376 if (doc) return c.acts.set({ confirm: 'patterns', note: '', patternsOpen: true })
377 c.acts.set({ confirm: '', note: '', patternsOpen: true })
378 c.acts.patterns()
379 }
380 return (
381 <Box flexDirection="column" gap={1} backgroundColor={tint(t.rule)} paddingX={2} paddingY={1}>
382 <Box flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
383 {doc ? <Button key="patterns:fold" plain label={ui.patternsOpen ? '▾' : '▸'} onPress={() => c.acts.set({ patternsOpen: !ui.patternsOpen })} /> : null}
384 <Text bold>Patterns across runs</Text>
385 <Box flexGrow={1}><Text color={t.muted}>{label}</Text></Box>
386 <Button key="patterns:go" label={busy ? 'Looking…' : doc ? 'Regenerate' : 'Find patterns'} hotkey="g" {...(isFull(c) ? {} : { dimColor: true })} onPress={press} />
387 </Box>
388 {ui.confirm === 'patterns' ? ConfirmRow(c, 'patterns', 'Look for patterns again? It asks Sonnet again.', () => c.acts.patterns()) : null}
389 {doc && ui.patternsOpen
390 ? doc.cards.map((card, i) => (
391 <Box key={`pat-${i}`} flexDirection="column" paddingLeft={1}>
392 <Box flexDirection="row" gap={1} alignItems="center">
393 <Svg source={iconSvg('warn', t.warn, 14)} alt="Pattern" width={14} height={14} />
394 <Text bold>{card.title}</Text>
395 </Box>
396 {card.evidence ? <Text color={t.muted}>{card.evidence}</Text> : null}
397 {card.try ? <Text><Text color={t.accent} bold>Try: </Text>{card.try}</Text> : null}
398 {card.runs.length
399 ? (
400 <Box flexDirection="row" gap={1} flexWrap="wrap">
401 {card.runs.map(r => <Button key={`prun:${i}:${r.id}`} plain label={`↳ ${clip(r.label, 40)}`} onPress={() => openRun(c, r.id)} />)}
402 </Box>
403 )
404 : null}
405 </Box>
406 ))
407 : null}
408 </Box>
409 )
410}
411
412function HistoryRow(c: Ctx, n: AgentNode, history: AgentNode[]) {
413 const { Box, Text, Button } = c.els
414 const { t } = c
415 const files = fileRows(scopeNodes(history, { kind: 'node', id: n.id }))
416 const ch = changeTotals(files)
417 const tok = runTokens(history, n)
418 const outcome = outcomeOf(n) || noReportReason(n)
419 return (
420 <Box key={`hr-${n.id}`} flexDirection="row" gap={1} alignItems="center">
421 {StatusMark(c.els, t, n.status)}
422 <Box width={2}>{KindMark(c.els, t, n.kind, 14)}</Box>
423 <Box width={c.wide ? 34 : 24}><Button key={`run:${n.id}`} plain label={clip(n.label, c.wide ? 34 : 24)} onPress={() => openRun(c, n.id)} /></Box>
424 <Box flexGrow={1}><Text color={t.muted} wrap="truncate-end">{outcome}</Text></Box>
425 {c.wide ? <Box width={14}><Text color={files.length ? t.add : t.muted}>{files.length ? `+${num(ch.added)} −${num(ch.removed)}` : '—'}</Text></Box> : null}
426 <Box width={8}><Text color={t.muted}>{duration((n.endedAt ?? c.now) - n.startedAt)}</Text></Box>
427 {c.wide ? <Box width={7}><Text color={t.muted}>{tok ? kTokens(tok) : ''}</Text></Box> : null}
428 </Box>
429 )
430}
431
432// ── a run: the chosen lens beside (or above) the detail of what is picked ────
433function RunView(c: Ctx, run: AgentNode) {
434 const { Box } = c.els
435 const { ui } = c
436 const nodes = c.all
437 const target = targetOf(ui.sel, nodes) ?? { kind: 'node' as const, node: run }
438 // Only the tree sits beside the detail, and only when both get room. The pictures
439 // (timeline, trace, board) need the full width, so they always sit above it.
440 const side = c.wide && ui.lens === 'tree'
441 const treeCols = Math.max(52, Math.round(c.columns * 0.4))
442 const full = c.columns - 4
443 const lens = ui.lens === 'board'
444 ? Board(c, boardLanes(run, nodes, [], 'all'), run, full)
445 : ui.lens === 'timeline'
446 ? Timeline(c, run, [], full)
447 : ui.lens === 'trace'
448 ? Trace(c, run, full)
449 : Tree(c, run)
450 const detail = Detail(c, run, target)
451 // a run that is one agent has a one-row tree that only repeats the card's title
452 const lone = ui.lens === 'tree' && run.kind === 'agent' && !childrenOf(nodes, run.id).length
453 if (lone) return detail
454 return side
455 ? (
456 <Box flexDirection="row" gap={2}>
457 <Box flexDirection="column" width={treeCols} flexShrink={0} overflow="hidden">{lens}</Box>
458 <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={40}>{detail}</Box>
459 </Box>
460 )
461 : <Box flexDirection="column" gap={2}>{lens}{detail}</Box>
462}
463
464type Target = { kind: 'node'; node: AgentNode } | { kind: 'phase'; wf: AgentNode; phase: string }
465
466function targetOf(sel: string | null, nodes: AgentNode[]): Target | undefined {
467 if (!sel) return undefined
468 if (sel.startsWith('phase:')) {
469 const [, wfId, ...rest] = sel.split(':')
470 const wf = nodes.find(n => n.id === wfId)
471 return wf ? { kind: 'phase', wf, phase: rest.join(':') } : undefined
472 }
473 const node = nodes.find(n => n.id === sel)
474 return node ? { kind: 'node', node } : undefined
475}
476
477const toggle = (list: string[], key: string) => (list.includes(key) ? list.filter(k => k !== key) : [...list, key])
478
479// ── Tree: workflow → phase → agent, cluster → members, subagents under parents ─
480function Tree(c: Ctx, run: AgentNode) {
481 const { Box, Text, Button, Svg } = c.els
482 const { t, ui } = c
483 const items = runTree(run, c.all, 'all', ui.flipped, ui.flipped)
484 // the picked row gets a clear tinted ground, and every row lights under the pointer,
485 // so rows read as pressable; its label never has to share space with a marker
486 const pickedBg = tint(t.accent, '40')
487 const hoverBg = { backgroundColor: tint(t.accent, '14') }
488 const byId = new Map(c.all.map(x => [x.id, x]))
489 // a sub-agent (spawned by an agent, not by the run) draws dim, one step down
490 const isSub = (n: AgentNode) => n.kind === 'agent' && !!n.parentId && byId.get(n.parentId)?.kind === 'agent' && n.parentId !== run.id
491 const INDENT = 3
492 // the right-hand facts sit in one block that never shrinks, so they line up and never spill
493 const facts = (parts: unknown[]) => <Box flexShrink={0} flexDirection="row" gap={1} alignItems="center">{parts}</Box>
494 const label = (key: string, text: string, onPress: () => void, dim = false) => (
495 <Box flexGrow={1} flexShrink={1} minWidth={10} overflow="hidden"><Button key={key} plain {...(dim ? { dimColor: true } : {})} label={text} onPress={onPress} /></Box>
496 )
497 const fold = (key: string, isOpen: boolean) => (
498 <Box width={2} flexShrink={0}><Button key={`fold:${key}`} plain label={isOpen ? '▾' : '▸'} onPress={() => c.acts.set({ flipped: toggle(ui.flipped, key) })} /></Box>
499 )
500 const noFold = <Box width={2} flexShrink={0} />
501 return (
502 <Box flexDirection="column" gap={0}>
503 {items.map((it, i) => {
504 if (it.kind === 'node') {
505 const n = it.node
506 const isSel = (ui.sel ?? run.id) === n.id
507 const files = n.kind === 'agent' ? fileRows([n]) : []
508 const ch = changeTotals(files)
509 const kids = n.kind === 'agent' ? [] : scopeNodes(c.all, { kind: 'node', id: n.id }).filter(k => k.kind === 'agent')
510 const r = rollup(kids)
511 return (
512 <Box key={`tn-${n.id}`} flexDirection="row" gap={1} alignItems="center" paddingLeft={it.depth * INDENT} {...(n.id === run.id ? { paddingBottom: 1 } : {})} hover={hoverBg} {...(isSel ? { backgroundColor: pickedBg } : {})}>
513 {it.fold ? fold(it.fold.key, it.fold.isOpen) : noFold}
514 {StatusMark(c.els, t, n.status, 16, isQuiet(n, c.now))}
515 {KindMark(c.els, t, n.kind)}
516 {n.id === run.id
517 // the run itself: bold, the top of the hierarchy (pressing the crumb or Esc returns to it)
518 ? <Box key={`rlabel:${n.id}`} flexGrow={1} flexShrink={1} minWidth={10} overflow="hidden"><Text bold wrap="truncate-end">{n.label}</Text></Box>
519 : label(`sel:${n.id}`, n.label, () => c.acts.set({ sel: n.id, file: null }), isSub(n))}
520 {facts([
521 kids.length ? <Svg key="bar" source={statusBarSvg(t, r, 48, 5)} alt={`${r.finished} of ${r.total}`} width={48} height={5} /> : null,
522 kids.length ? <Text key="n" color={t.muted}>{r.finished}/{r.total}</Text> : null,
523 files.length ? <Text key="d" color={t.add}>+{ch.added} <Text color={t.del}>−{ch.removed}</Text></Text> : null,
524 <Box key="ms" width={8} justifyContent="flex-end"><Text color={t.muted}>{duration((n.endedAt ?? c.now) - n.startedAt)}</Text></Box>,
525 ])}
526 </Box>
527 )
528 }
529 if (it.kind === 'phase') {
530 const key = `phase:${it.wfId}:${it.phase}`
531 const isSel = ui.sel === key
532 return (
533 <Box key={`tp-${it.key}`} flexDirection="row" gap={1} alignItems="center" paddingLeft={INDENT} {...(isSel ? { backgroundColor: pickedBg } : {})}>
534 {fold(it.key, it.isOpen)}
535 {label(`sel:${key}`, `${it.phase} phase`, () => c.acts.set({ sel: key, file: null }))}
536 {facts([
537 <Svg key="bar" source={statusBarSvg(t, it, 48, 5)} alt={`${it.done} of ${it.total}`} width={48} height={5} />,
538 <Box key="n" width={8} justifyContent="flex-end"><Text color={t.muted}>{it.total - it.running}/{it.total}</Text></Box>,
539 ])}
540 </Box>
541 )
542 }
543 if (it.kind === 'more') {
544 return <Box key={`tm-${i}`} paddingLeft={INDENT * 2 + 3}><Button key={`more:${it.key}`} plain label={`Show ${it.count} more finished`} onPress={() => c.acts.set({ flipped: toggle(ui.flipped, it.key) })} /></Box>
545 }
546 if (it.kind === 'info' && it.tone === 'warn') {
547 const o = overlaps(scopeNodes(c.all, { kind: 'node', id: it.nodeId }).filter(k => k.id !== it.nodeId))[0]
548 return o ? <Box key={`tw-${i}`} paddingLeft={INDENT * 2 + 3}><Text color={t.warn}>⚠ {o.by.length} members edited {o.path.split('/').pop()}</Text></Box> : null
549 }
550 if (it.kind === 'info' && it.tone === 'outcome') {
551 const n = c.all.find(x => x.id === it.nodeId)
552 // the outcome sits under the row it belongs to, indented past the marks
553 return n ? <Box key={`to-${i}`} paddingLeft={INDENT + 7} paddingBottom={1}><Text color={t.muted}>{clip(reportOf(n)?.result ?? '', 160)}</Text></Box> : null
554 }
555 return null
556 })}
557 </Box>
558 )
559}
560
561const isQuiet = (n: AgentNode, now: number) => n.status === 'running' && now - (n.lastToolAt ?? n.startedAt) >= 120_000
562
563// ── Board: one card per lane, its agents by status, full names and outcomes ────
564// Three fixed status columns squeezed every name into a third of the width, and
565// most of them stood empty. Now status is the order and the mark: running first,
566// then failed or stopped, then done.
567const BOARD_ORDER: Record<AgentNode['status'], number> = { running: 0, failed: 1, killed: 2, done: 3 }
568const BOARD_CAP = 12
569
570function Board(c: Ctx, lanes: Lane[], run: AgentNode | undefined, cols = c.columns - 4) {
571 const { Box, Text, Button } = c.els
572 const { t, ui } = c
573 if (!lanes.length) return Empty(c.els, t, 'Nothing to put on the board.', 'Agents show up here as cards, by status.')
574 const pick = (k: AgentNode) => {
575 if (run) return c.acts.set({ sel: k.id, file: null })
576 const byId = new Map(c.all.map(n => [n.id, n]))
577 let top: AgentNode | undefined = k
578 while (top?.parentId && byId.has(top.parentId)) top = byId.get(top.parentId)
579 if (top) c.acts.set({ run: top.id, sel: k.id, file: null })
580 }
581 const summary = (cards: AgentNode[]) => {
582 const cn = counts(cards)
583 return [cn.running ? `${cn.running} running` : '', cn.failed + cn.stopped ? `${cn.failed + cn.stopped} failed or stopped` : '', cn.done ? `${cn.done} done` : ''].filter(Boolean).join(' · ')
584 }
585 // agents as tiles, tinted by status: two to a row when each still gets 48 columns
586 const tileW = cols >= 100 ? Math.floor((cols - 1) / 2) : undefined
587 return (
588 <Box flexDirection="column" gap={1}>
589 {!run ? <Text color={t.muted}>Each section is one run. Press an agent to open its run.</Text> : null}
590 {lanes.map(l => {
591 const cards = [...l.cards].sort((a, b) => BOARD_ORDER[a.status] - BOARD_ORDER[b.status] || a.startedAt - b.startedAt)
592 const bad = cards.some(k => k.status === 'failed' || k.status === 'killed')
593 return (
594 <Box key={`lane-${l.key}`} flexDirection="column" gap={1}>
595 <Box flexDirection="column">
596 {Heading(c.els, l.title, `h-lane-${l.key}`)}
597 <Text color={bad ? t.bad : t.muted}>{summary(cards)}</Text>
598 </Box>
599 <Box flexDirection="row" flexWrap="wrap" gap={1}>
600 {cards.slice(0, BOARD_CAP).map(k => {
601 const outcome = k.status === 'running' ? (k.activity ?? '') : (reportOf(k)?.result ?? '')
602 const isSel = ui.sel === k.id
603 return (
604 <Box key={`card-${k.id}`} flexDirection="column" backgroundColor={tint(isSel ? t.accent : statusColor(t, k.status), isSel ? '33' : '1a')} paddingX={1}
605 {...(tileW ? { width: tileW } : { flexGrow: 1 })}>
606 <Box flexDirection="row" gap={1} alignItems="center">
607 {StatusMark(c.els, t, k.status, 14, isQuiet(k, c.now))}
608 <Box flexGrow={1} flexShrink={1} minWidth={10} overflow="hidden"><Button key={`bsel:${k.id}`} plain label={k.label} onPress={() => pick(k)} /></Box>
609 <Box flexShrink={0}><Text color={t.muted}>{duration((k.endedAt ?? c.now) - k.startedAt)}</Text></Box>
610 </Box>
611 {outcome ? <Box paddingLeft={3}><Text color={t.muted}>{clip(outcome, 120)}</Text></Box> : null}
612 </Box>
613 )
614 })}
615 </Box>
616 {cards.length > BOARD_CAP ? <Text color={t.muted}>and {cards.length - BOARD_CAP} more</Text> : null}
617 </Box>
618 )
619 })}
620 </Box>
621 )
622}
623
624// ── Timeline: bars on a shared ruler ──────────────────────────────────────────
625function Timeline(c: Ctx, run: AgentNode | undefined, tops: AgentNode[], cols = c.columns - 4) {
626 const { Box, Text, Button, Svg } = c.els
627 const { t, ui } = c
628 // on the run list, each run opens into its agents (newest 8 runs), so the bars are not 4 thin lines
629 const list = run ? undefined : listTimelineRows(c.all, tops)
630 // inside a run, sub-agents sit under the agent that spawned them, and fold
631 const rows = run ? timelineRows(run, c.all, tops, 'all', ui.flipped) : list!.rows
632 // inside a run: the chain that set its end time, outlined, and the idle time, shaded
633 const agents = rows.flatMap(r => (r.kind === 'bar' ? [r.node] : []))
634 const path = run ? criticalPath(agents, c.now) : undefined
635 const idle = run ? idleGaps(agents, c.now) : { gaps: [], ms: 0 }
636 const onPath = new Set(path?.ids ?? [])
637 if (!agents.length) return Empty(c.els, t, 'No timeline yet.', 'Bars appear as agents start and finish.')
638 const from = Math.min(...agents.map(n => n.startedAt))
639 const to = Math.max(...agents.map(n => n.endedAt ?? c.now))
640 // labels are native text in their own column (they follow the theme and can be
641 // pressed); each bar is a strip picture as wide as the rest of the pane
642 const LABEL = Math.max(18, Math.min(44, Math.round(cols * 0.32)))
643 const w = Math.max(200, Math.round((cols - LABEL - 2) * CELL_PX))
644 const pick = (n: AgentNode) => {
645 if (run) return c.acts.set({ sel: n.id, file: null })
646 const byId = new Map(c.all.map(x => [x.id, x]))
647 let top: AgentNode | undefined = n
648 while (top?.parentId && byId.has(top.parentId)) top = byId.get(top.parentId)
649 if (top) c.acts.set({ run: top.id, sel: n.id, file: null })
650 }
651 // one quiet line of facts: how long it took and where the time went (no card, no tiles)
652 const span = to - from
653 const cn = counts(agents)
654 const failed = cn.failed + cn.stopped
655 const facts: Fact[] = run
656 ? [
657 { text: `took ${duration(span)}` },
658 ...(path && path.ids.length ? [{ text: `critical path ${duration(path.ms)} · ${path.ids.length} agent${path.ids.length === 1 ? '' : 's'}`, color: t.accent }] : []),
659 ...(idle.ms ? [{ text: `idle ${duration(idle.ms)}`, ...(idle.ms >= span * 0.2 ? { color: t.warn } : {}) }] : []),
660 { text: `${agents.length} agents` },
661 ]
662 : [
663 { text: `${list!.runs} run${list!.runs === 1 ? '' : 's'}${list!.hidden ? ` (${list!.hidden} older hidden)` : ''}` },
664 { text: `${agents.length} agents over ${duration(span)}` },
665 ...(failed ? [{ text: `${STATUS_GLYPH.failed} ${failed} failed or stopped`, color: t.bad }] : []),
666 ]
667 const key = [run && path ? 'Outlined bars: critical path' : '', run && idle.ms ? 'shaded: idle' : '', 'press a name to open it'].filter(Boolean).join(' · ')
668 return (
669 <Box flexDirection="column" gap={1}>
670 <Box key="facts-timeline"><Text color={t.muted}>{facts.map((f, i) => <Text key={`tf-${i}`} {...(f.color ? { color: f.color } : {})}>{i ? ' · ' : ''}{f.text}</Text>)}</Text></Box>
671 <Box flexDirection="row" columnGap={2} alignItems="center" flexWrap="wrap">
672 <Box flexGrow={1} flexShrink={1}><Text color={t.muted}>{key.replace(/^./, ch => ch.toUpperCase())}.</Text></Box>
673 {run ? <Button key="save-timeline" plain label="Save picture" hotkey="x" onPress={() => c.acts.exportPic(run.id, 'timeline', ui.zoom)} /> : null}
674 </Box>
675 <Box flexDirection="column" gap={0}>
676 <Box flexDirection="row" gap={1}>
677 <Box width={LABEL} flexShrink={0} />
678 <Svg source={rulerSvg(t, from, to, w)} alt={`Timeline of ${agents.length} agents over ${duration(to - from)}`} width={w} height={20} />
679 </Box>
680 {rows.map((r, i) => {
681 if (r.kind === 'label') {
682 // a run or phase starts a section, as in the report
683 return <Box key={`tlh-${i}`} paddingTop={i ? 1 : 0}>{Heading(c.els, r.text, `h-tl-${i}`)}</Box>
684 }
685 const n = r.node
686 const isSel = ui.sel === n.id
687 const bar: TimeBar = { label: n.label, start: n.startedAt, end: n.endedAt ?? c.now, status: n.status, isCritical: onPath.has(n.id) }
688 const depth = r.depth ?? 0
689 // a bar with sub-agents under it (shown, or folded away) gets a fold control
690 const next = rows[i + 1]
691 const hasKids = !!r.hidden || (next?.kind === 'bar' && (next.depth ?? 0) > depth)
692 const foldKey = `tl:${n.id}`
693 return (
694 <Box key={`tl-${n.id}`} flexDirection="row" gap={1} alignItems="center" hover={{ backgroundColor: tint(t.accent, '14') }} {...(isSel ? { backgroundColor: tint(t.accent, '40') } : {})}>
695 <Box width={LABEL} flexShrink={0} overflow="hidden" paddingLeft={1 + depth * 2} flexDirection="row">
696 {run
697 ? <Box width={2} flexShrink={0}>{hasKids ? <Button key={`fold:${foldKey}`} plain label={ui.flipped.includes(foldKey) ? '▸' : '▾'} onPress={() => c.acts.set({ flipped: toggle(ui.flipped, foldKey) })} /> : null}</Box>
698 : null}
699 <Box flexShrink={1} minWidth={0} overflow="hidden">
700 <Button key={`tsel:${n.id}`} plain {...(depth > 0 || (run && !onPath.has(n.id)) ? { dimColor: true } : {})} label={r.hidden ? `${n.label} +${r.hidden}` : n.label} onPress={() => pick(n)} />
701 </Box>
702 </Box>
703 <Svg source={stripSvg(t, bar, from, to, w, idle.gaps)} alt={`${n.label}: ${STATUS_WORD[n.status]}, ${duration(bar.end - bar.start)}`} width={w} height={STRIP_H} />
704 </Box>
705 )
706 })}
707 </Box>
708 </Box>
709 )
710}
711
712// ── Trace: lanes on a time axis, arrows for spawns, messages, hand-backs ──────
713function Trace(c: Ctx, run: AgentNode, cols: number) {
714 const { Box, Text, Button, Svg } = c.els
715 const { t, ui } = c
716 const tr = c.data.trace
717 const zoomBar = Segmented(c, 'zoom', ZOOMS.map(z => [z, ZOOM_NAMES[z]] as [TraceZoom, string]), ui.zoom, z => {
718 c.acts.set({ zoom: z, traceOffset: 0 })
719 c.acts.askTrace(run.id, z, 0)
720 })
721 if (!tr || tr.run !== run.id) {
722 return (
723 <Box flexDirection="column" gap={1}>
724 {zoomBar}
725 <Text color={t.muted}>Reading the transcripts…</Text>
726 <Button key="read-trace" plain label="Read the trail now" onPress={() => c.acts.askTrace(run.id, ui.zoom, 0)} />
727 </Box>
728 )
729 }
730 const lanes = tr.lanes.map(l => ({ label: l.label, chip: l.chip, status: l.status, ...(l.depth ? { depth: l.depth } : {}) }))
731 const timed = tr.rows.filter(r => r.at > 0)
732 const from = timed.length ? Math.min(...timed.map(r => r.at)) : c.now
733 const to = timed.length ? Math.max(...timed.map(r => r.end ?? r.at)) : c.now
734 const w = Math.max(320, Math.round(cols * CELL_PX))
735 const marks = tr.rows.map(r => ({ lane: r.lane, ...(r.to !== undefined ? { to: r.to } : {}), at: r.at || from, kind: r.kind, text: r.text }))
736 // the agent picked in the tree or the timeline: its lane stands out, the others fade
737 const focus = ui.sel ? tr.lanes.findIndex(l => l.id === ui.sel) : -1
738 const svgH = 24 + lanes.length * 40 + 8
739 return (
740 <Box flexDirection="column" gap={1}>
741 <Box flexDirection="row" gap={2} alignItems="center">
742 {zoomBar}
743 <Text color={t.muted}>{tr.lanes.length} lanes · {tr.total} events{tr.missing ? ` · ${tr.missing} transcript${tr.missing === 1 ? '' : 's'} no longer on disk` : ''}{tr.loading ? ' · reading…' : ''}</Text>
744 {ui.zoom === 'story' && tr.storyBy ? <Text color={t.accent}>Story · {tr.storyBy}</Text> : null}
745 <Button key="save-trace" plain label="Save picture" hotkey="x" onPress={() => c.acts.exportPic(run.id, 'trace', ui.zoom, ui.sel ?? undefined)} />
746 </Box>
747 <Svg source={traceSvg(t, lanes, marks, from, to, w, focus >= 0 ? focus : undefined)} alt={`Trace of ${tr.lanes.length} agents`} width={w} height={svgH} />
748 <Box flexDirection="column">
749 {tr.rows.map((r, i) => (
750 <Box key={`tr-${tr.offset + i}`} flexDirection="row" gap={1}>
751 <Box width={8}><Text color={t.muted}>{r.at ? clock(r.at) : ''}</Text></Box>
752 {Chip(c.els, t, tr.lanes[r.lane]?.chip ?? '··', t.lanes[r.lane % t.lanes.length])}
753 <Box flexGrow={1}><Text {...(r.kind === 'fail' ? { color: t.bad } : r.kind === 'quiet' ? { color: t.muted } : {})} wrap="truncate-end">{r.kind === 'spawn' ? '↳ ' : r.kind === 'handback' ? '↩ ' : r.kind === 'message' ? '✉ ' : ''}{r.text}</Text></Box>
754 {r.kind === 'edit' && r.path
755 ? <Button key={`trdiff:${tr.offset + i}`} plain label="diff" onPress={() => { c.acts.set({ view: 'changes', file: r.path! }); c.acts.openDiff(r.path!) }} />
756 : null}
757 </Box>
758 ))}
759 </Box>
760 {tr.total > tr.rows.length
761 ? (
762 <Box flexDirection="row" gap={2}>
763 {tr.offset > 0 ? <Button key="trace-prev" plain label="‹ Earlier" onPress={() => { const o = Math.max(0, tr.offset - tr.rows.length); c.acts.set({ traceOffset: o }); c.acts.askTrace(run.id, ui.zoom, o) }} /> : null}
764 <Text color={t.muted}>{tr.offset + 1}–{tr.offset + tr.rows.length} of {tr.total}</Text>
765 {tr.offset + tr.rows.length < tr.total ? <Button key="trace-next" plain label="Later ›" onPress={() => { const o = tr.offset + tr.rows.length; c.acts.set({ traceOffset: o }); c.acts.askTrace(run.id, ui.zoom, o) }} /> : null}
766 </Box>
767 )
768 : null}
769 </Box>
770 )
771}
772
773// ── the detail of what is picked: header, then Overview, Changes or Output ───
774function Detail(c: Ctx, run: AgentNode, target: Target) {
775 const { Box, Text, Svg, Markdown, Button } = c.els
776 const { t, ui } = c
777 const scope = target.kind === 'node'
778 ? scopeNodes(c.all, { kind: 'node', id: target.node.id })
779 : scopeNodes(c.all, { kind: 'phase', wfId: target.wf.id, phase: target.phase })
780 const files = fileRows(scope)
781 const names = shortPaths(files.map(f => f.path))
782 const head = target.kind === 'node' ? target.node : undefined
783 const title = head ? head.label : `${target.kind === 'phase' ? target.phase : ''} phase`
784 const status = head ? head.status : (() => {
785 const cn = counts(scope)
786 return cn.running ? 'running' as const : cn.failed ? 'failed' as const : cn.stopped ? 'killed' as const : 'done' as const
787 })()
788 const quiet = head ? isQuiet(head, c.now) : false
789 const big = t.art
790 ? status === 'running' && !quiet
791 ? <Svg source={spriteSvg(t.art, walkSlot(c.now), 48)} alt="Running" width={48} height={48} />
792 : <Svg source={spriteSvg(t.art, quiet ? 'quiet' : head?.kind === 'workflow' ? 'workflow' : head?.kind === 'group' ? 'group' : status === 'done' ? 'done' : status === 'failed' ? 'failed' : 'stopped', 48)} alt={STATUS_WORD[status]} width={48} height={48} />
793 : <Svg source={iconSvg(quiet ? 'quiet' : status, quiet ? t.warn : statusColor(t, status), 28)} alt={STATUS_WORD[status]} width={28} height={28} />
794 const meta = head
795 ? [prettyType(head, !!head.phase), prettyModel(head.model), duration((head.endedAt ?? c.now) - head.startedAt), clock(head.startedAt)].filter(Boolean).join(' · ')
796 : `${scope.length} agents`
797 const tabs = Segmented(c, 'view', [['overview', 'Overview', 'o'], ['changes', `Changes ${files.length}`, 'c'], ['output', 'Output', 'u']], ui.view, v => {
798 c.acts.set({ view: v, file: null })
799 if (ui.file) c.acts.openDiff(null)
800 })
801 // the parts of a run: a workflow's phases, or a cluster's members
802 const parts: Part[] = head?.kind === 'workflow'
803 ? pipeline(head, c.all).map(p => ({
804 id: `phase:${head.id}:${p.phase}`, label: p.phase,
805 status: p.running ? 'running' as const : p.failed ? 'failed' as const : p.stopped ? 'killed' as const : 'done' as const,
806 result: head.partReports?.[p.phase]?.result ?? `${p.total - p.running} of ${p.total} agents finished`,
807 meta: `${p.total} agent${p.total === 1 ? '' : 's'}`,
808 }))
809 : head?.kind === 'group'
810 ? childrenOf(c.all, head.id).map(k => ({ id: k.id, label: k.label, status: k.status, result: reportOf(k)?.result ?? noReportReason(k) }))
811 : []
812 let body
813 if (ui.view === 'changes') body = Changes(c, scope, files, names)
814 else if (ui.view === 'output') {
815 const md = target.kind === 'node'
816 ? outputMarkdown(target.node, childrenOf(c.all, target.node.id))
817 : [`### ${target.phase} phase`, target.wf.partReports?.[target.phase]?.result ?? '', ...scope.map(k => `- **${k.label}** — ${reportOf(k)?.result ?? noReportReason(k)}`)].filter(Boolean).join('\n\n')
818 const brief = target.kind === 'node' && target.node.id === run.id && (run.explain || c.data.explaining?.includes(run.id))
819 ? `${briefMarkdown(run.explain, !!c.data.explaining?.includes(run.id), c.now)}\n\n---\n\n`
820 : ''
821 body = <Markdown key="output" text={brief + md} />
822 } else if (head) {
823 const prs = Object.values(head.partReports ?? {}).filter(p => p.model)
824 const partsBy = prs.length ? aiLabel({ model: prs[0]!.model, tokens: prs.reduce((a, p) => a + (p.tokens ?? 0), 0), at: Math.max(...prs.map(p => p.at ?? 0)) || undefined }, c.now) : ''
825 const writing = !!c.data.explaining?.includes(head.id)
826 const showBrief = head.id === run.id && (head.explain || writing)
827 body = (
828 <Box flexDirection="column" gap={1}>
829 {showBrief ? BriefBlock(c.els, t, head.explain, writing, c.now) : null}
830 {ReportBlock(c.els, t, head, c.all, c.now, parts, id => c.acts.set({ sel: id, file: null }), partsBy)}
831 </Box>
832 )
833 } else {
834 const pr = target.kind === 'phase' ? target.wf.partReports?.[target.phase] : undefined
835 body = (
836 <Box flexDirection="column" gap={1}>
837 {pr?.problems?.length
838 ? (
839 <Box key="attention" flexDirection="column">
840 <Box flexDirection="row" gap={1} alignItems="center">
841 <Svg source={iconSvg('warn', t.bad, 16)} alt="Needs your attention" width={16} height={16} />
842 <Text color={t.bad} bold>Needs your attention ({pr.problems.length})</Text>
843 </Box>
844 <Markdown key="pproblems" text={pr.problems.map(p => `- ${mdText(p.text)}`).join('\n')} />
845 </Box>
846 )
847 : null}
848 {Heading(c.els, `Agents (${scope.length})`, 'h-agents')}
849 {scope.map(k => (
850 <Box key={`pa-${k.id}`} flexDirection="column">
851 <Box flexDirection="row" gap={1} alignItems="center">
852 {StatusMark(c.els, t, k.status, 14)}
853 <Box flexGrow={1} flexShrink={1} overflow="hidden"><Button key={`psel:${k.id}`} plain label={k.label} onPress={() => c.acts.set({ sel: k.id })} /></Box>
854 <Box flexShrink={0}><Text color={t.muted}>{duration((k.endedAt ?? c.now) - k.startedAt)}</Text></Box>
855 </Box>
856 <Box paddingLeft={3}><Text color={t.muted}>{clip(reportOf(k)?.result ?? noReportReason(k), 200)}</Text></Box>
857 </Box>
858 ))}
859 {pr?.model ? <Text color={t.muted}>Part report by {aiLabel(pr, c.now)}</Text> : null}
860 </Box>
861 )
862 }
863 // the card: status, verdict and numbers in one glance; every view below shares it
864 const factScope = target.kind === 'node' ? { kind: 'node' as const, id: target.node.id } : { kind: 'phase' as const, wfId: target.wf.id, phase: target.phase }
865 const facts = reportFacts(c.all, factScope, c.now)
866 // a live agent has no verdict yet: it shows what it is doing now instead
867 const live = !!head && head.status === 'running' && !reportOf(head)
868 const result = head
869 ? live ? undefined : reportOf(head)?.result ?? noReportReason(head)
870 : target.kind === 'phase' ? target.wf.partReports?.[target.phase]?.result ?? `${counts(scope).done} of ${scope.length} agents done.` : ''
871 const nowText = live && head
872 ? [head.activity ?? head.lastTool ?? 'Starting', `${head.tools} tool call${head.tools === 1 ? '' : 's'}`, head.lastToolAt ? `last ${duration(c.now - head.lastToolAt)} ago` : ''].filter(Boolean).join(' · ')
873 : undefined
874 const problems = head ? (reportOf(head)?.problems?.length ?? 0) : target.kind === 'phase' ? (target.wf.partReports?.[target.phase]?.problems?.length ?? 0) : 0
875 const color = quiet ? t.warn : statusColor(t, status)
876 return (
877 <Box flexDirection="column" gap={1}>
878 {PlainHeader(c.els, t, { id: 'detail', big, status, statusWord: quiet ? 'Quiet' : STATUS_WORD[status], color, title, meta, ...(result ? { result } : {}), ...(nowText ? { now: nowText } : {}), facts: factsOf(t, facts, problems) })}
879 {quiet && head ? <Text color={t.warn}>No tool call for {duration(c.now - (head.lastToolAt ?? head.startedAt))}. Last: {head.activity ?? head.lastTool ?? 'unknown'}.</Text> : null}
880 {tabs}
881 {body}
882 </Box>
883 )
884}
885
886function Changes(c: Ctx, scope: AgentNode[], files: ReturnType<typeof fileRows>, names: Map<string, string>) {
887 const { Box, Text, Button, Svg, Code } = c.els
888 const { t, ui } = c
889 if (!files.length) return <Text color={t.muted}>No files were changed here.</Text>
890 if (ui.file) {
891 const row = files.find(f => f.path === ui.file)
892 const ids = new Set(scope.map(n => n.id))
893 const edits: EditRecord[] = c.data.diff?.path === ui.file ? c.data.diff.edits.filter(r => ids.has(r.agentId)) : []
894 const byId = new Map(c.all.map(n => [n.id, n]))
895 return (
896 <Box flexDirection="column" gap={1}>
897 <Box flexDirection="row" gap={2} alignItems="center">
898 <Button key="files" plain label="‹ All files" onPress={() => { c.acts.set({ file: null }); c.acts.openDiff(null) }} />
899 <Text bold>{names.get(ui.file) ?? ui.file}</Text>
900 {row ? <Text color={t.add}>+{num(row.added)} <Text color={t.del}>−{num(row.removed)}</Text></Text> : null}
901 </Box>
902 {c.data.diff?.path !== ui.file
903 ? <Text color={t.muted}>Loading the diff…</Text>
904 : edits.length === 0
905 ? <Text color={t.muted}>No saved edits for this file in this scope.</Text>
906 : edits.map(rec => {
907 const lines = lineDiff(rec.old, rec.new, rec.line)
908 const hunks = unifiedHunks(lines)
909 const who = byId.get(rec.agentId)
910 const added = lines.filter(l => l.op === '+').length
911 const removed = lines.filter(l => l.op === '-').length
912 return (
913 <Box key={`edit-${rec.id}`} flexDirection="column">
914 <Box flexDirection="row" gap={1} alignItems="center">
915 {Chip(c.els, t, who ? clip(who.label, 30) : rec.agentId.slice(0, 8), t.accent)}
916 <Text color={t.muted}>line {rec.line} · {clock(rec.at)}</Text>
917 <Text color={t.add}>+{added} <Text color={t.del}>−{removed}</Text></Text>
918 </Box>
919 {hunks.map((hunk, i) => <Code key={`hunk-${rec.id}-${i}`} source={hunk} format="diff" path={rec.path} wrap="wrap" />)}
920 </Box>
921 )
922 })}
923 </Box>
924 )
925 }
926 const max = Math.max(1, ...files.map(f => f.added + f.removed))
927 return (
928 <Box flexDirection="column">
929 {files.map(f => (
930 <Box key={`file-${f.path}`} flexDirection="row" gap={1} alignItems="center">
931 <Svg source={iconSvg('file', t.muted, 14)} alt="File" width={14} height={14} />
932 <Box flexGrow={1}><Button key={`file:${f.path}`} plain label={clip(names.get(f.path) ?? f.path, 50)} onPress={() => { c.acts.set({ file: f.path }); c.acts.openDiff(f.path) }} /></Box>
933 <Svg source={diffBarSvg(t, f.added, f.removed, max)} alt={`+${f.added} −${f.removed}`} width={60} height={6} />
934 <Box width={14}><Text color={t.add}>+{num(f.added)} <Text color={t.del}>−{num(f.removed)}</Text></Text></Box>
935 <Text color={t.muted}>{clip(f.by.map(b => b.node.label).join(', '), 30)}</Text>
936 </Box>
937 ))}
938 </Box>
939 )
940}
941hooks/desktop/state.ts 36 lines1import type { DeskUi } from '../../types'
2
3// The desktop view's own state: which tab, run, item and view are open, and how the
4// lists are filtered. It lives in $.state (key "desk"), written by Button presses.
5export const DESK_DEFAULT: DeskUi = {
6 tab: 'live', run: null, sel: null, view: 'overview', lens: 'tree', onlyRepo: true, file: null,
7 query: '', hfilter: 'all', olderOpen: false, flipped: [], zoom: 'story', traceOffset: 0,
8 confirm: '', note: '', patternsOpen: true,
9}
10
11const oneOf = <T extends string>(x: unknown, all: readonly T[], d: T): T => (all.includes(x as T) ? (x as T) : d)
12const str = (x: unknown) => (typeof x === 'string' ? x : null)
13
14// State from an older shape, or none, read with every field checked and defaulted.
15export function deskUi(raw: unknown): DeskUi {
16 const s = (raw ?? {}) as Partial<Record<keyof DeskUi, unknown>>
17 return {
18 tab: oneOf(s.tab, ['live', 'history'] as const, 'live'),
19 run: str(s.run),
20 sel: str(s.sel),
21 view: oneOf(s.view, ['overview', 'changes', 'output'] as const, 'overview'),
22 lens: oneOf(s.lens, ['tree', 'board', 'timeline', 'trace'] as const, 'tree'),
23 onlyRepo: s.onlyRepo !== false,
24 file: str(s.file),
25 query: typeof s.query === 'string' ? s.query : '',
26 hfilter: oneOf(s.hfilter, ['all', 'failed', 'changed'] as const, 'all'),
27 olderOpen: s.olderOpen === true,
28 flipped: Array.isArray(s.flipped) ? s.flipped.filter((x): x is string => typeof x === 'string') : [],
29 zoom: oneOf(s.zoom, ['story', 'steps', 'raw'] as const, 'story'),
30 traceOffset: typeof s.traceOffset === 'number' && Number.isFinite(s.traceOffset) ? Math.max(0, Math.floor(s.traceOffset)) : 0,
31 confirm: oneOf(s.confirm, ['', 'explain', 'patterns'] as const, ''),
32 note: typeof s.note === 'string' ? s.note : '',
33 patternsOpen: s.patternsOpen !== false,
34 }
35}
36hooks/view.tsx 2059 lines1import type { ClientModule, ClientSurface, JsonValue } from 'claude-code'
2
3import type { Act, AgentNode, Brief, EditRecord, PatternsDoc, TraceRow, TraceView, TraceZoom, ViewProps, Wheel } from '../types'
4import {
5 COLUMNS, LENSES, LENS_NAMES, aspects, boardLanes, columnOf, criticalPath, idleGaps, insights, lensesFor, modelFamily, rowFlags, spendByModel,
6 timelineRows, tokensUnder, type Column, type Flag, type Insight, type Lane, type Lens, type TimeRow,
7} from './lens'
8import { compareRuns, previousOf, verdict, type Metric } from './compare'
9import {
10 GROUPS, GROUP_NAMES, childrenOf, counts, dayLabel, diffCounts, fileRows, firstSentence, isSelectable, lineDiff,
11 noReportReason, overlaps, phaseWords, pipeline, plain, prettyModel, prettyType, readableResult, reportHeading, runTree, scopeNodes, shortPaths,
12 taskText, topItems, whereLabel, workSummary, type DiffLine, type FileRow, type Filter, type Group, type Item,
13 folderKey, joinNodes, runKey,
14} from './list'
15import { cellWidth, fit, kindGlyph, padEnd, padStart, themeNameOf, themeOf, type Theme } from './theme'
16import {
17 HISTORY_FILTERS, HISTORY_FILTER_NAMES, historyItems, historyStats, outcomeOf, runTokens, sparkline, type HistoryFilter,
18} from './history'
19import { kTokens, reportFacts, reportOf, type Facts } from './report'
20import { ZOOMS, ZOOM_NAMES } from './trace'
21import { ago } from './ai'
22
23type Tab = 'live' | 'history'
24type ViewName = 'agents' | 'changes' | 'output'
25type State = {
26 tab: Tab
27 // the run opened (a workflow, a cluster or a top-level subagent), or null for the run list
28 path: string | null
29 view: ViewName
30 // how the agents are drawn: their tree, a board by status, or a timeline
31 lens: Lens
32 sel: number
33 first: number
34 // the agents view's selection, kept while Changes or Output show its scope
35 agentSel: number
36 // what that selection was (a node id, or phase:<workflow>:<phase>), so any lens finds it again
37 focus: string | null
38 // the file whose diff the Changes view shows, or null for its file list
39 diffFile: string | null
40 filter: Filter
41 group: Group
42 flipped: string[]
43 showDone: string[]
44 tick: number
45 // The engine time last handed in, and the tick it arrived on: now = that + ticks since.
46 atSeen: number
47 tickAtSeen: number
48 // History shows only this repository's runs
49 onlyRepo: boolean
50 // the key overlay
51 help: boolean
52 // the last wheel move applied; -1 until the first props arrive
53 wheelSeen: number
54 // the insight `i` last jumped to; -1 before the first
55 insight: number
56 // History: which runs the page keeps, the search words, whether typing goes to
57 // the search line, and whether runs older than a week show
58 hfilter: HistoryFilter
59 query: string
60 searching: boolean
61 olderOpen: boolean
62 // the trace: how close it reads, what was last asked of the hooks and when,
63 // and the row to come back to after a diff
64 zoom: TraceZoom
65 traceAsk: string
66 traceAskTick: number
67 traceAt: number
68 // a short line in the footer (how to turn AI on, "press e again"), and the tick it was set
69 note: string
70 noteTick: number
71 // a second press within a few ticks writes the brief or the patterns again
72 confirm: '' | 'explain' | 'patterns'
73 confirmTick: number
74 // History: whether the patterns across runs show
75 patternsOpen: boolean
76 // Where the keys go, as on a remote: the content, or one of the two bars above it
77 // (the caption's views and lenses, the Live and History tabs). Arrows switch tabs
78 // only in a bar; ↑ on the first row goes up to it, ↓ comes back. `barAt` is the
79 // item the bar's cursor is on.
80 zone: Zone
81 barAt: number
82 // the agent picked in another lens, whose lane the trace opens on and marks;
83 // `traceJump` until the trace has come and the jump is made
84 traceFocus: string | null
85 traceJump: boolean
86 // the trace cut to one lane (its agent id), and the words searched in it
87 traceLane: string | null
88 tquery: string
89 // a run marked to compare with the next one m is pressed on; two runs side by side
90 mark: string | null
91 compare: [string, string] | null
92 // the last picture note shown
93 exportSeen: number
94}
95type Zone = 'content' | 'caption' | 'tabs'
96
97const TICK_MS = 500
98// every key the pane takes, for ? help
99const KEYS_HELP: [string, string][] = [
100 ['j k ↑ ↓', 'move, or scroll the text'], ['↑ on the top row', 'up to the bar: views and lenses, then Live · History'],
101 ['in a bar ← →', 'switch; ↓ or enter goes back down to the list'], ['PgUp PgDn', 'a page at a time'], ['g G', 'first, last'], ['enter', 'open'],
102 ['space ← →', 'fold or unfold in the tree; ← goes up to the parent'], ['v', 'view: tree, board, timeline; in a run, trace'],
103 ['1 2 a c o', 'straight to live, history; agents, changes, output'], ['b ⌫', 'back'],
104 ['i', 'next thing that needs a look'], ['f', 'filter: all, running, failed · history: all, failed, changed files'], ['s', 'group the run list'],
105 ['/', 'search history: names and outcomes; in a trace, its rows; enter keeps, ctrl+u clears'], ['o', 'show or hide history older than a week'],
106 ['r', 'this repo · all repos (history)'],
107 ['m', 'mark a run; m on a second run compares the two'], ['=', 'compare a run with its last run of the same work'],
108 ['trace n p', 'next, previous failure or quiet gap; with a search, its matches'], ['trace f', 'only the lane of the row you are on; f again for all'],
109 ['z', 'trace: story, steps, raw'], ['n p', 'next, previous file in a diff'],
110 ['x', 'save the run\'s timeline or trace as a picture (SVG, and PNG with rsvg-convert)'],
111 ['e', 'explain this run: a brief from Sonnet (ai: full); twice to write it again'],
112 ['g', 'history: patterns across runs from Sonnet (ai: full); twice to look again'],
113 ['p', 'history: show or hide the patterns'],
114 ['wheel', 'move, or scroll'], ['?', 'close this help'],
115]
116// its rows: a blank row, then the list
117const KEYS_HELP_COUNT = KEYS_HELP.length + 1
118const MIN_COLUMNS = 60
119const CARDS_PER_CELL = 4
120const DEFAULT_STATE: State = {
121 tab: 'live', path: null, view: 'agents', lens: 'tree', sel: 0, first: 0, agentSel: 0, focus: null, diffFile: null,
122 filter: 'all', group: 'none', flipped: [], showDone: [], tick: 0, atSeen: 0, tickAtSeen: 0, onlyRepo: true, help: false,
123 wheelSeen: -1, insight: -1, hfilter: 'all', query: '', searching: false, olderOpen: false,
124 zoom: 'story', traceAsk: '', traceAskTick: -100, traceAt: 0,
125 note: '', noteTick: -100, confirm: '', confirmTick: -100, patternsOpen: true,
126 zone: 'content', barAt: 0, traceFocus: null, traceJump: false, traceLane: null, tquery: '', mark: null, compare: null, exportSeen: 0,
127}
128const FILTERS: Filter[] = ['all', 'running', 'failed']
129// a note shows for 8 ticks (4 s); a confirm waits 6 ticks (3 s) for the second press
130const NOTE_TICKS = 8
131const CONFIRM_TICKS = 6
132const PATTERNS_TITLE = 'Patterns across runs'
133const VIEWS: ViewName[] = ['agents', 'changes', 'output']
134
135const arrayOf = <T,>(x: unknown): T[] => (Array.isArray(x) ? (x as T[]) : [])
136
137// Props and local state come from outside this module (the hooks, a previous
138// version of this view), so each field is checked and defaulted, never assumed.
139export function viewProps(raw: unknown): ViewProps {
140 const p = (raw ?? {}) as Partial<ViewProps>
141 const diff = p.diff && typeof p.diff.path === 'string' ? { path: p.diff.path, edits: arrayOf<EditRecord>(p.diff.edits) } : undefined
142 const w = p.wheel as Partial<Wheel> | undefined
143 return {
144 nodes: arrayOf(p.nodes), history: arrayOf(p.history), at: typeof p.at === 'number' ? p.at : 0, diff,
145 ...(typeof p.repo === 'string' ? { repo: p.repo } : {}),
146 theme: themeNameOf(p.theme),
147 wheel: { seq: typeof w?.seq === 'number' ? w.seq : 0, by: typeof w?.by === 'number' ? w.by : 0 },
148 ...(traceOf(p.trace) ? { trace: traceOf(p.trace) } : {}),
149 ai: p.ai === 'off' || p.ai === 'full' ? p.ai : 'cheap',
150 aiWeek: typeof p.aiWeek === 'number' ? p.aiWeek : 0,
151 explaining: arrayOf<string>(p.explaining).filter(x => typeof x === 'string'),
152 patternsBusy: p.patternsBusy === true,
153 ...(patternsOf(p.patterns) ? { patterns: patternsOf(p.patterns) } : {}),
154 ...(p.exported && typeof p.exported.seq === 'number' && typeof p.exported.text === 'string' ? { exported: { seq: p.exported.seq, text: p.exported.text } } : {}),
155 }
156}
157
158// Patterns from the hooks, when they have the shape the view draws.
159const patternsOf = (d: unknown): PatternsDoc | undefined => {
160 const x = d as Partial<PatternsDoc> | undefined
161 if (!x || !Array.isArray(x.cards) || typeof x.at !== 'number') return undefined
162 const cards = x.cards.filter(c => c && typeof c.title === 'string').map(c => ({ ...c, runs: arrayOf<{ id: string; label: string }>(c.runs) }))
163 return { cards, model: typeof x.model === 'string' ? x.model : 'Sonnet', at: x.at, ...(typeof x.tokens === 'number' ? { tokens: x.tokens } : {}) }
164}
165
166// A trace from the hooks, when it has the shape the view draws.
167const traceOf = (t: unknown): TraceView | undefined => {
168 const x = t as Partial<TraceView> | undefined
169 if (!x || typeof x.run !== 'string' || !Array.isArray(x.rows) || !Array.isArray(x.lanes)) return undefined
170 return { run: x.run, zoom: ZOOMS.includes(x.zoom as TraceZoom) ? (x.zoom as TraceZoom) : 'story', lanes: x.lanes, rows: x.rows as TraceRow[],
171 total: typeof x.total === 'number' ? x.total : x.rows.length, offset: typeof x.offset === 'number' ? x.offset : 0, missing: typeof x.missing === 'number' ? x.missing : 0,
172 ...(typeof x.storyBy === 'string' ? { storyBy: x.storyBy } : {}),
173 ...(typeof x.lane === 'string' ? { lane: x.lane } : {}),
174 marks: arrayOf<number>(x.marks).filter(n => typeof n === 'number'),
175 ...(typeof x.query === 'string' ? { query: x.query, hits: arrayOf<number>(x.hits).filter(n => typeof n === 'number') } : {}) }
176}
177
178export function viewState(raw: unknown): State {
179 const s = { ...DEFAULT_STATE, ...((raw ?? {}) as Partial<State>) }
180 const num = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) ? x : 0)
181 return {
182 ...s,
183 tab: s.tab === 'history' ? 'history' : 'live',
184 path: typeof s.path === 'string' ? s.path : null,
185 view: VIEWS.includes(s.view) ? s.view : 'agents',
186 lens: LENSES.includes(s.lens) ? s.lens : 'tree',
187 focus: typeof s.focus === 'string' ? s.focus : null,
188 diffFile: typeof s.diffFile === 'string' ? s.diffFile : null,
189 filter: FILTERS.includes(s.filter) ? s.filter : 'all',
190 group: GROUPS.includes(s.group) ? s.group : 'none',
191 flipped: arrayOf(s.flipped),
192 showDone: arrayOf(s.showDone),
193 sel: num(s.sel),
194 first: num(s.first),
195 agentSel: num(s.agentSel),
196 tick: num(s.tick),
197 onlyRepo: s.onlyRepo !== false,
198 help: s.help === true,
199 wheelSeen: typeof s.wheelSeen === 'number' ? s.wheelSeen : -1,
200 insight: typeof s.insight === 'number' ? s.insight : -1,
201 hfilter: HISTORY_FILTERS.includes(s.hfilter) ? s.hfilter : 'all',
202 query: typeof s.query === 'string' ? s.query : '',
203 searching: s.searching === true,
204 olderOpen: s.olderOpen === true,
205 zoom: ZOOMS.includes(s.zoom) ? s.zoom : 'story',
206 traceAsk: typeof s.traceAsk === 'string' ? s.traceAsk : '',
207 traceAskTick: typeof s.traceAskTick === 'number' ? s.traceAskTick : -100,
208 traceAt: num(s.traceAt),
209 note: typeof s.note === 'string' ? s.note : '',
210 noteTick: typeof s.noteTick === 'number' ? s.noteTick : -100,
211 confirm: s.confirm === 'explain' || s.confirm === 'patterns' ? s.confirm : '',
212 confirmTick: typeof s.confirmTick === 'number' ? s.confirmTick : -100,
213 patternsOpen: s.patternsOpen !== false,
214 zone: s.zone === 'caption' || s.zone === 'tabs' ? s.zone : 'content',
215 barAt: num(s.barAt),
216 traceFocus: typeof s.traceFocus === 'string' ? s.traceFocus : null,
217 traceJump: s.traceJump === true,
218 traceLane: typeof s.traceLane === 'string' ? s.traceLane : null,
219 tquery: typeof s.tquery === 'string' ? s.tquery : '',
220 mark: typeof s.mark === 'string' ? s.mark : null,
221 compare: Array.isArray(s.compare) && s.compare.length === 2 && s.compare.every(x => typeof x === 'string') ? [s.compare[0]!, s.compare[1]!] : null,
222 exportSeen: num(s.exportSeen),
223 }
224}
225
226const duration = (ms: number) => {
227 const s = Math.max(0, Math.floor(ms / 1000))
228 if (s < 60) return `${s}s`
229 const m = Math.floor(s / 60)
230 return m < 60 ? `${m}m ${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
231}
232// a ruler's relative time: 0:30, 4:00, 1:05:00
233const offset = (ms: number) => {
234 const s = Math.max(0, Math.round(ms / 1000))
235 const h = Math.floor(s / 3600)
236 const m = Math.floor((s % 3600) / 60)
237 return h ? `${h}:${String(m).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}` : `${m}:${String(s % 60).padStart(2, '0')}`
238}
239const clock = (t: number) => new Date(t).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
240const clockSec = (t: number) => new Date(t).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', second: '2-digit' })
241const baseName = (p: string) => p.split('/').filter(Boolean).pop() ?? p
242// 3,520 rather than 3520: counts read faster with separators
243const num = (n: number) => n.toLocaleString('en-US')
244
245// The status line's bar: ▰ filled, ▱ empty, rounded to the nearest cell.
246export function bar(done: number, total: number, width: number): { filled: string; empty: string; pct: number } {
247 const pct = total > 0 ? Math.round((done / total) * 100) : 0
248 const full = Math.min(width, Math.round((pct * width) / 100))
249 return { filled: '▰'.repeat(full), empty: '▱'.repeat(Math.max(0, width - full)), pct }
250}
251
252// A roll-up bar split by status, in cells: done, failed or stopped, then running.
253export function statusCells(c: { done: number; failed: number; stopped: number; running: number; total: number }, width: number) {
254 if (c.total === 0) return { done: 0, bad: 0, running: width }
255 const done = Math.round((c.done / c.total) * width)
256 const bad = Math.min(width - done, Math.max(c.failed + c.stopped > 0 ? 1 : 0, Math.round(((c.failed + c.stopped) / c.total) * width)))
257 return { done, bad, running: width - done - bad }
258}
259
260// Word wrap to a width in cells, so text scrolls and clips by whole lines.
261export function wrap(text: string, width: number): string[] {
262 const out: string[] = []
263 for (const para of text.split('\n')) {
264 if (!para.trim()) { out.push(''); continue }
265 let line = ''
266 for (const word of para.split(/\s+/)) {
267 if (!word) continue
268 if ((line ? cellWidth(line) + 1 : 0) + cellWidth(word) > width && line) { out.push(line); line = '' }
269 line = line ? `${line} ${word}` : cellWidth(word) > width ? fit(word, width) : word
270 }
271 if (line) out.push(line)
272 }
273 return out
274}
275
276export function step(n: number, from: number, dir: 1 | -1, ok: (i: number) => boolean): number {
277 for (let i = from + dir; i >= 0 && i < n; i += dir) if (ok(i)) return i
278 return from
279}
280
281// ── unified diff hunks for the engine's own diff drawing ──────────────────
282const CODE_LIMIT = 9000
283// One edit as unified-diff hunks, split so each stays under the Code element's size limit.
284export function unifiedHunks(lines: DiffLine[]): string[] {
285 const out: string[] = []
286 let chunk: DiffLine[] = []
287 let size = 0
288 const flush = () => {
289 if (chunk.length === 0) return
290 const oldNos = chunk.filter(l => l.op !== '+').map(l => l.oldNo ?? 0)
291 const newNos = chunk.filter(l => l.op !== '-').map(l => l.newNo ?? 0)
292 const firstOld = oldNos[0] ?? Math.max(0, (chunk[0]!.newNo ?? 1) - 1)
293 const firstNew = newNos[0] ?? Math.max(0, (chunk[0]!.oldNo ?? 1) - 1)
294 const head = `@@ -${firstOld},${oldNos.length} +${firstNew},${newNos.length} @@`
295 out.push([head, ...chunk.map(l => `${l.op === ' ' ? ' ' : l.op}${l.text}`)].join('\n'))
296 chunk = []
297 size = 0
298 }
299 for (const l of lines) {
300 const len = l.text.length + 2
301 if (size + len > CODE_LIMIT) flush()
302 chunk.push({ ...l, text: l.text.length > CODE_LIMIT - 100 ? l.text.slice(0, CODE_LIMIT - 100) : l.text })
303 size += len
304 }
305 flush()
306 return out
307}
308
309type Scope = { kind: 'node'; id: string } | { kind: 'phase'; wfId: string; phase: string }
310type FileItem = { row: FileRow }
311type DiffBlock = { rec: EditRecord; hunks: string[]; added: number; removed: number }
312
313// A row is a run of coloured pieces, laid out to an exact width in cells.
314type Seg = { t: string; c?: string; b?: boolean; bg?: string }
315type Row = { segs: Seg[]; bg?: string; hit?: Hit[] }
316type Hit = { x0: number; x1: number; act: () => void }
317const seg = (t: string, c?: string, b?: boolean): Seg => ({ t, c, b })
318const width = (segs: Seg[]) => segs.reduce((w, s) => w + cellWidth(s.t), 0)
319
320// Cuts pieces to a width (… on the last one kept), then pads with one piece of spaces.
321function lay(segs: Seg[], w: number): Seg[] {
322 const out: Seg[] = []
323 let used = 0
324 for (const s of segs) {
325 const cw = cellWidth(s.t)
326 if (used + cw <= w) { out.push(s); used += cw; continue }
327 const room = w - used
328 if (room > 0) { out.push({ ...s, t: fit(s.t, room) }); used += cellWidth(fit(s.t, room)) }
329 break
330 }
331 if (used < w) out.push({ t: ' '.repeat(w - used) })
332 return out
333}
334
335// What a selection is, as a key any lens can find again.
336const keyOf = (it: Item | undefined): string | null =>
337 it?.kind === 'node' ? it.node.id : it?.kind === 'phase' ? `phase:${JSON.stringify([it.wfId, it.phase])}` : null
338const scopeOfKey = (key: string | null, nodes: AgentNode[]): Scope | undefined => {
339 if (!key) return undefined
340 if (key.startsWith('phase:')) {
341 try {
342 const [wfId, phase] = JSON.parse(key.slice(6)) as [string, string]
343 return { kind: 'phase', wfId, phase }
344 } catch { return undefined }
345 }
346 return nodes.some(n => n.id === key) ? { kind: 'node', id: key } : undefined
347}
348
349const ACT_WORD: Record<Act, string> = { think: 'thinking', read: 'reading', write: 'writing', run: 'running', web: 'web' }
350const COLUMN_NAMES: Record<Column, [string, string]> = { running: ['RUNNING', 'RUNNING'], done: ['DONE', 'DONE'], failed: ['FAILED OR STOPPED', 'FAILED'] }
351
352let live: ClientSurface<State> | undefined
353
354const View: ClientModule<JsonValue, State> = (raw, surface) => {
355 const props = viewProps(raw)
356 const { Box, Text, Code } = surface.elements
357 const T: Theme = themeOf(props.theme)
358 const C = T.c
359 live = surface
360 const s: State = viewState(surface.state)
361 if (surface.state === undefined) {
362 surface.setState(s)
363 surface.every(TICK_MS, () => live?.state && live.setState({ ...live.state, tick: live.state.tick + 1 }))
364 }
365 if (surface.state !== undefined && s.atSeen !== props.at) surface.setState({ ...s, atSeen: props.at, tickAtSeen: s.tick })
366 const now = s.atSeen === props.at ? props.at + (s.tick - s.tickAtSeen) * TICK_MS : props.at
367 const pulse = s.tick % 2 === 0
368
369 // ── geometry, from the region as laid out now ─────────────────────────
370 const W = Math.max(20, surface.columns || 100)
371 const R = Math.max(8, surface.rows || 30)
372 const IW = W - 4 // inside the frame and its one-cell margins
373 const CH = R - 2 // rows between the top and bottom borders
374 const layout = W >= 140 ? 'split' : W >= 100 ? 'full' : 'compact'
375 const LW = layout === 'split' ? Math.floor(IW * 0.45) : IW
376 const RW = layout === 'split' ? IW - LW - 3 : IW
377
378 // History filtered to this repository: a run belongs where its top node ran.
379 const repoHistory = (() => {
380 if (!s.onlyRepo || !props.repo) return props.history
381 const byId = new Map(props.history.map(n => [n.id, n]))
382 const top = (n: AgentNode) => { let x = n; while (x.parentId && byId.has(x.parentId)) x = byId.get(x.parentId)!; return x }
383 const here = folderKey(props.repo)
384 return props.history.filter(n => runKey(top(n)) === here)
385 })()
386 const noRepoRuns = props.history.filter(n => !n.parentId && !runKey(n)).length
387 const isHistory = s.tab === 'history'
388 const nodes = isHistory ? repoHistory : props.nodes
389 const allNodes = joinNodes(props.nodes, props.history)
390 const run = s.path ? nodes.find(n => n.id === s.path) : undefined
391 const isInWorkflow = (n: AgentNode) => !!n.parentId && nodes.some(p => p.id === n.parentId && p.kind === 'workflow')
392 // a trace needs a run open; on the run list the lens falls back to the tree
393 const lens: Lens = s.lens === 'trace' && !run ? 'tree' : s.lens
394 const offered = lensesFor(!!run)
395 const nextLensOf = (l: Lens) => offered[(offered.indexOf(l) + 1) % offered.length] ?? 'tree'
396
397 // ── AI-written blocks: who wrote them, what it cost, how old they are ───────
398 const aiLabel = (b: { model?: string; tokens?: number; at?: number } | undefined): string =>
399 !b?.model ? '' : [b.model, ...(b.tokens ? [`${kTokens(b.tokens)} tokens`] : []), ...(b.at ? [ago(now - b.at)] : [])].join(' · ')
400 const isFull = props.ai === 'full'
401 // Patterns across runs, above the day groups: a heading, then per card its title, evidence,
402 // what to try and the runs it rests on (those rows open the run). Width: the list's.
403 const historyRunCount = props.history.filter(n => !n.parentId).length
404 const patternItems = (): Item[] => {
405 if (s.query || s.hfilter !== 'all') return []
406 const doc = props.patterns
407 const busy = !!props.patternsBusy
408 if (!doc && !busy && (!isFull || historyRunCount < 2)) return []
409 const note = busy ? `writing… (Sonnet)` : doc ? `${aiLabel(doc)}${isFull ? ' · g g writes them again' : ''}` : 'g asks Sonnet to look for patterns'
410 const head: Item = { kind: 'header', text: PATTERNS_TITLE, note, ...(doc ? { isOpen: s.patternsOpen } : {}) }
411 if (!doc || !s.patternsOpen) return [head]
412 const w = Math.max(20, (layout === 'split' ? LW : IW) - 6)
413 const out: Item[] = [head]
414 for (const c of doc.cards) {
415 out.push({ kind: 'pattern', tone: 'title', text: c.title })
416 if (c.evidence) for (const t of wrap(c.evidence, w)) out.push({ kind: 'pattern', tone: 'evidence', text: t })
417 if (c.try) wrap(`Try: ${c.try}`, w).forEach(t => out.push({ kind: 'pattern', tone: 'try', text: t }))
418 for (const r of c.runs) {
419 const node = props.history.find(n => n.id === r.id)
420 if (node) out.push({ kind: 'node', node, species: 'cat', depth: 1, guide: 'pattern' })
421 }
422 }
423 return out
424 }
425
426 // ── the three lenses over the same runs ───────────────────────────────
427 // the History page lists runs by day, filtered and searched; inside a run, its tree
428 const listFor = (flipped: readonly string[], showDone: readonly string[], at: AgentNode | undefined): Item[] =>
429 at ? runTree(at, nodes, s.filter, flipped, showDone)
430 : isHistory ? [...patternItems(), ...historyItems(nodes, now, { filter: s.hfilter, query: s.query, olderOpen: s.olderOpen })]
431 : topItems(nodes, s.filter, isHistory, now, s.group, flipped, showDone)
432 const agentItems: Item[] = listFor(s.flipped, s.showDone, run)
433 // the runs the run list shows, in its order, for the board and the timeline
434 const topRuns = topItems(nodes, s.filter, isHistory, now, 'none').flatMap(it => (it.kind === 'node' ? [it.node] : []))
435 const lanes: Lane[] = boardLanes(run, nodes, topRuns, s.filter)
436 const laneCells = lanes.map(l => COLUMNS.map(col => l.cards.filter(n => columnOf(n) === col)))
437 // a board's cards in reading order: lane by lane, column by column, the first few of each cell
438 const boardCards = laneCells.flatMap(cells => cells.flatMap(list => list.slice(0, CARDS_PER_CELL)))
439 const timeRows: TimeRow[] = timelineRows(run, nodes, topRuns, s.filter)
440 const timeCards = timeRows.flatMap(r => (r.kind === 'bar' ? [r.node] : []))
441 const cards = lens === 'board' ? boardCards : lens === 'timeline' ? timeCards : []
442
443 // ── what the screen is about ─────────────────────────────────────────
444 const view: ViewName = run ? s.view : 'agents'
445 const inAgents = view === 'agents'
446 // two runs side by side, when both are still kept
447 const pair = s.compare ? s.compare.map(id => allNodes.find(n => n.id === id)) : []
448 const comparing = pair.length === 2 && pair.every(Boolean)
449 const mode: 'help' | 'compare' | 'agents' | 'board' | 'timeline' | 'trace' | 'files' | 'diff' | 'output' = s.help ? 'help'
450 : comparing ? 'compare'
451 : inAgents ? (lens === 'tree' ? 'agents' : lens)
452 : view === 'output' ? 'output' : s.diffFile !== null ? 'diff' : 'files'
453 const asked = Math.min(Math.max(0, inAgents ? s.sel : s.agentSel), Math.max(0, agentItems.length - 1))
454 const snap = [asked, ...agentItems.map((_, i) => i).filter(i => i > asked), ...agentItems.map((_, i) => i).filter(i => i < asked).reverse()]
455 const agentSel = snap.find(i => isSelectable(agentItems[i])) ?? asked
456 const cardSel = Math.min(Math.max(0, s.sel), Math.max(0, cards.length - 1))
457 const focusItem = lens === 'tree' ? agentItems[agentSel] : undefined
458 const focusCard = lens !== 'tree' ? cards[cardSel] : undefined
459 // the key of what is selected in the agents view now
460 const focusKey = lens === 'tree' ? keyOf(focusItem) : focusCard?.id ?? null
461 const scope: Scope | undefined = inAgents
462 ? (scopeOfKey(focusKey, nodes) ?? (run ? { kind: 'node', id: run.id } : undefined))
463 : (scopeOfKey(s.focus, nodes) ?? (run ? { kind: 'node', id: run.id } : undefined))
464 const scopeList = scope ? scopeNodes(nodes, scope) : []
465 const scopeNode = scope?.kind === 'node' ? nodes.find(n => n.id === scope.id) : undefined
466 const files = fileRows(scopeList)
467 const names = shortPaths(files.map(f => f.path))
468 const scopeIds = new Set(scopeList.map(n => n.id))
469 const diffOpen = mode === 'diff'
470
471 const fileItems: FileItem[] = files.map(row => ({ row }))
472 const blocks: DiffBlock[] = (() => {
473 if (!diffOpen || props.diff?.path !== s.diffFile) return []
474 return props.diff.edits.filter(r => scopeIds.has(r.agentId)).map(rec => {
475 const lines = lineDiff(rec.old, rec.new, rec.line)
476 return { rec, hunks: unifiedHunks(lines), ...diffCounts(lines) }
477 })
478 })()
479
480 // what needs a look: inside a run, everything under it; on the run list, what is live
481 const shownInsights: Insight[] = run ? insights(scopeNodes(nodes, { kind: 'node', id: run.id }), nodes, now)
482 : !isHistory ? insights(props.nodes, props.nodes, now) : []
483 // the same insights on the rows they are about, inside a run
484 const flags: Map<string, Flag> = run ? rowFlags(scopeNodes(nodes, { kind: 'node', id: run.id }), nodes, now) : new Map()
485 // where a run's time went, on its timeline: the chain that set its end, and the idle time
486 const crit = run && lens === 'timeline' ? criticalPath(timeCards, now) : undefined
487 const onPath = new Set(crit?.ids ?? [])
488 const idle = run && lens === 'timeline' ? idleGaps(timeCards, now) : { gaps: [], ms: 0 }
489
490 // ── pieces ───────────────────────────────────────────────────────────
491 const outcome = (n: AgentNode) => n.summary ?? (n.kind === 'workflow' ? firstSentence(readableResult(n.result)) : firstSentence(n.result))
492 const elapsed = (n: Pick<AgentNode, 'status' | 'startedAt' | 'endedAt'>) => (n.status === 'running' ? now : n.endedAt ?? now) - n.startedAt
493 const statusIcon = (n: Pick<AgentNode, 'status'>) => (n.status === 'running' && !pulse ? T.runningAlt : T.status[n.status].icon)
494 const statusSegs = (n: Pick<AgentNode, 'status' | 'startedAt' | 'endedAt'>, extra?: string): Seg[] => {
495 const st = T.status[n.status]
496 return [seg(statusIcon(n), st.color), seg(' '), seg(st.word, st.color, true),
497 seg(' '), seg(duration(elapsed(n)), C.muted), ...(extra ? [seg(' '), seg(extra, C.muted)] : [])]
498 }
499 // a roll-up bar split by status: done, failed or stopped, still running
500 const rollSegs = (c: ReturnType<typeof counts>, w: number): Seg[] => {
501 const cells = statusCells(c, w)
502 return [seg(T.bar.full.repeat(cells.done), C.ok), seg(T.bar.full.repeat(cells.bad), C.bad), seg(T.bar.empty.repeat(cells.running), C.warn)]
503 }
504 const changeSegs = (rows: FileRow[]): Seg[] => {
505 if (rows.length === 0) return [seg('None', C.muted)]
506 const added = rows.reduce((a, r) => a + r.added, 0)
507 const removed = rows.reduce((a, r) => a + r.removed, 0)
508 return [seg(`${rows.length} file${rows.length === 1 ? '' : 's'}`, C.accent), seg(' '), seg(`+${num(added)}`, C.add), seg(' '), seg(`−${num(removed)}`, C.del)]
509 }
510 // tokens by model family: "Opus 120k (2) · Sonnet 40k (5)"
511 const spendSegs = (scope: AgentNode[]): Seg[] => spendByModel(scope).flatMap((m, i) => [
512 ...(i ? [seg(' · ', C.faint)] : []), seg(m.model, C.soft), seg(` ${kTokens(m.tokens)}`, C.ink), seg(` (${m.agents})`, C.faint)])
513 const nowSegs = (n: AgentNode): Seg[] => [seg('› ', C.accent), seg(n.activity ?? 'Thinking', C.ink), seg(` ${ACT_WORD[n.act ?? 'think']}`, C.faint)]
514 const quietFor = (n: AgentNode) => (n.status === 'running' ? now - (n.lastToolAt ?? n.startedAt) : 0)
515 // a cluster's aspects as chips: each member's short task with how it went
516 const chipSegs = (groupId: string, w: number): Seg[] => {
517 const list = aspects(nodes, groupId)
518 if (!list.length) return []
519 const each = Math.max(6, Math.floor(w / list.length) - 5)
520 const out: Seg[] = []
521 let used = 0
522 for (let i = 0; i < list.length; i++) {
523 const { node, text } = list[i]!
524 const piece: Seg[] = [...(i ? [seg(' ')] : []), seg(statusIcon(node), T.status[node.status].color), seg(' '), seg(fit(text, each), C.soft)]
525 const rest = list.length - i - 1
526 if (used + width(piece) + (rest ? 8 : 0) > w && i > 0) { out.push(seg(` +${list.length - i}`, C.faint)); break }
527 out.push(...piece)
528 used += width(piece)
529 }
530 return out
531 }
532 const overlapSegs = (groupId: string): Seg[] => {
533 const o = overlaps(scopeNodes(nodes, { kind: 'node', id: groupId }).filter(k => k.id !== groupId))[0]
534 if (!o) return []
535 const more = overlaps(scopeNodes(nodes, { kind: 'node', id: groupId }).filter(k => k.id !== groupId)).length - 1
536 return [seg(`${T.warn} `, C.warn), seg(`${baseName(o.path)} edited by ${o.by.length} members`, C.warn), seg(` (${o.by.map(b => b.label).join(', ')})`, C.muted),
537 ...(more > 0 ? [seg(` +${more} more file${more === 1 ? '' : 's'}`, C.faint)] : [])]
538 }
539
540 // ── the report: Result, Parts or Done, Decisions, Problems, Next, Changed, Totals ──
541 // The words are the model's; Changed and Totals come from the mod's own records.
542 type Section = [string, Seg[][]]
543 const pmSegs = (added: number, removed: number): Seg[] => [seg(`+${num(added)}`, C.add), seg(' '), seg(`−${num(removed)}`, C.del)]
544 const phaseStatus = (p: { running: number; failed: number; stopped: number }) =>
545 p.failed ? T.status.failed : p.running ? T.status.running : p.stopped ? T.status.killed : T.status.done
546 // one line per part: a workflow's phases, or a cluster's members
547 // `all` (the Output view) wraps each part's outcome under itself; the overview cuts it to one line
548 const partRows = (n: AgentNode, w: number, all = false): Seg[][] => {
549 const line = (glyph: { icon: string; color: string }, name: string, nameW: number, count: string, outcome: string, files: FileRow[]): Seg[][] => {
550 const added = files.reduce((a, f) => a + f.added, 0)
551 const removed = files.reduce((a, f) => a + f.removed, 0)
552 const pm = files.length ? pmSegs(added, removed) : []
553 const head: Seg[] = [seg(padEnd(glyph.icon, 2), glyph.color), seg(' '), seg(padEnd(fit(name, nameW), nameW), C.ink, true), ...(count ? [seg(` ${count}`, C.muted)] : [])]
554 const room = Math.max(8, w - width(head) - 2 - (pm.length ? width(pm) + 2 : 0))
555 const lines = all ? wrap(outcome, room) : [fit(outcome, room)]
556 return lines.map((said, i) => i === 0
557 ? [...head, seg(' '), seg(said, C.soft), seg(' '.repeat(Math.max(0, room - cellWidth(said)))), ...(pm.length ? [seg(' '), ...pm] : [])]
558 : [seg(' '.repeat(width(head) + 2)), seg(said, C.soft)])
559 }
560 if (n.kind === 'workflow') {
561 const ps = pipeline(n, nodes)
562 const nameW = Math.min(14, Math.max(4, ...ps.map(p => cellWidth(p.phase))))
563 return ps.flatMap(p => line(phaseStatus(p), p.phase, nameW, padStart(`${p.total} agent${p.total === 1 ? '' : 's'}`, 9),
564 n.partReports?.[p.phase]?.result ?? phaseWords(p), fileRows(scopeNodes(nodes, { kind: 'phase', wfId: n.id, phase: p.phase }))))
565 }
566 if (n.kind === 'group') {
567 const kids = childrenOf(nodes, n.id).sort((a, b) => a.startedAt - b.startedAt)
568 const nameW = Math.min(30, Math.max(8, ...kids.map(k => cellWidth(k.label))))
569 return kids.flatMap(k => line(T.status[k.status], k.label, nameW, '', outcomeOf(k) || noReportReason(k), fileRows(scopeNodes(nodes, { kind: 'node', id: k.id }))))
570 }
571 return []
572 }
573 const changedRows = (f: Facts, w: number, all: boolean): Seg[][] => {
574 const short = shortPaths(f.files.map(x => x.path))
575 if (all) {
576 const nameW = Math.min(w - 16, Math.max(...f.files.map(x => cellWidth(short.get(x.path) ?? x.path))))
577 return f.files.map(x => [seg(padEnd(fit(short.get(x.path) ?? x.path, nameW), nameW), C.ink), seg(' '), ...pmSegs(x.added, x.removed)])
578 }
579 const out: Seg[] = []
580 let shown = 0
581 for (const x of f.files) {
582 const piece: Seg[] = [...(shown ? [seg(' · ', C.faint)] : []), seg(short.get(x.path) ?? x.path, C.ink), seg(' '), ...pmSegs(x.added, x.removed)]
583 const rest = f.files.length - shown - 1
584 if (width(out) + width(piece) + (rest ? 10 : 0) > w && shown) break
585 out.push(...piece)
586 shown++
587 }
588 if (shown < f.files.length) out.push(seg(` · +${f.files.length - shown} more`, C.faint))
589 return [out]
590 }
591 const plural = (k: number, one: string) => `${k} ${one}${k === 1 ? '' : 's'}`
592 const totalsRows = (f: Facts, w: number): Seg[][] => {
593 const parts: Seg[][] = [
594 ...(f.phases ? [[seg(plural(f.phases, 'phase'), C.soft)]] : []),
595 [seg(plural(f.agents, 'agent'), C.soft)],
596 [seg(plural(f.files.length, 'file'), C.soft)],
597 ...(f.files.length ? [pmSegs(f.added, f.removed)] : []),
598 [seg(duration(f.ms), C.soft)],
599 ...(f.tokens ? [[seg(`${kTokens(f.tokens)} tokens`, C.soft)]] : []),
600 ]
601 const lines: Seg[][] = [[]]
602 for (const p of parts) {
603 const cur = lines[lines.length - 1]!
604 const piece = [...(cur.length ? [seg(' · ', C.faint)] : []), ...p]
605 if (cur.length && width(cur) + width(piece) > w) lines.push([...p])
606 else cur.push(...piece)
607 }
608 return lines
609 }
610 // `all`: the Output view's full block; otherwise lists and long text are capped for the
611 // overview; `brief` keeps only Result, Problems, Next and Totals, for a pane short of rows
612 const reportSections = (sc: Scope, valueW: number, all: boolean, brief = false): Section[] => {
613 const node = sc.kind === 'node' ? nodes.find(x => x.id === sc.id) : undefined
614 const wf = sc.kind === 'phase' ? nodes.find(x => x.id === sc.wfId) : undefined
615 const r = sc.kind === 'phase' ? wf?.partReports?.[sc.phase] : node ? reportOf(node) : undefined
616 const f = reportFacts(nodes, sc, now)
617 const text = (t: string, c: string): Seg[][] => wrap(t, valueW).slice(0, all ? 99 : brief ? 2 : 3).map(l => [seg(l, c)])
618 const bullets = (items: { text: string; source?: string }[], c: string): Seg[][] => items.slice(0, 3).flatMap(it =>
619 wrap(`${it.text}${it.source ? ` [${it.source}]` : ''}`, valueW - 3).slice(0, all ? 99 : 2).map((l, i) => [seg(i ? ' ' : '• ', C.faint), seg(l, c)]))
620 const out: Section[] = []
621 const aiOff = props.ai === 'off' && !r?.result
622 const fallback = aiOff ? 'AI is off: no written report. Set ai to cheap or full in /config.'
623 : sc.kind === 'phase' ? 'No part report yet.' : node ? noReportReason(node) : ''
624 out.push(['Result', text(r?.result ?? fallback, aiOff ? C.muted : C.ink)])
625 // with AI off the failures still show, from the records
626 const recordProblems = aiOff ? scopeNodes(nodes, sc).filter(n => n.kind === 'agent' && (n.status === 'failed' || n.status === 'killed'))
627 .map(n => ({ text: `${n.label} ${n.status === 'failed' ? 'failed' : 'was stopped'}.` })) : []
628 if (brief) {
629 if (r?.problems?.length) out.push(['Problems', r.problems.slice(0, 2).map(p => [seg('• ', C.faint), seg(fit(`${p.text}${p.source ? ` [${p.source}]` : ''}`, valueW - 3), C.warn)])])
630 if (r?.next) out.push(['Next', [[seg(fit(r.next, valueW), C.soft)]]])
631 out.push(['Totals', totalsRows(f, valueW)])
632 return out
633 }
634 const parts = node ? partRows(node, valueW, all) : []
635 if (parts.length) {
636 const cap = all ? parts.length : 6
637 out.push(['Parts', [...parts.slice(0, cap), ...(parts.length > cap ? [[seg(`+${parts.length - cap} more parts`, C.faint)]] : [])]])
638 } else if (r?.done?.length) out.push(['Done', bullets(r.done.map(t => ({ text: t })), C.soft)])
639 if (r?.decisions?.length) out.push(['Decisions', bullets(r.decisions, C.soft)])
640 if (r?.problems?.length) out.push(['Problems', bullets(r.problems, C.warn)])
641 else if (recordProblems.length) out.push(['Problems', bullets(recordProblems, C.warn)])
642 if (r?.next) out.push(['Next', text(r.next, C.soft)])
643 if (f.files.length) out.push(['Changed', changedRows(f, valueW, all)])
644 out.push(['Totals', totalsRows(f, valueW)])
645 return out
646 }
647 const sectionRows = (secs: Section[]): Row[] =>
648 secs.flatMap(([name, lines]) => lines.map((l, i) => ({ segs: [seg(padEnd(i ? '' : name, 11), C.muted), ...l] })))
649 // who wrote a report, beside its heading
650 const writtenBy = (sc: Scope): string => {
651 const r = sc.kind === 'phase' ? nodes.find(x => x.id === sc.wfId)?.partReports?.[sc.phase] : nodes.find(x => x.id === sc.id)?.report
652 if (r?.model) return aiLabel(r)
653 return props.ai === 'off' ? 'AI is off · from records' : 'from what the run kept'
654 }
655
656 // ── the overview of the selection, as rows of a given width ───────────
657 const overview = (w: number, dense: 'compact' | 'brief' | 'full'): Row[] => {
658 if (!scope) return []
659 const title = scope.kind === 'phase' ? `${scope.phase} phase` : scopeNode?.label ?? ''
660 const when = (n: AgentNode) => (isHistory ? clock(n.startedAt) : undefined)
661 let meta: Seg[] = []
662 let second: Seg[] = []
663 let rows: [string, Seg[]][] = []
664 let points: string[] = []
665 if (scope.kind === 'phase') {
666 const c = counts(scopeList)
667 const wf = nodes.find(n => n.id === scope.wfId)
668 const start = Math.min(...scopeList.map(k => k.startedAt))
669 const end = c.running ? now : Math.max(...scopeList.map(k => k.endedAt ?? now))
670 meta = statusSegs({ status: c.running ? 'running' : c.failed ? 'failed' : 'done', startedAt: start, endedAt: end })
671 second = [...rollSegs(c, 12), seg(` ${c.total - c.running} of ${c.total} agents`, C.muted)]
672 const spend = spendSegs(scopeList)
673 rows = [['Agents', [seg(phaseWords({ phase: scope.phase, ...c }), C.ink)]], ['Changes', changeSegs(files)], ...(spend.length ? [['Spend', spend] as [string, Seg[]]] : []), ['Part of', [seg(wf?.label ?? 'workflow', C.soft)]]]
674 } else if (scopeNode && scopeNode.kind !== 'agent') {
675 const n = scopeNode
676 const kids = childrenOf(nodes, n.id)
677 const c = counts(kids)
678 const busy = kids.find(x => x.status === 'running')
679 meta = statusSegs(n, when(n))
680 second = [...rollSegs(c, 12), seg(` ${c.total - c.running} of ${c.total} ${n.kind === 'group' ? 'members' : 'agents'}`, C.muted)]
681 const phases: Seg[] = pipeline(n, nodes).flatMap((p, i) => [...(i ? [seg(' → ', C.faint)] : []), seg(p.phase, C.ink), seg(` ${phaseWords(p)}`, C.muted)])
682 const inline = mode === 'agents' && n.kind === 'group' && (dense !== 'full' || layout !== 'split')
683 const overlap = n.kind === 'group' && !inline ? overlapSegs(n.id) : []
684 rows = [
685 n.kind === 'group' ? ['Agents', [seg(phaseWords({ phase: '', ...c }), C.ink)]] : ['Phases', phases],
686 ...(n.kind === 'group' && !inline ? [['Aspects', chipSegs(n.id, w - 11)] as [string, Seg[]]] : []),
687 ...(overlap.length ? [['Overlap', overlap] as [string, Seg[]]] : []),
688 ['Changes', changeSegs(files)],
689 ...(spendSegs(scopeList).length ? [['Spend', spendSegs(scopeList)] as [string, Seg[]]] : []),
690 n.status === 'running' && busy ? ['Now', [...nowSegs(busy), seg(` ${busy.label}`, C.muted)]] : ['Outcome', [seg(outcome(n) || '—', C.ink)]],
691 ]
692 points = n.points ?? []
693 } else if (scopeNode) {
694 const n = scopeNode
695 const inWf = isInWorkflow(n)
696 meta = statusSegs(n, when(n))
697 second = [seg([prettyType(n, inWf), prettyModel(n.model), inWf && n.phase ? `${n.phase} phase` : n.where && n.where !== 'main' ? whereLabel(n.where) : ''].filter(Boolean).join(' · '), C.muted)]
698 const quiet = quietFor(n)
699 rows = [
700 n.status === 'running' ? ['Now', [...nowSegs(n), ...(quiet >= 120_000 ? [seg(` ${T.warn} quiet ${duration(quiet)}`, C.warn)] : [])]] : ['Outcome', [seg(outcome(n) || noReportReason(n), C.ink)]],
701 ['Changes', changeSegs(files)],
702 ['Work', [seg(`${workSummary(n)}${n.tokens ? ` · ${Math.round(n.tokens / 1000)}k tokens` : ''}`, C.soft)]],
703 ]
704 points = n.points ?? []
705 }
706 // finished work shows its report: the model's words, then what changed and the totals from records
707 const isFinished = scope.kind === 'phase' ? counts(scopeList).running === 0 && scopeList.length > 0 : !!scopeNode && scopeNode.status !== 'running'
708 const secs = isFinished ? reportSections(scope, w - 11, false, dense === 'brief') : undefined
709 const out: Row[] = []
710 if (dense === 'compact') {
711 const changed = files.length ? changeSegs(files) : []
712 const titleW = Math.max(8, w - width(changed) - 3)
713 const shownTitle = fit(title, titleW)
714 out.push({ segs: [seg(shownTitle, C.ink, true), seg(' '.repeat(Math.max(3, w - cellWidth(shownTitle) - width(changed)))), ...changed] })
715 const what = scope.kind === 'node' && scopeNode?.kind === 'agent' ? second : rows[0]?.[1] ?? []
716 out.push({ segs: [...meta, ...(what.length ? [seg(' · ', C.faint), ...what] : [])] })
717 const result = secs?.find(([k]) => k === 'Result')?.[1][0]
718 const [name, value] = result ? ['Result', result] : rows.find(([k]) => k === 'Now' || k === 'Outcome') ?? rows[0] ?? ['', []]
719 out.push({ segs: [seg(padEnd(name, 10), C.muted), ...value] })
720 return out
721 }
722 for (const line of wrap(title, w).slice(0, dense === 'brief' ? 1 : 2)) out.push({ segs: [seg(line, C.ink, true)] })
723 out.push({ segs: meta })
724 if (dense !== 'brief') { out.push({ segs: second }); out.push({ segs: [] }) }
725 if (secs) {
726 // a parent keeps its one status line ("6 done"); the report follows
727 const status = scope.kind === 'phase' || scopeNode?.kind !== 'agent' ? rows.filter(([k]) => k === 'Agents' || k === 'Phases' || k === 'Spend') : []
728 for (const [name, value] of status) out.push({ segs: [seg(padEnd(name, 11), C.muted), ...value] })
729 out.push(...sectionRows(secs))
730 if (scopeNode?.kind === 'agent') out.push(...rows.filter(([k]) => k === 'Work').map(([name, value]) => ({ segs: [seg(padEnd(name, 11), C.muted), ...value] })))
731 return out
732 }
733 for (const [name, value] of rows) {
734 const valueW = w - 11
735 // a long sentence wraps under its value column
736 if (value.length === 1 && cellWidth(value[0]!.t) > valueW) {
737 wrap(value[0]!.t, valueW).slice(0, 3).forEach((t, i) => out.push({ segs: [seg(padEnd(i ? '' : name, 11), C.muted), seg(t, value[0]!.c)] }))
738 } else out.push({ segs: [seg(padEnd(name, 11), C.muted), ...value] })
739 }
740 if (layout === 'split' && points.length) {
741 out.push({ segs: [] })
742 out.push({ segs: [seg('Key points', C.accent, true)] })
743 for (const p of points) wrap(p, w - 3).forEach((t, i) => out.push({ segs: [seg(i ? ' ' : ' • ', C.faint), seg(t, C.soft)] }))
744 }
745 return out
746 }
747
748 // ── output text ──────────────────────────────────────────────────────
749 const outRows = (w: number): Row[] => {
750 if (mode !== 'output') return []
751 const out: Row[] = []
752 const para = (t: string, c?: string, b?: boolean) => wrap(t, w).forEach(text => out.push({ segs: [seg(text, c, b)] }))
753 const gap = () => out.push({ segs: [] })
754 // finished work opens with its whole report; the agents' own words follow
755 const reportBlock = (sc: Scope) => {
756 out.push({ segs: [seg('Report', C.accent, true), seg(` ${writtenBy(sc)}`, C.faint)] })
757 out.push(...sectionRows(reportSections(sc, w - 11, true)))
758 gap()
759 }
760 if (scope?.kind === 'phase') {
761 if (scopeList.length && counts(scopeList).running === 0) reportBlock(scope)
762 para(`What the ${scope.phase} phase reported`, C.accent, true)
763 for (const k of scopeList) {
764 gap()
765 para(k.label, C.ink, true)
766 para(k.summary ?? (firstSentence(k.result, 300) || noReportReason(k)), C.soft)
767 }
768 return out
769 }
770 const n = scopeNode
771 if (!n) return out
772 // the run's brief, when it has one or one is being written; else how to get one
773 if (run && n.id === run.id) {
774 const writing = props.explaining?.includes(run.id)
775 const b: Brief | undefined = run.explain
776 if (b || writing) {
777 out.push({ segs: [seg('Explain', C.accent, true), seg(` ${writing ? 'writing… (Sonnet)' : aiLabel(b)}`, C.faint)] })
778 if (b) {
779 const LBL = 18
780 const vw = Math.max(10, w - LBL)
781 const line = (name: string, t: string, c: string) => wrap(t, vw).forEach((x, i) => out.push({ segs: [seg(padEnd(i ? '' : name, LBL), C.muted), seg(x, c)] }))
782 const list = (name: string, items: string[], c: string) => items.forEach((t, k) => wrap(t, vw - 3).forEach((x, i) =>
783 out.push({ segs: [seg(padEnd(k === 0 && i === 0 ? name : '', LBL), C.muted), seg(i ? ' ' : '• ', C.faint), seg(x, c)] })))
784 if (b.goal) line('Goal', b.goal, C.ink)
785 if (b.who?.length) list('Who did what', b.who, C.soft)
786 if (b.connected) line('How it connected', b.connected, C.soft)
787 if (b.outcome) line('Outcome', b.outcome, C.ink)
788 if (b.open?.length) list('Open issues', b.open, C.warn)
789 }
790 gap()
791 } else if (isFull) {
792 out.push({ segs: [seg('e', C.soft, true), seg(' asks Sonnet to explain how this run hung together.', C.faint)] })
793 gap()
794 }
795 }
796 const isDone = n.status !== 'running'
797 if (isDone && scope) reportBlock(scope)
798 if (!isDone && n.summary) { para('Outcome', C.accent, true); para(n.summary, C.ink) }
799 if (!isDone && n.points?.length) { gap(); para('Key points', C.accent, true); n.points.forEach(p => para(`• ${p}`, C.soft)) }
800 if (n.kind !== 'agent') {
801 if (!isDone) gap()
802 para(n.kind === 'group' ? 'Members' : 'Agents', C.accent, true)
803 for (const k of childrenOf(nodes, n.id)) para(`${k.phase ? `${k.phase} · ` : ''}${k.label} — ${k.summary ?? (firstSentence(k.result, 160) || noReportReason(k))}`, C.soft)
804 }
805 const report = n.kind === 'workflow' ? readableResult(n.result) : n.result
806 if (report) {
807 gap(); para(reportHeading(n), C.accent, true)
808 for (const line of report.split('\n')) para(plain(line) || ' ', C.muted)
809 }
810 if (!isDone && !report && !n.summary) para('Still working — the report appears here when it finishes.', C.muted)
811 const task = taskText(n.prompt)
812 if (task) { gap(); para('Task it was given', C.accent, true); para(task, C.muted) }
813 return out
814 }
815
816 // ── two runs side by side: totals, phases, spend by model, files ──────
817 const compareRows = (w: number): Row[] => {
818 if (mode !== 'compare') return []
819 const [a, b] = pair as [AgentNode, AgentNode]
820 const cmp = compareRuns(allNodes, a, b, now)
821 const out: Row[] = []
822 const gap = () => out.push({ segs: [] })
823 const fmt = (m: Metric, v: number | undefined) => (v === undefined ? '—' : m.measure === 'ms' ? duration(v) : m.measure === 'tokens' ? kTokens(v) : num(v))
824 const nameW = Math.min(16, Math.max(8, ...[...cmp.totals, ...cmp.phases, ...cmp.models].map(m => cellWidth(m.name)))) + 2
825 const colW = Math.max(9, Math.min(14, Math.floor((w - nameW - 18) / 2)))
826 const change = (m: Metric): Seg => {
827 const v = verdict(m)
828 if (m.a === undefined || m.b === undefined) return seg(m.a === undefined ? 'only in B' : 'only in A', C.faint)
829 if (m.a === m.b) return seg('same', C.faint)
830 const d = m.b - m.a
831 const pct = m.a ? ` (${d > 0 ? '+' : ''}${Math.round((d / m.a) * 100)}%)` : ''
832 const abs = m.measure === 'ms' ? duration(Math.abs(d)) : m.measure === 'tokens' ? kTokens(Math.abs(d)) : num(Math.abs(d))
833 return seg(`${d > 0 ? '+' : '−'}${abs}${pct}`, v === 'better' ? C.ok : v === 'worse' ? C.bad : C.muted)
834 }
835 const table = (title: string, list: Metric[]) => {
836 if (!list.length) return
837 out.push({ segs: [seg(padEnd(title, nameW), C.accent, true), seg(padStart('A', colW), C.muted, true), seg(padStart('B', colW), C.muted, true), seg(' change', C.muted, true)] })
838 for (const m of list) out.push({ segs: [seg(padEnd(fit(m.name, nameW - 2), nameW), C.soft), seg(padStart(fmt(m, m.a), colW), C.ink), seg(padStart(fmt(m, m.b), colW), C.ink), seg(' '), change(m)] })
839 gap()
840 }
841 const who = (k: string, n: AgentNode) => [seg(`${k} `, C.accent, true), seg(statusIcon(n), T.status[n.status].color), seg(' '), seg(n.label, C.ink, true), seg(` ${dayLabel(n.startedAt, now)} ${clock(n.startedAt)}`, C.muted)]
842 out.push({ segs: who('A', a) }, { segs: who('B', b) })
843 gap()
844 table('Totals', cmp.totals)
845 table('Phases', cmp.phases)
846 table('Tokens by model', cmp.models)
847 const files = (title: string, list: string[]) => {
848 if (!list.length) return
849 const short = shortPaths(list)
850 out.push({ segs: [seg(title, C.accent, true), seg(` ${list.length}`, C.faint)] })
851 wrap(list.map(p => short.get(p) ?? p).join(' · '), w - 3).slice(0, 6).forEach(l => out.push({ segs: [seg(' '), seg(l, C.soft)] }))
852 }
853 files('Files only A changed', cmp.files.onlyA)
854 files('Files only B changed', cmp.files.onlyB)
855 files('Files both changed', cmp.files.both)
856 if (!cmp.files.onlyA.length && !cmp.files.onlyB.length && !cmp.files.both.length) out.push({ segs: [seg('Neither run changed files.', C.muted)] })
857 return out
858 }
859
860 // ── insights: one row on narrow panes, up to two on wide ones ─────────
861 const insightRows = (w: number): Row[] => {
862 if (!shownInsights.length || mode === 'help') return []
863 const piece = (it: Insight, i: number): Seg[] => {
864 const on = i === s.insight
865 const mark = it.tone === 'bad' ? T.status.failed.icon : it.tone === 'warn' ? T.warn : '·'
866 const color = it.tone === 'bad' ? C.bad : it.tone === 'warn' ? C.warn : C.soft
867 return [seg(`${mark} `, color), seg(it.text, on ? C.accent : color, on)]
868 }
869 const label = [seg(layout === 'compact' ? '' : 'Needs a look ', C.muted, true)]
870 const rows: Row[] = []
871 let cur: Seg[] = [...label]
872 let hits: Hit[] = []
873 const maxRows = layout === 'compact' ? 1 : 2
874 for (let i = 0; i < shownInsights.length; i++) {
875 const p = [...(width(cur) > width(label) ? [seg(' ')] : []), ...piece(shownInsights[i]!, i)]
876 const rest = shownInsights.length - i
877 const tail = rows.length + 1 === maxRows && rest > 1 ? 14 : 0
878 if (width(cur) + width(p) + tail > w && width(cur) > width(label)) {
879 if (rows.length + 1 === maxRows) { cur.push(seg(` +${rest} more · i`, C.faint)); break }
880 rows.push({ segs: cur, hit: hits })
881 cur = [seg(' '.repeat(width(label)))]
882 hits = []
883 i--
884 continue
885 }
886 const x0 = width(cur)
887 const target = shownInsights[i]!
888 const idx = i
889 hits.push({ x0, x1: x0 + width(p), act: () => jumpTo(target.target, idx) })
890 cur.push(...p)
891 }
892 rows.push({ segs: cur, hit: hits })
893 return rows
894 }
895
896 // ── fixed blocks: top rows, the body, bottom rows ─────────────────────
897 const isReading = mode === 'output' || mode === 'diff' || mode === 'help' || mode === 'trace' || mode === 'compare'
898 // the History page's numbers on top, and the search line while there is one
899 const isHistoryPage = isHistory && !run && lens === 'tree'
900 // runs that match, not the runs a pattern card points at
901 const matchCount = isHistoryPage ? agentItems.filter(it => it.kind === 'node' && it.guide !== 'pattern').length : 0
902 const historyHeader = (): Row[] => {
903 const st = historyStats(nodes, now)
904 const sp = sparkline(st.perDay)
905 // the numbers first; then what the AI layer spent; the sparkline's caption only where it fits
906 const base: Seg[] = [seg(`${st.runs}`, C.ink, true), seg(` run${st.runs === 1 ? '' : 's'}`, C.muted), seg(' '),
907 seg(`${st.okPct}%`, C.ink, true), seg(' finished OK', C.muted), seg(' '),
908 seg(kTokens(st.tokens), C.ink, true), seg(' tokens', C.muted), seg(' '), seg(sp.glyphs, C.accent)]
909 // the sparkline's scale keeps its place (a chart needs its extremes); AI spend fits around it
910 const spent = props.aiWeek ?? 0
911 const longCap = ` runs per day, last 7 days · 0 to ${sp.max}`
912 const shortCap = ` per day, 7 days · 0 to ${sp.max}`
913 const longAi = spent ? ` AI: ${kTokens(spent)} tokens this week` : ''
914 const shortAi = spent ? ` AI ${kTokens(spent)} this week` : ''
915 const [cap, ai] = ([[longCap, longAi], [shortCap, longAi], [shortCap, shortAi], [shortCap, ''], ['', '']] as [string, string][])
916 .find(([c, a]) => width(base) + cellWidth(c) + cellWidth(a) <= IW) ?? ['', '']
917 const rows: Row[] = [{ segs: [...base, ...(cap ? [seg(cap, C.faint)] : []), ...(ai ? [seg(ai, C.faint)] : [])] }]
918 if (s.searching || s.query) {
919 rows.push({
920 segs: [seg('/ ', C.accent, true), seg(s.query, C.ink, true), ...(s.searching ? [seg(T.cursor, C.accent)] : []),
921 seg(` ${matchCount} match${matchCount === 1 ? '' : 'es'}`, C.muted),
922 seg(s.searching ? ' enter keep · ctrl+u clear · ⌫ delete' : ' / edit · ctrl+u clear', C.faint)],
923 })
924 }
925 return rows
926 }
927 const strip = isHistoryPage && mode !== 'help' ? historyHeader() : insightRows(IW)
928 const fullOverview = (() => {
929 // History's rows carry each run's result; a run's report shows beside them from 140 columns
930 if (layout === 'split' || isReading || isHistoryPage) return []
931 if (layout === 'compact') return overview(IW, 'compact')
932 // the whole report when the list keeps 10 rows; else its brief form; else three lines
933 const rowsLeft = (o: Row[]) => CH - 1 - 1 - (strip.length ? strip.length + 1 : 0) - 1 - 2 - (o.length + 1)
934 const full = overview(IW, 'full')
935 if (rowsLeft(full) >= 10) return full
936 const brief = overview(IW, 'brief')
937 return rowsLeft(brief) >= 8 ? brief : overview(IW, 'compact')
938 })()
939 const TOP = 1 + 1 + (strip.length ? strip.length + 1 : 0) + (fullOverview.length ? fullOverview.length + 1 : 0) + 1 // tabs, rule, insights + rule, overview + rule, caption
940 const BOTTOM = 2 // rule, keys
941 const bodyRows = Math.max(1, CH - TOP - BOTTOM)
942 const isSplit = layout === 'split' && (mode === 'agents' || mode === 'files' || mode === 'board' || mode === 'timeline')
943 const listW = isSplit ? LW : IW
944 const output = outRows(IW)
945 const comparison = compareRows(IW)
946 // the views that scroll as text, a page at a time
947 const isText = mode === 'output' || mode === 'compare' || mode === 'help'
948
949 // ── the board and the timeline: rows built at a width, cards placed on them ──
950 type Body = { rows: Row[]; cardRow: number[] }
951 const cursorSeg = (on: boolean) => seg(on ? T.cursor : ' ', C.accent)
952 const cell2 = (g: string, c?: string) => seg(padEnd(g, 2), c)
953 const emptyRows = (w: number): Row[] => [
954 { segs: [] },
955 { segs: [seg(' '), seg(isHistory ? T.words.emptyHistory : T.words.emptyLive, C.ink)] },
956 { segs: [] },
957 ...wrap(isHistory ? 'Finished subagents and workflows are kept here across sessions.' : T.words.emptyHint, w - 2).map(t => ({ segs: [seg(' '), seg(t, C.muted)] })),
958 ]
959 const cardMeta = (n: AgentNode): Seg[] => {
960 const quiet = quietFor(n)
961 if (n.status === 'running' && quiet >= 120_000) return [seg(`${T.warn} quiet ${duration(quiet)}`, C.warn)]
962 const rows = fileRows([n])
963 const added = rows.reduce((a, r) => a + r.added, 0)
964 const removed = rows.reduce((a, r) => a + r.removed, 0)
965 return [seg(duration(elapsed(n)), C.muted), ...(rows.length ? [seg(' '), seg(`+${added}`, C.add), seg(' '), seg(`−${removed}`, C.del)] : []),
966 ...(n.status === 'running' && n.activity ? [seg(` ${n.activity}`, C.faint)] : [])]
967 }
968 const boardBody = (w: number): Body => {
969 const rows: Row[] = []
970 const cardRow: number[] = []
971 const gap = 2
972 const colW = Math.floor((w - gap * 2) / 3)
973 const narrow = colW < 22
974 const totals = COLUMNS.map((_, ci) => laneCells.reduce((a, cells) => a + cells[ci]!.length, 0))
975 rows.push({
976 segs: COLUMNS.flatMap((col, ci) => {
977 const color = col === 'running' ? T.status.running.color : col === 'done' ? T.status.done.color : T.status.failed.color
978 return [...(ci ? [seg(' '.repeat(gap))] : []), seg(padEnd(fit(`${COLUMN_NAMES[col][narrow ? 1 : 0]} ${totals[ci]}`, colW), colW), color, true)]
979 }),
980 })
981 if (!lanes.length) return { rows: [...rows, ...emptyRows(w)], cardRow }
982 let k = 0
983 lanes.forEach((lane, li) => {
984 const cells = laneCells[li]!
985 const c = counts(lane.cards)
986 const glyph = lane.kind === 'cluster' ? T.kind.group : lane.kind === 'workflow' ? T.kind.workflow : ''
987 rows.push({ segs: [] })
988 rows.push({ segs: [...(glyph ? [seg(`${glyph} `)] : []), seg(lane.title, C.ink, true), seg(' '), ...rollSegs(c, 6), seg(` ${c.total - c.running}/${c.total}`, C.muted)] })
989 const idx = cells.map(list => list.slice(0, CARDS_PER_CELL).map(() => k++))
990 const depth = Math.min(CARDS_PER_CELL, Math.max(...cells.map(l => l.length)))
991 for (let r = 0; r < depth; r++) {
992 const line1: Seg[] = []
993 const line2: Seg[] = []
994 const hits: Hit[] = []
995 let x = 0
996 cells.forEach((list, ci) => {
997 if (ci) { line1.push(seg(' '.repeat(gap))); line2.push(seg(' '.repeat(gap))); x += gap }
998 const n = list[r]
999 if (!n) { line1.push(seg(' '.repeat(colW))); line2.push(seg(' '.repeat(colW))); x += colW; return }
1000 const at = idx[ci]![r]!
1001 const on = mode === 'board' && at === sel
1002 const bg = on ? C.selBg : undefined
1003 line1.push(...lay([cursorSeg(on), seg(statusIcon(n), T.status[n.status].color), seg(' '), seg(n.label, on ? C.ink : C.soft, on)], colW).map(sg => ({ ...sg, bg })))
1004 line2.push(...lay([seg(' '), ...cardMeta(n)], colW).map(sg => ({ ...sg, bg })))
1005 hits.push({ x0: x, x1: x + colW, act: () => pickCard(at) })
1006 cardRow[at] = rows.length
1007 x += colW
1008 })
1009 rows.push({ segs: line1, hit: hits })
1010 rows.push({ segs: line2, hit: hits })
1011 }
1012 const extra = cells.map(list => Math.max(0, list.length - CARDS_PER_CELL))
1013 if (extra.some(Boolean)) {
1014 rows.push({ segs: cells.flatMap((_, ci) => [...(ci ? [seg(' '.repeat(gap))] : []), seg(padEnd(extra[ci] ? ` +${extra[ci]} more` : '', colW), C.faint)]) })
1015 }
1016 })
1017 return { rows, cardRow }
1018 }
1019 const timeBody = (w: number): Body => {
1020 const rows: Row[] = []
1021 const cardRow: number[] = []
1022 if (!timeCards.length) return { rows: [{ segs: [] }, ...emptyRows(w)], cardRow }
1023 const labelW = Math.min(32, Math.max(16, Math.floor(w * 0.34)))
1024 const durW = 8
1025 const barW = Math.max(10, w - labelW - durW - 2)
1026 const t0 = Math.min(...timeCards.map(n => n.startedAt))
1027 const t1 = Math.max(t0 + 1000, ...timeCards.map(n => n.endedAt ?? now))
1028 const span = t1 - t0
1029 const xOf = (t: number) => Math.round(((t - t0) / span) * barW)
1030 // the ruler: times since the first start, spaced so labels never touch
1031 const ruler = new Array<string>(barW).fill(' ')
1032 const ticks = Math.max(1, Math.min(5, Math.floor(barW / 12)))
1033 for (let i = 0; i <= ticks; i++) {
1034 const label = offset((i / ticks) * span)
1035 const x = Math.round((i / ticks) * (barW - 1))
1036 const at = Math.max(0, Math.min(barW - label.length, i === ticks ? x - label.length + 1 : x))
1037 for (let j = 0; j < label.length; j++) ruler[at + j] = label[j]!
1038 }
1039 // left of the ruler, inside a run: how long the critical path took, and the idle share
1040 const pathNote = crit ? `━ critical ${duration(crit.ms)}${idle.ms && crit.span ? ` · idle ${Math.round((idle.ms / crit.span) * 100)}%` : ''}` : ''
1041 rows.push({ segs: [seg(padEnd(fit(pathNote, labelW), labelW), C.accent), seg(' '), seg(ruler.join(''), C.faint), seg(' '.repeat(durW + 1))] })
1042 // idle stretches shade every row with dots, as a column
1043 const idleAt = new Array<boolean>(barW).fill(false)
1044 for (const g of idle.gaps) for (let x = Math.max(0, xOf(g.from)); x < Math.min(barW, xOf(g.to)); x++) idleAt[x] = true
1045 let k = 0
1046 for (const r of timeRows) {
1047 if (r.kind === 'label') { rows.push({ segs: [seg(' '), seg(r.text, C.muted, true)] }); continue }
1048 const n = r.node
1049 const at = k++
1050 const on = mode === 'timeline' && at === sel
1051 const color = T.status[n.status].color
1052 const x0 = Math.min(barW - 1, xOf(n.startedAt))
1053 const x1 = Math.max(x0 + 1, Math.min(barW, xOf(n.endedAt ?? now)))
1054 const isLive = n.status === 'running'
1055 // with a critical path, its bars are heavy and the others light
1056 const isCrit = onPath.has(n.id)
1057 const line = !crit || isCrit ? '━' : '─'
1058 const quiet = quietFor(n)
1059 const flag = flags.get(n.id)
1060 const tag = isLive ? (quiet >= 120_000 ? ` quiet ${duration(quiet)}` : ' running') : flag ? ` ${flag.text}` : ''
1061 const tagShown = tag && barW - x1 >= cellWidth(tag) ? tag : ''
1062 const tagColor = isLive ? (quiet >= 120_000 ? C.warn : C.faint) : flag?.tone === 'warn' ? C.warn : C.faint
1063 // the bar's cells: idle dots, the bar, then its tag
1064 const cells: Seg[] = []
1065 const put = (t: string, c?: string) => { const last = cells[cells.length - 1]; if (last && last.c === c) last.t += t; else cells.push({ t, c }) }
1066 for (let x = 0; x < x0; x++) put(idleAt[x] ? '·' : ' ', idleAt[x] ? C.rule : undefined)
1067 put(isLive ? `${line.repeat(Math.max(0, x1 - x0 - 1))}▸` : line.repeat(x1 - x0), color)
1068 if (tagShown) put(tagShown, tagColor)
1069 for (let x = x1 + cellWidth(tagShown); x < barW; x++) put(idleAt[x] ? '·' : ' ', idleAt[x] ? C.rule : undefined)
1070 const label = lay([cursorSeg(on), seg(' '), cell2(statusIcon(n), color), seg(' '), seg(n.label, on || isLive || isCrit ? C.ink : C.soft, on || isCrit)], labelW)
1071 rows.push({
1072 bg: on ? C.selBg : undefined,
1073 segs: [...label, seg(' '), ...cells, seg(' '), seg(padStart(duration(elapsed(n)), durW), C.muted)],
1074 hit: [{ x0: 0, x1: w, act: () => pickCard(at) }],
1075 })
1076 cardRow[at] = rows.length - 1
1077 }
1078 return { rows, cardRow }
1079 }
1080
1081 // ── selection, scrolling ─────────────────────────────────────────────
1082 const isLens = mode === 'board' || mode === 'timeline'
1083 // the trace the hooks sent for this run at this zoom; its rows are a window of all of them
1084 // (cut to the lane asked for; while a search is typed the rows stay, and only the hits wait)
1085 const tq = s.tquery.trim().slice(0, 80)
1086 const tv: TraceView | undefined = mode === 'trace' && run && props.trace?.run === run.id && props.trace.zoom === s.zoom && (props.trace.lane ?? null) === s.traceLane ? props.trace : undefined
1087 // the rows n and p step through: the search's hits while there is a search, else what needs a look
1088 const traceStops = tv ? (tq ? (tv.query === tq ? tv.hits ?? [] : []) : tv.marks ?? []) : []
1089 // under the trace: two pinned rows above (legend, lanes), a rule and two detail rows below
1090 const traceWin = mode === 'trace' ? Math.max(1, bodyRows - 5) : 0
1091 const count = mode === 'agents' ? agentItems.length : mode === 'files' ? fileItems.length : mode === 'diff' ? blocks.length
1092 : mode === 'output' ? output.length : mode === 'compare' ? comparison.length : mode === 'help' ? KEYS_HELP_COUNT : isLens ? cards.length : mode === 'trace' ? tv?.total ?? 0 : 0
1093 const okRow = (i: number) => (mode === 'agents' ? isSelectable(agentItems[i]) : true)
1094 const rawSel = mode === 'agents' ? agentSel : isLens ? cardSel : s.sel
1095 const sel = isText ? 0 : Math.min(Math.max(0, rawSel), Math.max(0, count - 1))
1096 const body: Body | undefined = mode === 'board' ? boardBody(listW) : mode === 'timeline' ? timeBody(listW) : undefined
1097 // the diff scrolls by edit block, the selected one at the top; the board and the
1098 // timeline by rows under their pinned first row, keeping the selected card in sight
1099 let first = isText ? s.first : mode === 'diff' ? sel : Math.min(s.first, sel)
1100 if (body) {
1101 const win = Math.max(1, bodyRows - 1)
1102 const total = body.rows.length - 1
1103 const top = (body.cardRow[sel] ?? 1) - 1
1104 const tall = mode === 'board' ? 2 : 1
1105 first = Math.min(s.first, total)
1106 if (top < first) first = Math.max(0, top - (mode === 'board' ? 2 : 0))
1107 if (top + tall > first + win) first = top + tall - win
1108 first = Math.max(0, Math.min(first, Math.max(0, total - win)))
1109 } else {
1110 const win = mode === 'trace' ? traceWin : bodyRows
1111 if (!isText && mode !== 'diff' && sel >= first + win) first = sel - win + 1
1112 if (mode !== 'diff') first = Math.max(0, Math.min(first, Math.max(0, count - win)))
1113 }
1114
1115 // ── actions ──────────────────────────────────────────────────────────
1116 const set = (patch: Partial<State>) => surface.setState({ ...s, sel, first, ...patch })
1117 const toggleIn = (list: string[], key: string) => (list.includes(key) ? list.filter(k => k !== key) : [...list, key])
1118 const closeDiff = () => { surface.post({ type: 'diff', path: null }); return { diffFile: null } }
1119 const topOf = (n: AgentNode) => { let x = n; while (x.parentId) { const p = nodes.find(m => m.id === x.parentId); if (!p) break; x = p } return x }
1120 const cardsFor = (at: AgentNode | undefined, l: Lens) => {
1121 if (l === 'board') return boardLanes(at, nodes, topRuns, s.filter).flatMap(lane => COLUMNS.flatMap(col => lane.cards.filter(n => columnOf(n) === col).slice(0, CARDS_PER_CELL)))
1122 return timelineRows(at, nodes, topRuns, s.filter).flatMap(r => (r.kind === 'bar' ? [r.node] : []))
1123 }
1124 // where a key sits in a lens's list, so a selection survives a change of view
1125 const indexIn = (key: string | null, at: AgentNode | undefined, l: Lens, flipped = s.flipped, showDone = s.showDone): number => {
1126 // a trace comes back to the row it was left on
1127 if (l === 'trace') return s.traceAt
1128 if (!key) return -1
1129 if (l === 'tree') return listFor(flipped, showDone, at).findIndex(it => keyOf(it) === key)
1130 return cardsFor(at, l).findIndex(n => n.id === key)
1131 }
1132 const go = (v: ViewName, extra: Partial<State> = {}) => {
1133 if (!run || v === view) return
1134 const keep = inAgents ? { agentSel: sel, focus: focusKey } : {}
1135 const leaving = diffOpen ? closeDiff() : {}
1136 const back = v === 'agents' ? Math.max(0, indexIn(s.focus, run, lens)) : 0
1137 set({ ...keep, ...leaving, ...extra, view: v, sel: v === 'agents' ? (inAgents ? sel : back) : 0, first: 0 })
1138 }
1139 const openRun = (n: AgentNode, v: ViewName = 'agents', focus: string | null = null) =>
1140 set({ path: n.id, view: v, sel: v === 'agents' ? Math.max(0, indexIn(focus, n, lens)) : 0, first: 0, agentSel: 0, focus, diffFile: null })
1141 const openDiff = (path: string) => { surface.post({ type: 'diff', path }); set({ diffFile: path, sel: 0, first: 0 }) }
1142 // Opens what hides a node in a run's tree: its phase, the done agents folded
1143 // under it, and any parent that was closed.
1144 const reveal = (n: AgentNode, at: AgentNode) => {
1145 let flipped = [...s.flipped]
1146 let showDone = [...s.showDone]
1147 for (let x: AgentNode | undefined = nodes.find(m => m.id === n.parentId); x; x = nodes.find(m => m.id === x!.parentId)) {
1148 flipped = flipped.filter(k => k !== `o:${x.id}`)
1149 if (x.id === at.id) break
1150 }
1151 const wf = nodes.find(m => m.id === n.parentId && m.kind === 'workflow')
1152 if (wf && n.phase) {
1153 const key = `${wf.id}:${n.phase}`
1154 const phaseRow = listFor(flipped, showDone, at).find(it => it.kind === 'phase' && it.key === key)
1155 if (phaseRow?.kind === 'phase' && !phaseRow.isOpen) flipped = toggleIn(flipped, key)
1156 const shown = listFor(flipped, showDone, at).some(it => it.kind === 'node' && it.node.id === n.id)
1157 if (!shown && !showDone.includes(key)) showDone = [...showDone, key]
1158 }
1159 return { flipped, showDone }
1160 }
1161 // From a change, or an insight, to the agent it names, in the tree.
1162 const showInTree = (id: string, extra: Partial<State> = {}) => {
1163 const n = nodes.find(x => x.id === id)
1164 if (!n) return
1165 const at = topOf(n)
1166 if (!run && at.id === n.id && n.kind === 'agent') {
1167 const i = listFor(s.flipped, s.showDone, undefined).findIndex(it => it.kind === 'node' && it.node.id === id)
1168 return set({ ...extra, lens: 'tree', sel: Math.max(0, i) })
1169 }
1170 const { flipped, showDone } = reveal(n, at)
1171 const i = listFor(flipped, showDone, at).findIndex(it => it.kind === 'node' && it.node.id === id)
1172 if (diffOpen) surface.post({ type: 'diff', path: null })
1173 surface.setState({ ...s, ...extra, path: at.id, view: 'agents', lens: 'tree', diffFile: null, flipped, showDone, sel: Math.max(0, i), agentSel: Math.max(0, i), first: Math.max(0, i - 2) })
1174 }
1175 const jumpTo = (id: string | undefined, idx: number) => {
1176 if (!id) return set({ insight: idx })
1177 if (isLens && inAgents) {
1178 const i = cards.findIndex(c => c.id === id)
1179 if (i >= 0) return set({ sel: i, insight: idx })
1180 }
1181 showInTree(id, { insight: idx })
1182 }
1183 const toggleFold = (it: Item | undefined, open?: boolean) => {
1184 if (it?.kind === 'node' && it.fold && open !== it.fold.isOpen) return set({ flipped: toggleIn(s.flipped, it.fold.key) }), true
1185 if (it?.kind === 'phase' && open !== it.isOpen) return set({ flipped: toggleIn(s.flipped, it.key) }), true
1186 if (it?.kind === 'more' && open !== false) return set({ showDone: toggleIn(s.showDone, it.key) }), true
1187 return false
1188 }
1189 const activateCard = (i: number) => {
1190 const n = cards[i]
1191 if (!n) return
1192 if (!run) return openRun(topOf(n), 'agents', n.id)
1193 set({ agentSel: i, focus: n.id, view: 'output', sel: 0, first: 0 })
1194 }
1195 const pickCard = (i: number) => (i === sel ? activateCard(i) : set({ sel: i }))
1196 // a trace row, when the window the hooks sent holds it
1197 const traceRow = (i: number): TraceRow | undefined => (tv && i >= tv.offset && i < tv.offset + tv.rows.length ? tv.rows[i - tv.offset] : undefined)
1198 const laneId = (r: TraceRow | undefined) => (r && tv ? tv.lanes[r.lane]?.id : undefined)
1199 // Enter on a trace row: an edit opens its diff; any other row shows its agent in the tree
1200 const activateTrace = (i: number) => {hooks/desktop/sprites.ts 701 lines1// Pixel art for the desktop view: one set per playful theme, each a palette and text
2// grids ("." is clear), drawn as SVG squares with crisp edges. Every set fills the
3// same slots, so the view asks for "done" or "workflow" and each theme answers with
4// its own picture: kitty's cats, fish on lines, dogs on walks. Each state reads by
5// its outline at 16 px; failed and quiet lie down where the sprite has a body to lay.
6export const SLOTS = ['walk0', 'walk1', 'walk2', 'walk3', 'done', 'failed', 'stopped', 'quiet', 'workflow', 'group', 'scene'] as const
7export type Slot = typeof SLOTS[number]
8export type ArtSet = { pal: Record<string, string>; pix: Record<Slot, readonly string[]> }
9export type ArtName = 'kitty' | 'fish' | 'dog'
10
11// Cats: generated from the approved mockup's pixel data; workflow is yarn, a cluster a pile.
12const KITTY: ArtSet = {
13 pal: {"o": "#2e1f2b", "a": "#ffd09a", "b": "#f59a4f", "c": "#c96a2e", "d": "#a8522a", "H": "#d5dae3", "G": "#9fa8ba", "I": "#6e778b", "M": "#86799e", "N": "#5a4d70", "n": "#3f3550", "w": "#fff6ea", "x": "#e3cdb8", "p": "#f4899a", "q": "#d9667b", "g": "#ffffff", "z": "#8fb0f0", "Z": "#5f86d8", "B": "#f6eedc", "C": "#d8cbb0", "R": "#e5485a", "T": "#7cc8f4", "l": "#ffb3c0", "y": "#ec6a80", "Y": "#b94860", "L": "#bdb6d3", "K": "#8e87a9", "k": "#5a5373", "s": "#3a3449", "r": "#ffcf4d"},
14 pix: {
15 walk0: [
16 '................',
17 '.........o....o.',
18 '........oco..oco',
19 '.o......opoooapo',
20 'oco.....oabaaaco',
21 'oco.....oabbbgco',
22 'oao..ooooabbboco',
23 'oabooadadabbwxpo',
24 '.obbdabbbbbcxxo.',
25 '..obbbbbbbbcoo..',
26 '..oabbbbbcbco...',
27 '..occbcbbcoco...',
28 '..ocoococcooco..',
29 '.oco..occo.oco..',
30 '..w....ww...ow..',
31 '................',
32 ],
33 walk1: [
34 '..............o.',
35 '.........o...oco',
36 '........oaooooco',
37 '.o......opbaaapo',
38 'oco.....oabbbgco',
39 'oco.....oabbboco',
40 'oao.oooooabbbwpo',
41 'oaboaadadabcxxxo',
42 '.obbdbbbbbbcooo.',
43 '..obbbbbbbbco...',
44 '...ocbbbbbbco...',
45 '...ococccbbco...',
46 '...ococooobco...',
47 '...ococo.occo...',
48 '....w.w...ww....',
49 '................',
50 ],
51 walk2: [
52 '................',
53 '.........o....o.',
54 '........oco..oco',
55 '.o......opoooapo',
56 'oco.....oabaaaco',
57 'oco.....oabbbgco',
58 'oao..ooooabbboco',
59 'oabooadadabbwxpo',
60 '.obbdabbbbbcxxo.',
61 '..obbbbbbbbcoo..',
62 '..oabbbbbbcco...',
63 '...obccccbco....',
64 '...oacoooobo....',
65 '...occo..occo...',
66 '....ww....ww....',
67 '................',
68 ],
69 walk3: [
70 '..............o.',
71 '.........o...oco',
72 '........oaooooco',
73 '.o......opbaaapo',
74 'oco.....oabbbgco',
75 'oco.....oabbboco',
76 'oao.oooooabbbwpo',
77 'oaboaadadabcxxxo',
78 '.obbdbbbbbbcooo.',
79 '..obbbbbbbbco...',
80 '...ocbbbbcbco...',
81 '...ococcbcoco...',
82 '...ococoococo...',
83 '...ococoococo...',
84 '....w.w..w.ow...',
85 '................',
86 ],
87 done: [
88 '..o.......o.....',
89 '.oao.....oco....',
90 '.oapooooopco....',
91 '.oabbadaaaco....',
92 '.oabbbddbbco....',
93 '.oabbbbbbbco....',
94 '.oabobbbobco..o.',
95 '.oaobobobobo.oco',
96 '..obwwpwwbbbooco',
97 '...obowobbbdboco',
98 '....obbbbbbbdbco',
99 '....oabobbbbbbco',
100 '....owwbwwbbbcco',
101 '....owwbwwbccco.',
102 '....oxxcxxccoo..',
103 '.....ooooooo....',
104 ],
105 failed: [
106 '................',
107 '................',
108 '................',
109 '................',
110 '................',
111 '..o.....o.......',
112 '.oao...oco......',
113 '.oaBCBoaao......',
114 '.oapRCapbbooo...',
115 '.oabBbbbbbdado..',
116 '.oabbbbdbbbbbbo.',
117 '.ooobboobbbbbbco',
118 '..obbpbbbbbbbcco',
119 '.ToccbbbbccccccT',
120 'TT.occdccdccdc..',
121 '.......oooo.....',
122 ],
123 stopped: [
124 '.r..............',
125 '.roo.....oo...o.',
126 '.oaaoooooaco.oao',
127 '.rapbaaaaapooacc',
128 '.oabbbbbbbcooaco',
129 '.oabbbbbbbcooaco',
130 '.oabgbbbgbcooaco',
131 '.oabobbbobbooaco',
132 '.oabbwpwbbbbacco',
133 '..obwwpwwbbbbco.',
134 '...obbobbbbbbco.',
135 '...oabbbbbbbbco.',
136 '...owwbbbwwbcco.',
137 '...owxbbbwwcco..',
138 '...oxxoccxxco...',
139 '....oo.ooooo....',
140 ],
141 quiet: [
142 '................',
143 '..........zzz...',
144 '............z...',
145 '...........z....',
146 '..........zzz.ZZ',
147 '..o.....o......Z',
148 '.oao...oco....ZZ',
149 '.oaboooaao......',
150 '.oapbaapbbooo...',
151 '.oabbbbbbbdado..',
152 '.oabbbbdbbbbbbo.',
153 '.ooobboobbbbbbco',
154 '..obbpbbbbbbbcco',
155 '...occbbbbccccc.',
156 '...occdccdccdc..',
157 '.......oooo.....',
158 ],
159 workflow: [
160 '................',
161 '.....ooooo......',
162 '....olllllo.....',
163 '...ollyylyyo....',
164 '..ollyylyyyyo...',
165 '.ollyylyyylyYo..',
166 '.olyylyyylyyYo..',
167 '.olylyyylyyyYo..',
168 '.olyyyylyyyYYo..',
169 '.olyyylyyyYyYo..',
170 '.olyyyyyyYyYYo..',
171 '..oyYyyyYyYYo...',
172 '...oyYyYyYYo....',
173 '....oYYYYYo.yy..',
174 '.....ooooo....yy',
175 '................',
176 ],
177 group: [
178 '................',
179 '.o...o....o...o.',
180 'oHoooIo..oMooono',
181 'opGHHpo..opNMMpo',
182 'oHGGGGo..orNNNro',
183 'oHooGooooMoNNNoo',
184 'oHGGpIo..oNNpnno',
185 '.oIIIoo..oonnno.',
186 '..oooaoooocooo..',
187 '....oabaaaco....',
188 '....oabbbbbo....',
189 '...oaaobbboco...',
190 '...oaobobocoo...',
191 '....ocwwpxco....',
192 '.....ooccoo.....',
193 '.......oo.......',
194 ],
195 scene: [
196 '.....................................................ZZZZZ......',
197 '........................................................Z.......',
198 '.......................................................Z........',
199 '......................................................Z.........',
200 '.....................................................ZZZZZ......',
201 '................................................................',
202 '................................................ZZZZ............',
203 '..................................................Z.............',
204 '.................................................Z..............',
205 '................................................ZZZZ............',
206 '................................................................',
207 '..............o...........o.................zzz.................',
208 '.............oapoo.....oopco.................z..................',
209 '.............oappaoooooappco................zzz.................',
210 '.............oabbbbaaaaabbco.oooooooooo.........................',
211 '.............oabbbbbbbbbbbbooaadaadaaaaooo......................',
212 '.............oabbbbbbbbbbbbbaadbbbbdbbdbaaooo...................',
213 '.............oabbbbbbbbbbbbbbbbbbbbbbbbdbbbaao..................',
214 '............oaabbbbbbbbbbbbbbbbdbbbdbbbbbbdbbco.................',
215 '............oabobbbbbbbbbobbbbbbbbbbbbbbbbbbbbco................',
216 '............oabbooobbbooobbbbbbbbbbbbbbbbbbbbcco................',
217 '.............obbbbwwwwwbbbbbbbbbbbbbbbbbbbbbbbcco...............',
218 '.............ocbbwwwpwwwbbbbbbbbbbbbbbbbbbbbbbco................',
219 '..............ocbwwowowwbbbbbbbbbbbbbbbbbbbbbbcco...............',
220 '...............oobwwwwwbbbbbbbbbbbbbbbbbbbbbcccco...............',
221 '................oabbbbbbbbbbbbbbbbbbbbbbbccccccco...............',
222 '......oooooooooocccbbbbbbbbbbbbbbbbbbbbcccccccoooooooooooo......',
223 '.....oLLLLLLLLLLoccccccccccccccccccccccccccoooLLLLLLLLLLLLo.....',
224 '....oLLKKKKKKKKKKoococdcccccdcccccdcccccdoocKKKKKKKKKKKKKKko....',
225 '....oLKKKLLkKLLkKLLkKooooooooooooooooooooLLkKLLkKLLkKLLkKKKo....',
226 '...oLLKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKko...',
227 '...oLKKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKKo...',
228 '..oLLKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKko..',
229 '..oLKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKLLkKo..',
230 '.okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkko.',
231 '..oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo..',
232 '...sssssssssssssssssssssssssssssssssssssssssssssssssssssssssss..',
233 '................................................................',
234 '................................................................',
235 '................................................................',
236 ],
237 },
238}
239
240// Fish: swimming, caught on the line, bones (it got away), a bobber (line reeled in),
241// asleep with bubbles; a rowboat for a workflow, a school for a cluster; a night lake.
242const FISH: ArtSet = {
243 pal: {"o": "#1d2b3a", "b": "#3f9fd6", "c": "#2a78ad", "a": "#c4e8f8", "f": "#f29b38", "d": "#c9701f", "g": "#ffffff", "z": "#bfe8ff", "Z": "#6fb7e6", "h": "#b8c0c9", "l": "#8c96a3", "r": "#e5484d", "w": "#fff6ea", "x": "#e0d2c0", "W": "#a8703f", "V": "#6e4424", "B": "#f3ead8", "S": "#4a8fc2", "s": "#2f6c9e", "k": "#d6f0ff", "y": "#ffcf4d", "Y": "#f0a830"},
244 pix: {
245 walk0: [
246 '..............Z.',
247 '................',
248 '...............z',
249 '........oooo....',
250 '.......offffo...',
251 '.....ooobbbboo..',
252 'oo..obbbcbbbbbo.',
253 'ofo.obbcbbbbgobo',
254 'offoobbcbbbbbbbo',
255 'offoobbcbbbbbboo',
256 'ofo.oaacaaaaaao.',
257 'oo...oaaaaaaoo..',
258 '......offoooo...',
259 '.......oo.......',
260 '................',
261 '................',
262 ],
263 walk1: [
264 '.............z..',
265 '...............z',
266 '................',
267 '........oooo....',
268 '.......offffo...',
269 'o....ooobbbboo..',
270 'ofo.obbbcbbbbbo.',
271 'offoobbcbbbbgobo',
272 'offfobbcbbbbbbbo',
273 '.oooobbcbbbbbboo',
274 '....oaacaaaaaao.',
275 '.....oaaaaaaoo..',
276 '......offoooo...',
277 '.......oo.......',
278 '................',
279 '................',
280 ],
281 walk2: [
282 '...............Z',
283 '................',
284 '..............z.',
285 '........oooo....',
286 '.......offffo...',
287 '.....ooobbbboo..',
288 'oo..obbbcbbbbbo.',
289 'ofo.obbcbbbbgobo',
290 'offoobbcbbbbbbbo',
291 'offoobbcbbbbbboo',
292 'ofo.oaacaaaaaao.',
293 'oo...oaaaaaaoo..',
294 '......offoooo...',
295 '.......oo.......',
296 '................',
297 '................',
298 ],
299 walk3: [
300 '...............z',
301 '..............z.',
302 '................',
303 '........oooo....',
304 '.......offffo...',
305 '.....ooobbbboo..',
306 '....obbbcbbbbbo.',
307 '....obbcbbbbgobo',
308 '.oooobbcbbbbbbbo',
309 'offfobbcbbbbbboo',
310 'offooaacaaaaaao.',
311 'ofo..oaaaaaaoo..',
312 'o.....offoooo...',
313 '.......oo.......',
314 '................',
315 '................',
316 ],
317 done: [
318 '...............l',
319 '...y...........l',
320 '..yYy..........l',
321 '...y...........l',
322 '...............l',
323 '........oooo...l',
324 '.......offffo..l',
325 'o....ooobbbboo.l',
326 'ofo.obbbcbbbbbol',
327 'offoobbcbbbbgobh',
328 'offfobbcbbbbbbbh',
329 '.oooobbcbbbbbboo',
330 '....oaacaaaaaao.',
331 '.....oaaaaaaoo..',
332 '......offoooo...',
333 '.......oo.......',
334 ],
335 failed: [
336 '................',
337 '................',
338 '................',
339 '...o.o.o..oooo..',
340 'o.oBoBoBo.oBBBo.',
341 'BooBoBoBooBBBBBo',
342 'BBoBoBoBooBoBBBo',
343 'BBBBBBBBBBBBBBBo',
344 'BBoBoBoBooBBBBBo',
345 'BooBoBoBooBBBBo.',
346 'o.oBoBoBo.oBBo..',
347 '...o.o.o..ooo...',
348 '................',
349 '................',
350 '................',
351 '................',
352 ],
353 stopped: [
354 '................',
355 '.......o........',
356 '.......o........',
357 '......ooo.......',
358 '.....orrro......',
359 '....orgrrro.....',
360 '....orrrrro.....',
361 '....orrrrro.....',
362 '....owwwwwo.....',
363 '....owwwwxo.....',
364 '.....owwxo......',
365 '.kk...ooo...kk..',
366 'kSSkkSSSSSkkSSkk',
367 'SSSSSSSSSSSSSSSS',
368 'SsSSSSsSSSSSsSSS',
369 '................',
370 ],
371 quiet: [
372 '............ZZZ.',
373 '..............Z.',
374 '..........Z..Z..',
375 '............ZZZ.',
376 '................',
377 '........oooo....',
378 '.......offffo...',
379 '.....ooobbbboo..',
380 'oo..obbbcbbbbbo.',
381 'ofo.obbcbbbooobo',
382 'offoobbcbbbbbbbo',
383 'offoobbcbbbbbboo',
384 'ofo.oaacaaaaaao.',
385 'oo...oaaaaaaoo..',
386 '......offoooo...',
387 '.......oo.......',
388 ],
389 workflow: [
390 '................',
391 '.............W..',
392 '............W..l',
393 '...........W...l',
394 '..........W....l',
395 '..........W....l',
396 '.........W.....l',
397 '........W......l',
398 '.......W.......l',
399 'ooooooWooooooo.r',
400 '.oWWWWWWWWWWo..w',
401 '..oVVVVVVVVo....',
402 '...oooooooo.....',
403 '.kk..k...kk...kk',
404 'SSSSSSSSSSSSSSSS',
405 'SsSSSSSsSSSSSsSS',
406 ],
407 group: [
408 '................',
409 '..........ooo...',
410 '........oobbobo.',
411 '........obbbbbo.',
412 '........ooaaao..',
413 '..........ooo...',
414 '...ooo..........',
415 '.ooffofo........',
416 '.offfffo........',
417 '.ooyyyo.........',
418 '...ooo....ooo...',
419 '........oobbobo.',
420 '........obbbbbo.',
421 '........ooaaao..',
422 '..........ooo...',
423 '................',
424 ],
425 scene: [
426 '................................................................',
427 '..............................y.................................',
428 '......yyy...............................................y.......',
429 '.....yy.............y...........................................',
430 '....yy......................................y...................',
431 '....yy..............................W...........................',
432 '....yy............................WW.l..........................',
433 '.....yy.........................WW...l..........................',
434 '......yyy......................W.....ly.........................',
435 '.............................WW......l......................y...',
436 '..............y............WW........l..........................',
437 '..........................W..........l..........................',
438 '........................WW............l.........................',
439 '......................WW..............l.................ZZZZ....',
440 '....................WW................l...................Z.....',
441 '...................W..................l..................Z......',
442 '.................WW...................l.................ZZZZ....',
443 '...............WW.....................l.........................',
444 '.............VV........................l............ZZZ.........',
445 'oooooooooooooooooooooo.................o..............Z.........',
446 'WWWWWWWWWWWWWWWWWWWWWW................ooo............Z..........',
447 'VVVVVVVVVVVVVVVVVVVVVV................oro...........ZZZ.........',
448 'oooooooooooooooooooooo................owo.......................',
449 'kkSVWSkkSSSSkkSSSVWkSSSSkkSSSSkkSSSSkk.o.SkkSSSSkkSSSSkkzSSSkkSS',
450 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSooooSSSSSSSSSS',
451 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSoffffozSSSSSSSS',
452 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSSSSSSooobbbbooSSSSSSSS',
453 'SSSVWSSSSSSSkSSSSVWSSkSSSSSSSSkSSSSSSSSkSSooSSobbbcbbbbbokSSSSSS',
454 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSofoSobbcbbboooboSSSSSS',
455 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSoffoobbcbbbbbbboSSSSSS',
456 'SSSVWSSSSSSSSSSSSVWSSSSSSSSSSSSSSSSSSSSSSSoffoobbcbbbbbbooSSSSSS',
457 'SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSofoSoaacaaaaaaoSSSSSSS',
458 'ssssssssssssssssssssssssssssssssssssssssssoosssoaaaaaaoossssssss',
459 'ssssssssssssssssssssssssssssssssssssssssssssssssoffoooosssssssss',
460 'sssssssssssssssssssssssssssssssssssssssssssssssssoosssssssssssss',
461 'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss',
462 'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss',
463 'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss',
464 'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss',
465 'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss',
466 ],
467 },
468}
469
470// Dogs: trotting, a happy sit, lying down with a tear, told to sit, asleep; a tennis
471// ball for a workflow, the pack's paw print for a cluster; asleep by the dog house.
472const DOG: ArtSet = {
473 pal: {"o": "#2e1f1b", "b": "#d99a52", "a": "#f2c98e", "c": "#a8662f", "d": "#7a4520", "w": "#fff6ea", "x": "#e3cdb8", "p": "#f4899a", "r": "#e5484d", "y": "#ffcf4d", "T": "#c8e04a", "U": "#94ad28", "g": "#ffffff", "z": "#8fb0f0", "Z": "#5f86d8", "R": "#c2413b", "Q": "#8f2b27", "W": "#c08850", "V": "#8a5a30", "k": "#3a2a24", "G": "#6bb34a", "F": "#4d8c35", "L": "#bdb6d3", "K": "#8e87a9"},
474 pix: {
475 walk0: [
476 '................',
477 '.........ooo....',
478 '........obbbo...',
479 '.......odbbbboo.',
480 '.......oddbobbbo',
481 'oo.....oddbbbwwo',
482 'obo.....odbbwwoo',
483 'oo.ooooooobbwpo.',
484 'obooabbbborrry..',
485 '.obbbbbbbbbbwo..',
486 '..obbbbbbbbbwo..',
487 '..obbbbbbbbbo...',
488 '..obco..obco....',
489 '..oco...oco.....',
490 '..ow.....ow.....',
491 '................',
492 ],
493 walk1: [
494 '................',
495 '.........ooo....',
496 '........obbbo...',
497 '.......odbbbboo.',
498 '.......oddbobbbo',
499 '.oo....oddbbbwwo',
500 'obo.....odbbwwoo',
501 'oo.ooooooobbwpo.',
502 'obooabbbborrry..',
503 '.obbbbbbbbbbwo..',
504 '..obbbbbbbbbwo..',
505 '..obbbbbbbbbo...',
506 '...obco.obco....',
507 '....oco.oco.....',
508 '....ow..ow......',
509 '................',
510 ],
511 walk2: [
512 '................',
513 '.........ooo....',
514 '........obbbo...',
515 '.......odbbbboo.',
516 '.......oddbobbbo',
517 'oo.....oddbbbwwo',
518 'obo.....odbbwwoo',
519 'oo.ooooooobbwpo.',
520 'obooabbbborrry..',
521 '.obbbbbbbbbbwo..',
522 '..obbbbbbbbbwo..',
523 '..obbbbbbbbbo...',
524 '.obco....obco...',
525 'oco......oco....',
526 'ow........ow....',
527 '................',
528 ],
529 walk3: [
530 '................',
531 '.........ooo....',
532 '........obbbo...',
533 '.......odbbbboo.',
534 '.......oddbobbbo',
535 'o......oddbbbwwo',
536 'ob......odbbwwoo',
537 'oo.ooooooobbwpo.',
538 'obooabbbborrry..',
539 '.obbbbbbbbbbwo..',
540 '..obbbbbbbbbwo..',
541 '..obbbbbbbbbo...',
542 '...obco.obco....',
543 '...oco..oco.....',
544 '...ow...ow......',
545 '................',
546 ],
547 done: [
548 '..oo........oo..',
549 '.oddo......oddo.',
550 '.oddooooooooddoo',
551 '.oddbbbbbbbbddo.',
552 '.odbbobbbbobbdo.',
553 '..obbobbbbobbo..',
554 '..obbbbwwbbbbo..',
555 '...obbwoowbbo...',
556 '...obbwwwwbbo...',
557 '....orrpprro....',
558 '...obbwppwbbo...',
559 '..obbbwwwwbbbo..',
560 '..obbbwwwwbbbo..',
561 '..obobwwwwbobo..',
562 '..owwbbbbbbwwo..',
563 '...oooooooooo...',
564 ],
565 failed: [
566 '................',
567 '................',
568 '................',
569 '................',
570 '................',
571 '................',
572 '..........oooo..',
573 '.........obbbbo.',
574 '........oddbbbbo',
575 '.oo.....oddboobo',
576 'obooooooodbzbwwo',
577 '.obbbbbbbbbzbwoo',
578 '.obbbbbbbbbbbwo.',
579 '.owbbbbbbbbbbwwo',
580 'oowwooooooooowwo',
581 '.oo.......z.ooo.',
582 ],
583 stopped: [
584 '.........ooo....',
585 '........obbbo...',
586 '.......odbbbboo.',
587 '.......oddbobbbo',
588 '.......oddbbbwwo',
589 '........odbbwwoo',
590 '........obbbwwo.',
591 '........orrryo..',
592 '.......obbbbwo..',
593 '......obbbbbwo..',
594 '.....obbbbbbwo..',
595 'oo..obbbbbbbwo..',
596 'obooobbbbbbbo...',
597 '.obbbbbcbbbco...',
598 '..obbbcowwcwwo..',
599 '...ooooooooooo..',
600 ],
601 quiet: [
602 '...........ZZZZ.',
603 '.............Z..',
604 '.......ZZZ..Z...',
605 '.........Z.ZZZZ.',
606 '........Z.......',
607 '.......ZZZ......',
608 '..........oooo..',
609 '.........obbbbo.',
610 '........oddbbbbo',
611 '.oo.....oddboobo',
612 'obooooooodbbbwwo',
613 '.obbbbbbbbbbbwoo',
614 '.obbbbbbbbbbbwo.',
615 '.owbbbbbbbbbbwwo',
616 'oowwooooooooowwo',
617 '.oo.........ooo.',
618 ],
619 workflow: [
620 '................',
621 '.....oooooo.....',
622 '...ooTTTTTToo...',
623 '..oTTgTTTTTTTo..',
624 '..oTggTTTTTTTo..',
625 '.oTTTggTTTTTTUo.',
626 '.oTTTTggTTTTTUo.',
627 '.oTTTTTgggTTTUo.',
628 '.oTTTTTTTTggTUo.',
629 '.oTTTTTTTTTTgUo.',
630 '.oTTTTTTTTTTggo.',
631 '..oTTTTTTTTTUo..',
632 '..oUTTTTTTTUUo..',
633 '...ooUUUUUUoo...',
634 '.....oooooo.....',
635 '................',
636 ],
637 group: [
638 '................',
639 '.....oo...oo....',
640 '....obbo.obbo...',
641 '....obbo.obbo...',
642 '.oo..oo...oo.oo.',
643 'obbo.........obo',
644 'obbo..oooo...obo',
645 '.oo..obbbbo...o.',
646 '....obbbbbbo....',
647 '...obbbbbbbbo...',
648 '...obbbbbbbbo...',
649 '...obbbbbbbbo...',
650 '....obbooobbo...',
651 '.....oo...oo....',
652 '................',
653 '................',
654 ],
655 scene: [
656 '................................................................',
657 '................................................................',
658 '................................................................',
659 '........................oQQQQo..................................',
660 '......................oRRRRRRRRo................................',
661 '....................oRRRRRRRRRRRRo..............................',
662 '..................oRRRRRRRRRRRRRRRRo............................',
663 '................oRRRRRRRRRRRRRRRRRRRRo..........................',
664 '..............oRRRRRRRRRRRRRRRRRRRRRRRRo........................',
665 '............oRRRRRRRRRRRRRRRRRRRRRRRRRRRRo......................',
666 '..........oRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRo....................',
667 '........oRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRo..................',
668 '......oRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRo................',
669 '....QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQZZZZ............',
670 '.......oWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWo...Z.............',
671 '.......oVVVVVVVVVVVVVVVVVoooVVVVVVVVVVVVVVVVVVo..Z..............',
672 '.......oWWWWWWWWWWWWWWWWWoyoWWWWWWWWWWWWWWWWWWo.ZZZZ............',
673 '.......oWWWWWWWWWWWWWWWWWoooWWWWWWWWWWWWWWWWZZZ.................',
674 '.......oVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVZ.................',
675 '.......oWWWWWWWWWWWWWWkkkkkkkkkkWWWWWWWWWWWWWZo.................',
676 '.......oWWWWWWWWWWWWWWkkkkkkkkkkWWWWWWWWWWWWZZZ.................',
677 '.......oVVVVVVVVVVVVkkkkkkkkkkkkkkVVVVVVVVVVVVo.................',
678 '.......oWWWWWWWWWWWWkkkkkkkkkkkkkkWWWWWWWWWoooo.................',
679 '.......oWWWWWWWWWWWWkkkkkkkkkkkkkkWWWWWWWWobbbbo................',
680 '.......oVVVVVVVVVVVVkkkkkkkkkkkkkkVVVVVVVoddbbbbo...............',
681 '.......oWWWWWWWWWWWWkkkkkkkkkkkkkkooWWWWWoddboobo...............',
682 '.......oWWWWWWWWWWWWkkkkkkkkkkkkkobooooooodbbbwwo...............',
683 '.......oVVVVVVVVVVVVkkkkkkkkkkkkkkobbbbbbbbbbbwoo......ooo......',
684 '........oooooo..WWWWkkkkkkkkkkkkkkobbbbbbbbbbbwo......oTTTo.....',
685 '.......oLLLLLLo.WWWWkkkkkkkkkkkkkkowbbbbbbbbbbwwo.....oTgTo.....',
686 '..G....oKKKKKKo.VVVVkkkkkkkkkkkkkoowwooooooooowwo...G.oUUUo...G.',
687 '.G......oooooo..WWWWkkkkkkkkkkkkkkooWWWWWWWWWooo...G...ooo...G..',
688 'GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG',
689 'GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG',
690 'GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG',
691 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
692 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
693 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
694 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
695 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
696 ],
697 },
698}
699
700export const ART: Record<ArtName, ArtSet> = { kitty: KITTY, fish: FISH, dog: DOG }
701