Progress bar above the prompt for delegated work, plus an agents panel (/agents-info) that opens for any subagent: running, finished and planned subagents with…

A Claude Code mod, forked from savvy-progress (MIT): a progress bar above the prompt and a live panel of subagents.
/agents-info toggles it): opens by itself when any subagent starts, once per busy spell (a run started while none was running) or once per reported flow, so closing it sticks until then. Shows the session's subagents, across flows: running, the latest ten finished (a +N earlier button opens the rest) and the planned ones, with model, effort, task progress (percent and steps, once the run reports them), context, estimated cost and time; the totals count every run.View button on the desktop) puts its transcript in the main view, and on the run in view brings the main conversation back; ↩ Main conversation (m) does too. The run in view is marked.▸ button (the title on the terminal) opens its agents beneath it. Its agents keep their prompts as the script wrote them, and the progress bar counts the run once.c collapses it, f folds the finished runs and e opens the earlier ones. On the terminal, s ([ ○ ]) keeps each run to its name and bar, without the grey rows; press it again ([ ● ]) for the details. There the buttons are framed, [ − ] collapsing and [ + ] expanding, so no key prefix (c:) is drawn before their labels. The ? at the top left of the terminal's pane lists these keys. Esc closes it, from the pane or from an idle, empty prompt.Opus 5.5 high | careful, the tier in the panel's language); the bar with the task's steps; then context share, tokens, cost and time.progress, sits under any other plugin's band, and steps aside 10 seconds after the flow is reported finished.careful, plugin:careful) wins; otherwise the model decides: Fable is fable, Opus is heavy at xhigh or max effort and careful below, Sonnet is medium, Haiku is light.mcp__agents-progress__progress: the delegating session reports the plan, phase and accepted tasks.mcp__agents-progress__step: a subagent reports its own steps (done, total, note). From Claude Code 2.1.293 it is listed from the first prompt, so a subagent calls it without a ToolSearch first. The mod adds a paragraph asking for it to every subagent's prompt, except a workflow's agents; a run that does not report shows its context fill in grey.agents-progress:reportar-progresso: Claude loads it before any delegation to report the plan and each accepted task. It is not in the / menu.Cost is a rough estimate from token counts and the PRICES table in hooks/register.tsx, not a bill.
Set them in /config.
language: auto (default), en, pt or ru.stepBrief: on (default) briefs every subagent to report its steps; off leaves prompts as written. Each report is one more model request in the subagent.At the prompt of a Claude Code session in a terminal:
/plugin install agents-progress --marketplace fabiopbarbieri/agents-progress
Answer y to add the marketplace, then pick a scope. Or from a shell:
claude plugin marketplace add fabiopbarbieri/agents-progress
claude plugin install agents-progress@agents-progress
The Claude desktop app has no /plugin command: install from a terminal, and the mod loads in the app's local sessions too.
The options are optional: the install may say they are not set, and their defaults apply until you change them in /config.
To work on it, add your clone as the marketplace instead (claude plugin marketplace add <path to the clone>): the entry's source is relative, so the session reads the plugin from that folder. Edit, then /reload-plugins.
claude plugin validate . --strict
claude plugin test .
npx -p typescript@5 tsc -p .
claude plugin test runs tests/*.test.ts against the engine's own host, on the terminal and desktop surfaces; tests/kit.ts stands for the engine beneath the mod. It checks the hooks and the trees they return, not how a surface paints them.
tsc reads the API types the engine lays in .claude-plugin/types/ (ignored by Git) when an interactive session loads the mod from its folder, as claude --plugin-dir . does; a claude -p run does not lay them. Tests stay out of it, as their fixtures are partial.
Semantic Versioning 2.0.0, with version in .claude-plugin/plugin.json as the one source:
$.state contract in types/index.d.ts, a userConfig option removed or renamed, the /agents-info command.To release: move version, add its section to CHANGELOG.md, commit, then claude plugin tag . --push (tag agents-progress--v<version>) and a GitHub release from that section.
hooks/register.tsx 1703 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, Timer } from 'claude-code'
3
4import type { AgentRun, AgentStatus, Flow, Panel, Phase, PlannedTask } from '../types'
5
6const flow = atom({ plugin: 'agents-progress', key: 'flow' } as const, null)
7const agents = atom({ plugin: 'agents-progress', key: 'agents' } as const, [])
8const panel = atom({ plugin: 'agents-progress', key: 'panel' } as const, {
9 isCompact: false,
10 isDoneCollapsed: false,
11 autoOpenedFor: '',
12})
13const now = atom({ plugin: 'agents-progress', key: 'now' } as const, 0)
14const workflows = atom({ plugin: 'agents-progress', key: 'workflows' } as const, {})
15
16// `update` writes, and so redraws every reader, even when the value stays the same:
17// these write only a change. One per value, as the engine's scan reads each by name.
18const same = (a: unknown, b: unknown): boolean => a === b || JSON.stringify(a) === JSON.stringify(b)
19
20async function patchFlow($: EngineInterface, change: (f: Flow | null) => Flow | null): Promise<Flow | null> {
21 const held = await read($, flow)
22 return same(change(held), held) ? held : update($, flow, change)
23}
24
25async function patchAgents($: EngineInterface, change: (list: AgentRun[]) => AgentRun[]): Promise<AgentRun[]> {
26 const held = await read($, agents)
27 return same(change(held), held) ? held : update($, agents, change)
28}
29
30const TOOL = 'mcp__agents-progress__progress'
31const STEP_TOOL = 'mcp__agents-progress__step'
32const PANE = 'agents-progress'
33const QUIET_TOOLS = new Set([TOOL, STEP_TOOL])
34const PHASES: readonly Phase[] = ['plan', 'design', 'delegate', 'review', 'close']
35// How long a finished flow's band stays before it steps aside by itself.
36const FINISHED_LINGER_MS = 10_000
37const ACCENT = '#8f8cf4'
38const DONE = '#5fbf8f'
39
40type ProgressInput = {
41 title?: string
42 total?: number
43 done?: number
44 phase?: Phase
45 finished?: boolean
46 tasks?: { title?: string; tier?: string; after?: number[] }[]
47}
48
49// ---------------------------------------------------------------------------
50// Language: the `language` option, else Claude Code's `language` setting, else the
51// process locale; English when nothing says Portuguese or Russian.
52
53type Lang = 'en' | 'pt' | 'ru'
54
55const STRINGS = {
56 en: {
57 pane: 'Agents',
58 cost: 'Cost',
59 tokens: 'Tokens',
60 time: 'Time',
61 collapse: 'Collapse',
62 expand: 'Expand',
63 keysWhen: 'With the pane focused (ctrl+x tab):',
64 keys: { s: 'simple view', c: 'collapse', f: 'finished', e: 'earlier', m: 'main conversation', Esc: 'close' },
65 running: 'Running',
66 finished: 'Finished',
67 earlier: 'earlier',
68 fewer: 'Show fewer',
69 planned: 'Planned',
70 empty: 'No subagents yet.',
71 round: 'round',
72 failed: 'error',
73 after: 'after',
74 tokensWord: 'tokens',
75 agentsCount: 'agents',
76 isRunning: 'running',
77 isFinished: 'finished',
78 isPlanned: 'planned',
79 opened: 'Agents panel opened.',
80 closed: 'Agents panel closed.',
81 done: 'Done',
82 plan: 'Plan',
83 design: 'Design',
84 tasks: 'Tasks',
85 review: 'Review',
86 busy: 'Tasks running',
87 flow: 'Progress',
88 view: 'View',
89 main: 'Main conversation',
90 inView: 'in view',
91 gone: "This run's transcript is gone: Claude Code lets a run go about 30 seconds after it ends.",
92 tiers: { fable: 'fable', heavy: 'heavy', careful: 'careful', medium: 'medium', light: 'light' },
93 },
94 pt: {
95 pane: 'Agentes',
96 cost: 'Custo',
97 tokens: 'Tokens',
98 time: 'Tempo',
99 collapse: 'Recolher',
100 expand: 'Expandir',
101 keysWhen: 'Com o painel focado (ctrl+x tab):',
102 keys: { s: 'simplificar', c: 'recolher', f: 'concluídos', e: 'anteriores', m: 'conversa principal', Esc: 'fechar' },
103 running: 'Em execução',
104 finished: 'Concluídos',
105 earlier: 'anteriores',
106 fewer: 'Mostrar menos',
107 planned: 'Planejados',
108 empty: 'Nenhum subagente ainda.',
109 round: 'rodada',
110 failed: 'erro',
111 after: 'depois de',
112 tokensWord: 'tokens',
113 agentsCount: 'agentes',
114 isRunning: 'em execução',
115 isFinished: 'concluído',
116 isPlanned: 'planejada',
117 opened: 'Painel de agentes aberto.',
118 closed: 'Painel de agentes fechado.',
119 done: 'Concluído',
120 plan: 'Plano',
121 design: 'Design',
122 tasks: 'Tarefas',
123 review: 'Revisão',
124 busy: 'Tarefas em execução',
125 flow: 'Progresso',
126 view: 'Ver',
127 main: 'Conversa principal',
128 inView: 'em vista',
129 gone: 'O transcript deste run não está mais disponível: o Claude Code libera um run cerca de 30 s depois que ele termina.',
130 tiers: { fable: 'fable', heavy: 'pesado', careful: 'cuidadoso', medium: 'médio', light: 'leve' },
131 },
132 ru: {
133 pane: 'Агенты',
134 cost: 'Стоимость',
135 tokens: 'Токены',
136 time: 'Время',
137 collapse: 'Свернуть',
138 expand: 'Развернуть',
139 keysWhen: 'Когда панель в фокусе (ctrl+x tab):',
140 keys: { s: 'упростить', c: 'свернуть', f: 'завершённые', e: 'ранее', m: 'основной разговор', Esc: 'закрыть' },
141 running: 'Работают',
142 finished: 'Завершены',
143 earlier: 'ранее',
144 fewer: 'Показать меньше',
145 planned: 'Запланированы',
146 empty: 'Субагентов пока нет.',
147 round: 'раунд',
148 failed: 'ошибка',
149 after: 'после',
150 tokensWord: 'токенов',
151 agentsCount: 'агентов',
152 isRunning: 'работает',
153 isFinished: 'завершён',
154 isPlanned: 'запланирована',
155 opened: 'Панель агентов открыта.',
156 closed: 'Панель агентов закрыта.',
157 done: 'Готово',
158 plan: 'План',
159 design: 'Дизайн',
160 tasks: 'Задачи',
161 review: 'Ревью',
162 busy: 'Задачи в работе',
163 flow: 'Прогресс',
164 view: 'Открыть',
165 main: 'Основной диалог',
166 inView: 'открыт',
167 gone: 'Транскрипт этого запуска больше недоступен: Claude Code отпускает запуск примерно через 30 секунд после завершения.',
168 tiers: { fable: 'fable', heavy: 'тяжёлый', careful: 'тщательный', medium: 'средний', light: 'лёгкий' },
169 },
170} as const
171
172// Module scope is fine here: session.start sets it again on every (re)load.
173let lang: Lang = 'en'
174// $.ui.view came with Claude Code 2.1.300; the desktop app runs its own engine, which
175// may lag. Set in session.start, as lang is.
176let canView = true
177
178const VIEW_SINCE = [2, 1, 300]
179// `isDeferred` on $.tool.register came with 2.1.293.
180const LISTED_SINCE = [2, 1, 293]
181
182async function engineSince($: EngineInterface, release: number[]): Promise<boolean> {
183 try {
184 const { base, version } = await $.session.version()
185 const parts = (base ?? version).split(/[.-]/).slice(0, 3).map(Number)
186 // A version not spelled as a release is a build of its own: assume it has the call.
187 if (parts.length < 3 || parts.some(isNaN)) return true
188 for (const [i, since] of release.entries()) if (parts[i] !== since) return parts[i]! > since
189 return true
190 } catch {
191 return false
192 }
193}
194
195const engineHasView = ($: EngineInterface): Promise<boolean> => engineSince($, VIEW_SINCE)
196const tr = () => STRINGS[lang]
197
198const langOf = (v: unknown): Lang => {
199 if (typeof v !== 'string') return 'en'
200 if (/^(ru|russian|рус)/i.test(v.trim())) return 'ru'
201 if (/^(pt|portugu)/i.test(v.trim())) return 'pt'
202 return 'en'
203}
204
205async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
206 if (option === 'en' || option === 'pt' || option === 'ru') return option
207 try {
208 const settings = (await $.settings.read()) as Record<string, unknown>
209 if (typeof settings.language === 'string' && settings.language.trim()) return langOf(settings.language)
210 } catch {
211 // No settings: fall through to the locale.
212 }
213 const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
214 return langOf(locale)
215}
216
217const blank = (): Flow => ({
218 title: tr().flow,
219 total: 0,
220 done: 0,
221 phase: 'plan',
222 isFinished: false,
223 tasks: [],
224})
225
226const isNewFlow = (prev: Flow | null, input: ProgressInput): boolean =>
227 !prev || prev.isFinished || (input.title !== undefined && input.title.trim() !== prev.title)
228
229const cleanTasks = (tasks: ProgressInput['tasks']): PlannedTask[] | undefined =>
230 tasks
231 ?.filter(t => t.title?.trim())
232 .map(t => ({
233 title: (t.title ?? '').trim(),
234 tier: (t.tier ?? '').trim().toLowerCase(),
235 after: (t.after ?? []).filter(n => Number.isInteger(n) && n > 0),
236 }))
237
238const merge = (prev: Flow | null, input: ProgressInput): Flow => {
239 // A new title means a new flow: never carry counters over from an earlier one.
240 const base = isNewFlow(prev, input) || !prev ? blank() : { ...blank(), ...prev }
241 const tasks = cleanTasks(input.tasks) ?? base.tasks
242 const total = Math.max(0, Math.round(input.total ?? (input.tasks ? tasks.length : base.total)))
243 const done = Math.min(total || Infinity, Math.max(0, Math.round(input.done ?? base.done)))
244 const phase = input.phase && PHASES.includes(input.phase) ? input.phase : base.phase
245 return {
246 ...base,
247 title: input.title?.trim() || base.title,
248 total,
249 done,
250 phase: input.finished ? 'close' : phase,
251 isFinished: input.finished === true,
252 tasks,
253 }
254}
255
256// What every subagent's brief gets, so the pane draws the task's own bar instead of
257// its context fill. In English, as the tools' own descriptions are.
258const STEP_BRIEF =
259 'Report your progress with `mcp__agents-progress__step` (if it is listed only by name, load it first with ' +
260 'ToolSearch `select:mcp__agents-progress__step`): right after reading this brief, call it with `total` (your plan ' +
261 'in 3 to 8 steps) and `done: 0`; call it again with the new `done` and a short `note` as each step finishes.'
262
263const briefed = (prompt: string, isOn: boolean): string =>
264 !isOn || prompt.includes(STEP_TOOL) ? prompt : `${prompt}\n\n${STEP_BRIEF}`
265
266// Runs still at work. The Agent tool answers as soon as a background run starts,
267// so only the runs' own status says how many are out.
268const runningOf = (list: AgentRun[]): number => list.filter(a => a.status === 'running').length
269
270const label = (f: Flow, running: number): string => {
271 const s = tr()
272 if (f.isFinished) return s.done
273 if (f.phase === 'plan') return s.plan
274 if (f.phase === 'design') return s.design
275 const isReview = f.phase === 'review'
276 // Without a plan there is no x/y, only how many run now: "Tarefas em execução: 2".
277 if (!f.total) return `${isReview ? s.review : s.busy}: ${running}`
278 return `${isReview ? s.review : s.tasks} ${f.done}/${f.total}`
279}
280
281const ratio = (f: Flow): number => (f.isFinished ? 1 : f.total ? f.done / f.total : 0)
282
283// Deterministic noise so the dither does not shimmer between redraws.
284const noise = (x: number, y: number): number => {
285 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
286 return s - Math.floor(s)
287}
288
289// The whole row is one SVG: the desktop wraps sibling elements onto new lines,
290// so title, bar, percent and the crab live in one drawing; only the count and
291// the dismiss are Buttons beside it.
292const H = 22
293const BAR_H = 16
294const CRAB_W = 26
295const CELL = 3
296const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
297
298const xml = (s: string): string =>
299 s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c)
300
301const clip = (s: string, max: number): string => (s.length > max ? s.slice(0, Math.max(1, max - 1)) + '…' : s)
302
303// Rough advance of system UI text, in em; good enough to size the title's slot.
304const charEm = (ch: string): number =>
305 /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-ZА-ЯЁmwшщжюМШЩЖЮ@%]/.test(ch) ? 0.72 : 0.56
306
307const textWidth = (s: string, size: number): number => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
308
309// Cuts `s` to fit `maxW` pixels, with an ellipsis when it had to cut.
310const fitText = (s: string, size: number, maxW: number): string => {
311 if (textWidth(s, size) <= maxW) return s
312 let out = ''
313 for (const ch of s) {
314 if (textWidth(out + ch + '…', size) > maxW) break
315 out += ch
316 }
317 return out + '…'
318}
319
320const rowSvg = (f: Flow, W: number, running: number): string => {
321 const isWorking = running > 0
322 // The title takes what it needs, up to 40% of the row; the bar takes the rest.
323 const title = fitText(f.title, 13, Math.max(60, W * 0.4))
324 const BAR_X = Math.round(16 + textWidth(title, 13) + 12)
325 const BAR_W = Math.max(60, W - BAR_X - 46 - CRAB_W)
326 const color = f.isFinished ? DONE : ACCENT
327 const y0 = (H - BAR_H) / 2
328 const fillW = Math.round(BAR_W * ratio(f))
329 const runW = f.total ? Math.round((BAR_W * Math.min(f.total, f.done + running)) / f.total) : 0
330 // Each layer's cells go into four paths, one per twinkle group: four animated
331 // elements however wide the bar, where every cell was one before.
332 const dots = ['', '', '', '']
333 const faint = ['', '', '', '']
334 const cell = (x: number, y: number, size: number) => `M${x} ${y}h${size}v${size}h${-size}z`
335
336 // Dithered fill: sparse at the start, dense toward the head.
337 const cols = Math.floor(fillW / CELL)
338 const rows = Math.floor(BAR_H / CELL)
339 for (let c = 0; c < cols; c++) {
340 const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
341 for (let r = 0; r < rows; r++) {
342 if (noise(c, r) < density) dots[Math.floor(noise(r, c) * 4)] += cell(c * CELL + 1, r * CELL + 1, 2)
343 }
344 }
345 // Handed to workers, not yet accepted: a faint second layer.
346 for (let c = cols; c < Math.floor(runW / CELL); c++) {
347 for (let r = 0; r < rows; r++) {
348 if (noise(c + 7, r + 3) < 0.2) faint[Math.floor(noise(r + 5, c) * 4)] += cell(c * CELL + 1, r * CELL + 1, 1.7)
349 }
350 }
351
352 const ticks: string[] = []
353 for (let i = 1; i < f.total; i++) {
354 const x = Math.round((BAR_W * i) / f.total)
355 if (x > fillW + 4) ticks.push(`<rect x="${x}" y="${BAR_H / 2 - 4}" width="1.5" height="8" rx="0.75"/>`)
356 }
357
358 const text = label(f, running)
359 const pillW = Math.round(18 + text.length * 6.6)
360 const pillX = Math.max(0, Math.min(BAR_W - pillW, fillW - pillW))
361 const percent = `${Math.round(ratio(f) * 100)}%`
362 const walker = crab(W - CRAB_W + 1, 0, 'other', false, isWorking, 0.8)
363 const layer = (groups: string[]) => groups.map((d, k) => (d ? `<path class="t${k}" d="${d}"/>` : '')).join('')
364 // Pixels twinkle in four out-of-phase groups while runs are at work; otherwise the bar stands still.
365 const twinkle =
366 isWorking && !f.isFinished
367 ? `.t0,.t1,.t2,.t3{animation:tw 2.2s ease-in-out infinite}
368.t1{animation-duration:2.8s;animation-delay:-.7s}.t2{animation-duration:1.9s;animation-delay:-1.3s}.t3{animation-duration:3.3s;animation-delay:-.4s}
369@keyframes tw{0%,100%{opacity:1}50%{opacity:0.3}}
370@media (prefers-reduced-motion: reduce){.t0,.t1,.t2,.t3{animation:none}}`
371 : ''
372
373 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
374<style>
375.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#b4b4b0}
376@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#5a5a5a}}
377${twinkle}
378</style>
379<defs><clipPath id="c"><rect x="0" y="0" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath></defs>
380<circle cx="5" cy="${H / 2}" r="4" fill="${color}"/>
381<text class="t" x="16" y="${H / 2 + 4.5}" font-family="${FONT}" font-size="13" font-weight="500">${xml(title)}</text>
382<g transform="translate(${BAR_X},${y0})">
383<rect class="k" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/>
384<g clip-path="url(#c)">
385<g fill="${color}">${layer(dots)}</g>
386<g fill="${color}" opacity="0.45">${layer(faint)}</g>
387<g class="tk">${ticks.join('')}</g>
388</g>
389<rect x="${pillX}" width="${pillW}" height="${BAR_H}" rx="${BAR_H / 2}" fill="${color}"/>
390<text x="${pillX + pillW / 2}" y="${BAR_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11" font-weight="600" fill="#ffffff">${xml(text)}</text>
391</g>
392<text class="m" x="${W - CRAB_W - 6}" y="${H / 2 + 4.5}" text-anchor="end" font-family="${FONT}" font-size="12.5" font-variant-numeric="tabular-nums">${percent}</text>
393${crabCss(walker)}${walker}
394</svg>`
395}
396
397const barText = (f: Flow, width: number): string => {
398 const filled = Math.round(width * ratio(f))
399 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
400}
401
402// ---------------------------------------------------------------------------
403// Agents panel: every subagent of the session, plus the tasks the flow planned.
404
405const TIER_COLOR: Record<string, string> = {
406 fable: '#7F77DD',
407 heavy: '#D85A30',
408 careful: '#BA7517',
409 medium: '#378ADD',
410 light: '#1D9E75',
411 other: '#888780',
412}
413
414const colorOf = (tier: string): string => TIER_COLOR[tier] ?? '#888780'
415
416const TIER_MODEL: Record<string, string> = {
417 fable: 'Fable',
418 heavy: 'Opus',
419 careful: 'Opus',
420 medium: 'Sonnet',
421 light: 'Haiku',
422}
423
424// USD per million tokens: input, output, cache read, cache write (5-minute TTL).
425// The engine reports tokens, not money, so the panel's cost is an estimate.
426const PRICES: [RegExp, [number, number, number, number]][] = [
427 [/fable|mythos/, [10, 50, 0.25, 12.5]],
428 [/opus-5-5/, [4, 20, 0.2, 5]],
429 [/opus/, [5, 25, 0.5, 6.25]],
430 [/sonnet/, [2, 10, 0.2, 2.5]],
431 [/haiku/, [1, 5, 0.1, 1.25]],
432]
433
434type Usage = {
435 input_tokens: number
436 output_tokens: number
437 cache_read_input_tokens: number
438 cache_creation_input_tokens: number
439}
440
441const priceOf = (model: string): [number, number, number, number] =>
442 PRICES.find(([re]) => re.test(model.toLowerCase()))?.[1] ?? [4, 20, 0.2, 5]
443
444const costOf = (model: string, u: Usage): number => {
445 const [i, o, r, w] = priceOf(model)
446 return (
447 ((u.input_tokens || 0) * i +
448 (u.output_tokens || 0) * o +
449 (u.cache_read_input_tokens || 0) * r +
450 (u.cache_creation_input_tokens || 0) * w) /
451 1e6
452 )
453}
454
455const windowOf = (model: string): number => (/haiku/i.test(model) ? 200_000 : 1_000_000)
456
457// What each tier runs on, for planned tasks that have no run yet.
458// A run takes its tier from an agent type named after one (`careful`, `plugin:careful`), else from its model: Fable is fable, Opus heavy at xhigh or max
459// effort and careful below, Sonnet medium, Haiku light.
460const tierOf = (type: string, model = '', effort = ''): string => {
461 const named = type.replace(/^[^:]*:/, '').toLowerCase()
462 if (named in TIER_MODEL) return named
463 const m = model.toLowerCase()
464 if (/fable|mythos/.test(m)) return 'fable'
465 if (/opus/.test(m)) return /xhigh|max/.test(effort) ? 'heavy' : 'careful'
466 if (/sonnet/.test(m)) return 'medium'
467 if (/haiku/.test(m)) return 'light'
468 return 'other'
469}
470
471const tierOfRun = (a: AgentRun): string => tierOf(a.type, a.model, a.effort)
472
473const modelName = (id: string): string => {
474 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
475 const [, family = '', major = '', minor] = m ?? []
476 if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
477 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
478}
479
480const norm = (s: string): string => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
481
482const fmtTokens = (n: number): string =>
483 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
484
485const fmtCost = (usd: number): string => `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
486
487const fmtTime = (ms: number): string => {
488 const s = Math.max(0, Math.round(ms / 1000))
489 const h = Math.floor(s / 3600)
490 const m = Math.floor((s % 3600) / 60)
491 const ss = String(s % 60).padStart(2, '0')
492 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
493}
494
495const elapsed = (a: AgentRun, at: number): number => (a.endedAt ?? Math.max(at, a.startedAt)) - a.startedAt
496
497type Planned = PlannedTask & { n: number }
498
499// The runs started since the flow began: earlier runs of the session are not its tasks.
500const runsOf = (f: Flow, list: AgentRun[]): AgentRun[] => list.filter(a => a.startedAt >= (f.startedAt ?? 0))
501
502const plannedOf = (f: Flow | null, list: AgentRun[]): Planned[] => {
503 if (!f || f.isFinished) return []
504 const started = new Set(runsOf(f, list).map(a => norm(a.description)))
505 return (f.tasks ?? []).map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(norm(t.title)))
506}
507
508// The time some run was at work: runs side by side count once, and the idle spells
509// between them (the session keeps its runs across flows) not at all.
510const busyTime = (list: AgentRun[], at: number): number => {
511 const spans = list.map(a => [a.startedAt, a.endedAt ?? Math.max(at, a.startedAt)] as const).sort((x, y) => x[0] - y[0])
512 let total = 0
513 let end = -Infinity
514 for (const [from, to] of spans) {
515 if (to <= end) continue
516 total += to - Math.max(from, end)
517 end = to
518 }
519 return total
520}
521
522const totals = (list: AgentRun[], at: number) => {
523 const cost = list.reduce((s, a) => s + a.costUsd, 0)
524 const tokens = list.reduce((s, a) => s + a.tokens, 0)
525 return { cost, tokens, time: busyTime(list, at) }
526}
527
528// --- desktop drawings: each row is one SVG, as the band above the prompt is.
529
530const PANE_CSS = `<style>
531.t{fill:#1f1f1f}.s{fill:#6b6b68}.m{fill:#9a9a96}.k{fill:#ecebe8}.ln{stroke:#e4e4e1}.tile{fill:#f4f3f0}
532@media (prefers-color-scheme: dark){.t{fill:#ececec}.s{fill:#a8a8a4}.m{fill:#7d7d79}.k{fill:#2c2c2b}.ln{stroke:#333331}.tile{fill:#262625}}
533.live{animation:p 1.6s ease-in-out infinite}@keyframes p{50%{opacity:.3}}
534@media (prefers-reduced-motion: reduce){.live{animation:none}}
535</style>`
536
537// Pixel Clawd from DockCrab (Clawdy): a 24×18 crab on a 30×28 grid, one costume per tier.
538// The body keeps the brand clay; the tier's color lives in the costume's accent.
539const CLAY = '#D97757'
540const INK = '#1F1E1D'
541
542// `cls` puts a pixel in a named group: `bd` (the default) is the body and its
543// costume, `la`/`lb` the leg pairs, anything else a prop with its own motion.
544type Fill = (x: number, y: number, w: number, h: number, c: string, cls?: string) => void
545
546const stamp = (f: Fill, x: number, y: number, rows: string[], map: Record<string, string>, cls?: string): void =>
547 rows.forEach((row, dy) => [...row].forEach((ch, dx) => map[ch] && f(x + dx, y + dy, 1, 1, map[ch] ?? '', cls)))
548
549// `armCls` lets a raised claw travel with the prop it holds.
550const crabBody = (f: Fill, armFront = 0, armCls?: string): void => {
551 f(7, 10, 16, 12, CLAY)
552 f(3, 14, 4, 4, CLAY)
553 f(23, 14 + armFront, 4, 4, CLAY, armCls)
554 f(9, 12, 2, 2, INK)
555 f(19, 12, 2, 2, INK)
556 f(7, 22, 2, 4, CLAY, 'la')
557 f(17, 22, 2, 4, CLAY, 'la')
558 f(11, 22, 2, 4, CLAY, 'lb')
559 f(21, 22, 2, 4, CLAY, 'lb')
560}
561
562// Pure CSS, run by the compositor: no redraws. Periods divide one second, so the
563// once-a-second redraw of a running row restarts them in phase. Every crab walks;
564// each costume adds its prop's own motion on top. A drawing carries only the rules
565// of the costumes walking in it, and none when no crab walks.
566const WALK_CSS = `.run .la{animation:st .5s steps(1) infinite}.run .lb{animation:st .5s steps(1) infinite -.25s}
567.run .bd{animation:bob .5s steps(1) infinite -.125s}
568.run g{transform-box:fill-box}
569@keyframes st{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}
570@keyframes blink{50%{opacity:.15}}
571@media (prefers-reduced-motion: reduce){.run,.run g{animation:none!important}}`
572
573const COSTUME_CSS: Record<string, string> = {
574 fable: `.c-fable.run{animation:float 1s ease-in-out infinite}
575.c-fable.run .la,.c-fable.run .lb,.c-fable.run .bd{animation:none}
576.c-fable.run .ant{animation:blink 1s steps(1) infinite}
577.c-fable.run .star{animation:blink .5s steps(1) infinite -.25s}
578@keyframes float{50%{transform:translateY(-2px)}}`,
579 heavy: `.c-heavy.run .it{animation:scan 1s steps(1) infinite}
580.c-heavy.run .gl{animation:blink 1s steps(1) infinite -.5s}
581@keyframes scan{25%{transform:translate(-1px,1px)}50%{transform:translate(-2px,2px)}75%{transform:translate(-1px,1px)}}`,
582 careful: `.c-careful.run .it{transform-origin:100% 100%;animation:twist .5s ease-in-out infinite}
583@keyframes twist{50%{transform:rotate(-35deg)}}`,
584 medium: `.c-medium.run .pan{transform-origin:0 50%;animation:tilt 1s ease-in-out infinite}
585.c-medium.run .egg{animation:flip 1s ease-in-out infinite}
586@keyframes tilt{20%,40%{transform:rotate(-12deg)}}@keyframes flip{30%{transform:translateY(-5px) scaleY(-1)}60%{transform:translateY(0)}}`,
587 light: `.c-light.run .la{animation-duration:.25s}.c-light.run .lb{animation-duration:.25s;animation-delay:-.125s}
588.c-light.run .flag{transform-origin:0 50%;animation:wave .25s steps(1) infinite}
589@keyframes wave{50%{transform:skewY(-12deg) scaleX(.85)}}`,
590 explore: `.c-explore.run .it{transform-origin:50% 100%;animation:fence .5s ease-in-out infinite}
591@keyframes fence{50%{transform:rotate(25deg)}}`,
592}
593
594const crabCss = (markup: string): string => {
595 const walking = new Set([...markup.matchAll(/class="c-([a-z]+) run"/g)].map(m => m[1] ?? ''))
596 if (!walking.size) return ''
597 return `<style>${WALK_CSS}${[...walking].map(c => COSTUME_CSS[c] ?? '').join('')}</style>`
598}
599
600const COSTUMES: Record<string, (f: Fill, t: string) => void> = {
601 // Fable: astronaut in a glass dome; floats instead of walking, the antenna and the star blink.
602 fable: (f, t) => {
603 crabBody(f)
604 f(6, 7, 18, 1, '#E6E8EE'); f(5, 8, 1, 14, '#E6E8EE'); f(24, 8, 1, 14, '#E6E8EE'); f(6, 22, 18, 1, '#C9CCD2')
605 f(6, 8, 18, 14, 'rgba(169,214,245,.32)'); f(8, 9, 2, 1, '#fff'); f(8, 10, 1, 2, '#fff')
606 f(14, 4, 2, 3, '#C9CCD2'); f(14, 2, 2, 2, t, 'ant'); f(13, 18, 4, 2, t)
607 f(27, 3, 1, 3, '#F5C542', 'star'); f(26, 4, 3, 1, '#F5C542', 'star')
608 },
609 // Heavy: detective with a deerstalker; the magnifier sweeps and glints.
610 heavy: (f, t) => {
611 crabBody(f, -4, 'it')
612 stamp(f, 6, 3, ['......bbbbbb......', '....bbcbbcbbbb....', '...bbbbbbbbbbbb...', '..bcbbcbbcbbcbbb..', '.bbbbbbbbbbbbbbbb.', 'dddddddddddddddddd'], { b: '#7A4A26', c: '#A0703F', d: '#5A3519' })
613 f(6, 9, 18, 1, t)
614 stamp(f, 23, 1, ['.kkk.', 'k...k', 'k...k', 'k...k', '.kkk.'], { k: '#3A3A3C' }, 'it')
615 f(24, 2, 3, 3, 'rgba(169,214,245,.7)', 'it'); f(25, 6, 1, 4, '#7A4A26', 'it'); f(24, 2, 1, 1, '#fff', 'gl')
616 },
617 // Careful: engineer in a hard hat; the wrench turns a bolt.
618 careful: (f, t) => {
619 crabBody(f)
620 stamp(f, 6, 4, ['.....yyyyyyyy.....', '...yyyyyhhyyyyy...', '..yyyyyyhhyyyyyy..', '..yyyyyyhhyyyyyy..', '.yyyyyyyhhyyyyyyy.', 'dddddddddddddddddd'], { y: '#F5C542', h: '#FBE08A', d: '#C99A1E' })
621 f(13, 5, 4, 2, t)
622 stamp(f, 0, 10, ['.s.s', 'sss.', '.s..', '.s..'], { s: '#8E929A' }, 'it')
623 },
624 // Medium: chef, the toque traced from DockCrab's Sprites.chefHat; tosses the omelette.
625 medium: (f, t) => {
626 crabBody(f, -4, 'pan')
627 stamp(f, 6, 0, ['........lll.......', '.......lllll......', '.wwwwgwwwwwwgwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwgwwwwwggwwwww', '.wwwwgwwwwwggwwwww', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.'], { w: '#F4F3EE', l: '#F7F6F2', g: '#D2D1C8', b: t, d: '#B45F43' })
628 f(22, 8, 7, 2, '#4A4A48', 'pan'); f(26, 10, 1, 1, '#4A4A48', 'pan'); f(24, 7, 3, 1, '#F5B731', 'egg')
629 },
630 // Light: racer in a helmet; runs at double pace, the checkered flag flutters.
631 light: (f, t) => {
632 crabBody(f, -4)
633 stamp(f, 6, 5, ['....rrrrrrrrrr....', '..rrrrrrwwrrrrrr..', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.kkkkkkkkkkkkkkkkr'], { r: t, w: '#F8F6F1', k: INK })
634 f(25, 1, 1, 9, '#8E929A')
635 stamp(f, 26, 1, ['wkwk', 'kwkw', 'wkwk'], { w: '#F8F6F1', k: INK }, 'flag')
636 },
637 // Explore: pirate scouting the code; the cutlass fences.
638 explore: f => {
639 crabBody(f)
640 stamp(f, 5, 3, ['.kk..............kk.', '.kkk....kkkk....kkk.', '..kkkkkkkwwkkkkkkk..', '..kkkkkkkkkkkkkkkk..', '.gggggggggggggggggg.'], { k: '#55514C', w: '#F8F6F1', g: '#F5C542' })
641 f(7, 11, 11, 1, INK); f(18, 11, 4, 3, INK)
642 f(27, 6, 1, 9, '#C9CCD2', 'it'); f(26, 15, 3, 1, '#7A4A26', 'it')
643 },
644 other: f => crabBody(f),
645}
646
647const costumeOf = (a: AgentRun): string => (a.type === 'Explore' ? 'explore' : tierOfRun(a))
648
649const CRAB_SCALE = 1.1
650
651// Body and props nest inside `bd` so a prop rides the bob and adds its own motion;
652// legs stay outside it and step on their own.
653const crab = (x: number, y: number, costume: string, dim = false, isWalking = false, scale = CRAB_SCALE): string => {
654 // Cells in a row of one colour become one path, in drawing order, so what
655 // overlaps still overlaps the same way: a few paths instead of ~150 rects.
656 const groups = new Map<string, { c: string; d: string }[]>([['bd', []]])
657 const f: Fill = (cx, cy, w, h, c, cls = 'bd') => {
658 const runs = groups.get(cls) ?? []
659 groups.set(cls, runs)
660 const cell = `M${cx} ${cy}h${w}v${h}h${-w}z`
661 const last = runs[runs.length - 1]
662 if (last?.c === c) last.d += cell
663 else runs.push({ c, d: cell })
664 }
665 const draw = COSTUMES[costume] ?? ((g: Fill) => crabBody(g))
666 draw(f, colorOf(costume))
667 const paths = (cls: string) => (groups.get(cls) ?? []).map(r => `<path fill="${r.c}" d="${r.d}"/>`).join('')
668 const group = (cls: string) => `<g class="${cls}">${paths(cls)}</g>`
669 const props = [...groups.keys()].filter(k => k !== 'bd' && k !== 'la' && k !== 'lb')
670 const body = `<g class="bd">${paths('bd')}${props.map(group).join('')}</g>`
671 return `<g transform="translate(${x},${y}) scale(${scale})" opacity="${dim ? 0.45 : 1}" shape-rendering="crispEdges"><g class="c-${costume}${isWalking ? ' run' : ''}">${body}${group('la')}${group('lb')}</g></g>`
672}
673
674const statusMark = (x: number, y: number, status: string, color: string): string => {
675 if (status === 'running') return `<circle class="live" cx="${x}" cy="${y}" r="3.5" fill="${color}"/>`
676 if (status === 'done') return `<path d="M${x - 5} ${y}l3.5 3.5 6.5-7" fill="none" stroke="#3B9C5F" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`
677 if (status === 'failed') return `<path d="M${x - 4} ${y - 4}l8 8M${x + 4} ${y - 4}l-8 8" stroke="#D0453F" stroke-width="1.8" stroke-linecap="round"/>`
678 return `<circle cx="${x}" cy="${y}" r="5" fill="none" stroke="#9a9a96" stroke-width="1.4"/><path d="M${x} ${y - 2.5}v2.8l1.8 1.2" fill="none" stroke="#9a9a96" stroke-width="1.4" stroke-linecap="round"/>`
679}
680
681const svg = (W: number, H: number, body: string): string =>
682 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${PANE_CSS}${crabCss(body)}${body}</svg>`
683
684// The pane's own title already says "Agents": the header names the flow, if any.
685const headerSvg = (W: number, title: string, t: ReturnType<typeof totals>): string => {
686 const s = tr()
687 const gap = 6
688 const tw = (W - gap * 2) / 3
689 const top = title ? 28 : 0
690 const tile = (i: number, k: string, v: string) =>
691 `<rect class="tile" x="${i * (tw + gap)}" y="${top}" width="${tw}" height="40" rx="8"/>
692<text class="s" x="${i * (tw + gap) + 9}" y="${top + 16}" font-family="${FONT}" font-size="11">${k}</text>
693<text class="t" x="${i * (tw + gap) + 9}" y="${top + 33}" font-family="${FONT}" font-size="15" font-weight="600" font-variant-numeric="tabular-nums">${v}</text>`
694 return svg(
695 W,
696 headerHeight(title),
697 `${title ? `<text class="t" x="0" y="15" font-family="${FONT}" font-size="14" font-weight="600">${xml(fitText(title, 14, W))}</text>` : ''}
698${tile(0, s.cost, '≈' + fmtCost(t.cost))}${tile(1, s.tokens, fmtTokens(t.tokens))}${tile(2, s.time, fmtTime(t.time))}`,
699 )
700}
701
702const headerHeight = (title: string): number => (title ? 72 : 44)
703
704// The task's own progress when the worker reports steps; a finished run is full.
705const progressOf = (a: AgentRun): number | null => {
706 if (a.status === 'done') return 1
707 if (a.stepTotal) return Math.min(1, (a.stepDone ?? 0) / a.stepTotal)
708 return null
709}
710
711// The task's own percentage, for a run that reports its steps. A run that answered is
712// full, though it may answer before reporting its last step; a failed one keeps its count.
713const stepsOf = (a: AgentRun, sep: string): string => {
714 if (!a.stepTotal) return ''
715 const done = a.status === 'done' ? a.stepTotal : (a.stepDone ?? 0)
716 return `${Math.round((progressOf(a) ?? 0) * 100)}% · ${done}/${a.stepTotal}${a.stepNote ? sep + a.stepNote : ''}`
717}
718
719const ctxOf = (a: AgentRun): number => (a.contextMax ? Math.min(100, Math.round((a.contextTokens / a.contextMax) * 100)) : 0)
720
721// A run another subagent started sits under it, this many pixels in per level.
722const INDENT = 16
723
724const agentSvg = (full: number, a: AgentRun, at: number, depth = 0, isViewed = false): string => {
725 const s = tr()
726 const ind = Math.min(depth, MAX_DEPTH) * INDENT
727 const W = full - ind
728 const tier = tierOfRun(a)
729 const color = colorOf(tier)
730 const ctx = ctxOf(a)
731 const textW = W - 42 - 22
732 const isGroup = isGroupRow(a)
733 const meta = isGroup
734 ? [`${a.stepTotal ?? 0} ${s.agentsCount}`]
735 : [a.effort ? `${modelName(a.model)} · ${a.effort}` : modelName(a.model)]
736 if (a.round > 1) meta.push(`${s.round} ${a.round}`)
737 if (a.status === 'failed') meta.push(s.failed)
738 const barW = textW
739 const progress = progressOf(a)
740 const stats = isGroup
741 ? `${fmtTokens(a.tokens)} ≈${fmtCost(a.costUsd)} ${fmtTime(elapsed(a, at))}`
742 : `ctx ${ctx}% · ${fmtTokens(a.contextTokens)} ≈${fmtCost(a.costUsd)} ${fmtTime(elapsed(a, at))}`
743 const steps = stepsOf(a, ' · ')
744 const stepsW = Math.max(0, barW - textWidth(stats, 11) - 12)
745 // Without reported steps the bar falls back to the context, drawn grey.
746 const fillW = Math.round(barW * (progress ?? ctx / 100))
747 // The run in the main view sits on a tile; a nested one hangs from an elbow.
748 const tile = isViewed ? `<rect class="tile" x="-4" y="1" width="${W + 4}" height="63" rx="8"/>` : ''
749 const elbow = ind ? `<path class="ln" d="M${ind - 10} 0v24h6" fill="none"/>` : ''
750 return svg(
751 full,
752 66,
753 `${elbow}<g transform="translate(${ind},0)">${tile}${crab(0, 14, costumeOf(a), false, a.status === 'running')}
754<text class="t" x="42" y="18" font-family="${FONT}" font-size="13" font-weight="600">${xml(fitText(a.description || a.type, 13, textW))}</text>
755<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(isGroup || tier === 'other' ? a.type : tier)}</tspan><tspan class="s"> ${xml(meta.join(' · '))}</tspan></text>
756${steps && stepsW > 30 ? `<text class="t" x="42" y="49" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${xml(fitText(steps, 11, stepsW))}</text>` : ''}
757<text class="s" x="${42 + barW}" y="49" text-anchor="end" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${stats}</text>
758<rect class="k" x="42" y="55" width="${barW}" height="4" rx="2"/><rect${progress === null ? ' class="m"' : ''} x="42" y="55" width="${fillW}" height="4" rx="2"${progress === null ? '' : ` fill="${color}"`}/>
759${statusMark(W - 8, 16, a.status, color)}
760<line class="ln" x1="0" y1="65.5" x2="${W}" y2="65.5"/></g>`,
761 )
762}
763
764const plannedSvg = (W: number, p: Planned): string => {
765 const tier = p.tier in TIER_COLOR ? p.tier : 'other'
766 const color = colorOf(tier)
767 const textW = W - 42 - 22
768 const meta = [TIER_MODEL[tier] ?? '']
769 if (p.after.length) meta.push(`${tr().after} ${p.after.join(', ')}`)
770 return svg(
771 W,
772 46,
773 `${crab(0, 6, tier, true)}
774<text class="s" x="42" y="18" font-family="${FONT}" font-size="13" font-weight="600">${xml(fitText(`${p.n}. ${p.title}`, 13, textW))}</text>
775<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(tier)}</tspan><tspan class="m"> ${xml(meta.filter(Boolean).join(' · '))}</tspan></text>
776${statusMark(W - 8, 16, 'planned', color)}
777<line class="ln" x1="0" y1="45.5" x2="${W}" y2="45.5"/>`,
778 )
779}
780
781const compactSvg = (W: number, list: AgentRun[], planned: Planned[], t: ReturnType<typeof totals>): string => {
782 const icons = [
783 ...list.filter(a => a.status === 'running').map(a => ({ k: costumeOf(a), c: colorOf(tierOfRun(a)), s: 'running', dim: false })),
784 ...list.filter(a => a.status !== 'running').map(a => ({ k: costumeOf(a), c: colorOf(tierOfRun(a)), s: a.status, dim: false })),
785 ...planned.map(p => ({ k: p.tier in TIER_COLOR ? p.tier : 'other', c: colorOf(p.tier), s: 'planned', dim: true })),
786 ]
787 const fit = Math.max(1, Math.floor((W - 150) / 36))
788 const shown = icons.slice(0, fit)
789 const more = icons.length - shown.length
790 const body = shown
791 .map((ic, i) => crab(i * 36, 0, ic.k, ic.dim, ic.s === 'running') + (ic.s === 'running' ? `<circle class="live" cx="${i * 36 + 32}" cy="4" r="3" fill="${ic.c}"/>` : ''))
792 .join('')
793 const x = shown.length * 36 + (more ? 4 : 0)
794 return svg(
795 W,
796 32,
797 `${body}${more ? `<text class="s" x="${x}" y="21" font-family="${FONT}" font-size="12">+${more}</text>` : ''}
798<text class="s" x="${W}" y="21" text-anchor="end" font-family="${FONT}" font-size="12" font-variant-numeric="tabular-nums">≈${fmtCost(t.cost)} · ${fmtTokens(t.tokens)} · ${fmtTime(t.time)}</text>`,
799 )
800}
801
802// --- terminal drawing: the same rows in text.
803
804const ctxBar = (pct: number, width: number): string => {
805 const filled = Math.round((width * pct) / 100)
806 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
807}
808
809// The pane draws the latest finished runs; the totals still count every run.
810const FINISHED_SHOWN = 10
811
812// CSS pixels the desktop keeps beside each run's drawing for its transcript button.
813const VIEW_W = 72
814
815// Claude Code drops a finished subagent from its tasks list 30 s after it ends, and
816// $.ui.view finds only the agents still there. A redraw a little later takes the press
817// off the runs it let go.
818const RELEASED_MS = 31_000
819
820// The ids $.agent.list() still holds; null where it could not say.
821async function listedIds($: EngineInterface): Promise<Set<string> | null> {
822 try {
823 return new Set((await $.agent.list()).map(a => a.id))
824 } catch {
825 return null
826 }
827}
828
829// How deep the pane indents a run started by another subagent; deeper ones stay at it.
830const MAX_DEPTH = 3
831
832type Nested = { a: AgentRun; depth: number }
833
834// Each run followed by the runs it started, a level deeper, when they share its
835// section; one whose parent is drawn elsewhere, or not at all, starts a tree of its own.
836const nest = (rows: AgentRun[]): Nested[] => {
837 const ids = new Set(rows.map(a => a.agentId).filter(Boolean))
838 const out: Nested[] = []
839 const seen = new Set<AgentRun>()
840 const walk = (a: AgentRun, depth: number): void => {
841 if (seen.has(a)) return
842 seen.add(a)
843 out.push({ a, depth })
844 for (const c of rows) if (c.parentId && c.parentId === a.agentId) walk(c, depth + 1)
845 }
846 for (const a of rows) if (!a.parentId || !ids.has(a.parentId)) walk(a, 0)
847 for (const a of rows) walk(a, 0)
848 return out
849}
850
851// --- workflow runs: a script's agents gather under one row, opened on demand.
852
853type Group = { runId: string; rows: AgentRun[] }
854
855// How many runs the session keeps; past it, finished workflow agents go first.
856const MAX_RUNS = 200
857
858const prune = (list: AgentRun[]): AgentRun[] => {
859 const extra = list.length - MAX_RUNS
860 if (extra <= 0) return list
861 const drop = new Set(list.filter(a => a.workflow && a.status !== 'running').slice(0, extra))
862 return list.filter(a => !drop.has(a)).slice(-MAX_RUNS)
863}
864
865// The workflow run a row belongs to: its own, else the one of the run that started it.
866const runIdOf = (list: AgentRun[]): Map<AgentRun, string> => {
867 const byId = new Map(list.flatMap(a => (a.agentId ? [[a.agentId, a] as const] : [])))
868 const out = new Map<AgentRun, string>()
869 const find = (a: AgentRun, hops: number): string | undefined => {
870 if (a.workflow) return a.workflow.runId
871 const parent = a.parentId ? byId.get(a.parentId) : undefined
872 return parent && hops < MAX_RUNS ? find(parent, hops + 1) : undefined
873 }
874 for (const a of list) {
875 const runId = find(a, 0)
876 if (runId !== undefined) out.set(a, runId)
877 }
878 return out
879}
880
881const GROUP_PREFIX = 'wf:'
882const isGroupRow = (a: AgentRun): boolean => a.id.startsWith(GROUP_PREFIX)
883
884// One row standing for a workflow run: its agents' sums, and how many of them answered
885// as its steps, so the bar and the percentage read as they do for a reporting run.
886const standIn = (g: Group, name: string): AgentRun => {
887 const sum = (k: 'tokens' | 'costUsd' | 'steps') => g.rows.reduce((s, a) => s + a[k], 0)
888 const running = g.rows.filter(a => a.status === 'running').length
889 const status: AgentStatus = running ? 'running' : g.rows.some(a => a.status === 'failed') ? 'failed' : 'done'
890 return {
891 id: GROUP_PREFIX + g.runId,
892 type: 'workflow',
893 description: name || `workflow ${g.runId.replace(/^wf_/, '').slice(0, 8)}`,
894 model: g.rows[0]?.model ?? '',
895 status,
896 startedAt: Math.min(...g.rows.map(a => a.startedAt)),
897 ...(running ? {} : { endedAt: Math.max(...g.rows.map(a => a.endedAt ?? a.startedAt)) }),
898 contextTokens: 0,
899 contextMax: 0,
900 tokens: sum('tokens'),
901 costUsd: sum('costUsd'),
902 steps: sum('steps'),
903 round: 1,
904 stepDone: g.rows.length - running,
905 stepTotal: g.rows.length,
906 ...(running ? { stepNote: `${running} ${tr().isRunning}` } : {}),
907 }
908}
909
910type Units = { runs: AgentRun[]; groups: Map<string, Group> }
911
912// The session's runs as the pane and the band count them, in start order: each run
913// on its own, and each workflow run once, where its first agent started.
914const unitsOf = (list: AgentRun[], names: Record<string, string>): Units => {
915 const of = runIdOf(list)
916 const groups = new Map<string, Group>()
917 const order: (AgentRun | Group)[] = []
918 for (const a of list) {
919 const runId = of.get(a)
920 if (runId === undefined) {
921 order.push(a)
922 continue
923 }
924 const g = groups.get(runId) ?? { runId, rows: [] }
925 if (!groups.has(runId)) {
926 groups.set(runId, g)
927 order.push(g)
928 }
929 g.rows.push(a)
930 }
931 const byRow = new Map<string, Group>()
932 const runs = order.map(u => {
933 if (!('runId' in u)) return u
934 const row = standIn(u, names[u.runId] ?? '')
935 byRow.set(row.id, u)
936 return row
937 })
938 return { runs, groups: byRow }
939}
940
941// The rows a section draws: each run with the runs it started beneath it, and each
942// workflow run as one row, its agents a level deeper when it is open.
943const layout = (runs: AgentRun[], groups: Map<string, Group>, open: ReadonlySet<string>): Nested[] => {
944 const trees = new Map<AgentRun, Nested[]>()
945 let tree: Nested[] = []
946 for (const n of nest(runs.filter(a => !groups.has(a.id)))) {
947 if (n.depth === 0) trees.set(n.a, (tree = []))
948 tree.push(n)
949 }
950 return runs.flatMap(a => {
951 const g = groups.get(a.id)
952 if (!g) return trees.get(a) ?? []
953 const head = { a, depth: 0 }
954 return open.has(g.runId) ? [head, ...nest(g.rows).map(n => ({ a: n.a, depth: n.depth + 1 }))] : [head]
955 })
956}
957
958async function unitRuns($: EngineInterface): Promise<AgentRun[]> {
959 return unitsOf(await read($, agents), await read($, workflows)).runs
960}
961
962const STATUS_GLYPH: Record<string, string> = { running: '●', done: '✓', failed: '✗', planned: '◷' }
963
964// Escape closes it, from the pane or an idle, empty prompt; over a turn or text it stays the person's.
965const PANE_OPEN = () => ({ id: PANE, title: tr().pane, closeOnEscape: true }) as const
966
967// Opens the agents pane, or closes it when it is up; true when it ends up open.
968// Up means drawn and in front: one opened unasked on a narrow terminal waits undrawn,
969// and one behind another pane's tab is out of sight, so the person's ask opens those.
970async function togglePane($: EngineInterface): Promise<boolean> {
971 const mine = (await $.ui.panes()).find(p => p.id === PANE)
972 if (mine?.isPlaced && mine.isShown) {
973 await $.ui.close({ id: PANE })
974 return false
975 }
976 const at = await $.clock.now()
977 await update($, now, () => at)
978 await $.ui.open(PANE_OPEN())
979 return true
980}
981
982// Marks the key once the pane opened (or waits for room, which seats it later);
983// an open that fails leaves it unmarked, so the next run tries again.
984async function autoOpen($: EngineInterface, key: string): Promise<void> {
985 const p = await read($, panel)
986 if (p.autoOpenedFor === key) return
987 void $.ui
988 .open(PANE_OPEN())
989 .then(() => update($, panel, prev => ({ ...prev, autoOpenedFor: key })))
990 .catch(() => {})
991}
992
993// Ticks the running runs' clocks once a second, and stops when none runs: an idle
994// session reads nothing. A run that starts or resumes starts it again.
995let ticker: Timer | null = null
996
997function startTicker($: EngineInterface): void {
998 if (ticker) return
999 ticker = $.clock.every(1000, () => {
1000 void (async () => {
1001 if (!(await read($, agents)).some(a => a.status === 'running')) {
1002 ticker?.cancel()
1003 ticker = null
1004 return
1005 }
1006 const at = await $.clock.now()
1007 await update($, now, () => at)
1008 })()
1009 })
1010}
1011
1012// A finished flow leaves the band after FINISHED_LINGER_MS, unless a newer one took its place.
1013function stepAside($: EngineInterface, f: Flow): void {
1014 const finishedAt = f.finishedAt
1015 if (finishedAt === undefined) return
1016 void (async () => {
1017 const wait = Math.max(0, finishedAt + FINISHED_LINGER_MS - (await $.clock.now()))
1018 $.clock.after(wait, () => {
1019 void patchFlow($, prev => (prev?.isFinished && prev.finishedAt === finishedAt ? null : prev))
1020 })
1021 })()
1022}
1023
1024// Nothing another plugin drew: core's own band (an `engine` element, which the band
1025// replaced before too) or an empty box.
1026const isBlank = (el: RenderElement | undefined): boolean =>
1027 !el || el.type === 'engine' || (el.type === 'Box' && (el.children ?? []).length === 0)
1028
1029export const register: Register = (on, options) => {
1030 on('session.start', async ($, e, next) => {
1031 const started = await next(e)
1032 lang = await detectLang($, options.language)
1033 canView = await engineHasView($)
1034 // A reload drops pending timers: a finished flow held by the host still steps aside.
1035 const held = await read($, flow)
1036 if (held?.isFinished) stepAside($, held)
1037 await $.tool.register({
1038 name: 'progress',
1039 description:
1040 'Report the progress of work delegated to subagents to the progress bar above the prompt and the agents panel. ' +
1041 'Call it after presenting the plan (title, total, tasks, phase "delegate"), each time a task is accepted (done), ' +
1042 'when switching phase or re-planning (tasks), and once at the end with finished: true. Fields left out keep their previous value.',
1043 inputSchema: {
1044 type: 'object',
1045 properties: {
1046 title: { type: 'string', description: 'Short name of the overall task, a few words.' },
1047 total: { type: 'integer', minimum: 0, description: 'Number of planned worker tasks.' },
1048 done: { type: 'integer', minimum: 0, description: 'Number of tasks accepted after review.' },
1049 phase: { type: 'string', enum: [...PHASES] },
1050 finished: { type: 'boolean', description: 'True once the flow is closed.' },
1051 tasks: {
1052 type: 'array',
1053 description:
1054 'The planned worker tasks in order, numbered from 1. Each title must equal the Agent tool `description` the task will be delegated with, so the panel can match runs to tasks.',
1055 items: {
1056 type: 'object',
1057 properties: {
1058 title: { type: 'string', description: 'A few words; reused verbatim as the Agent description.' },
1059 tier: {
1060 type: 'string',
1061 enum: ['fable', 'heavy', 'careful', 'medium', 'light'],
1062 description: 'The model the task runs on: fable = Fable, heavy and careful = Opus, medium = Sonnet, light = Haiku.',
1063 },
1064 after: { type: 'array', items: { type: 'integer' }, description: 'Numbers of the tasks this one waits for.' },
1065 },
1066 required: ['title', 'tier'],
1067 },
1068 },
1069 },
1070 },
1071 })
1072 // Every briefed subagent calls `step` first thing: listed from the start, it needs no
1073 // ToolSearch round first. `progress` stays behind tool search, loaded by the skill.
1074 const listed = (await engineSince($, LISTED_SINCE)) ? { isDeferred: false } : {}
1075 await $.tool.register({
1076 ...listed,
1077 name: 'step',
1078 description:
1079 'For subagents: report progress on your own task to the agents panel. ' +
1080 'Right after reading the brief, call it with `total` (your plan in 3-8 steps) and `done: 0`; ' +
1081 'call it again as each step finishes. Cheap and silent: it only draws a bar.',
1082 inputSchema: {
1083 type: 'object',
1084 properties: {
1085 done: { type: 'integer', minimum: 0, description: 'Steps finished so far.' },
1086 total: { type: 'integer', minimum: 1, description: 'Steps planned; may change if the plan changes.' },
1087 note: { type: 'string', description: 'The step in progress, a few words.' },
1088 },
1089 required: ['done'],
1090 },
1091 })
1092 await $.command.register({
1093 name: 'agents-info',
1094 description: 'Show or hide the panel of subagents: running, finished and planned, with model, context, cost and time',
1095 })
1096
1097 // A reload drops the old ticker with the old module: start again for runs still at work.
1098 if ((await read($, agents)).some(a => a.status === 'running')) startTicker($)
1099 return started
1100 })
1101
1102 on('command.run', { command: 'agents-info' }, async $ => {
1103 const isOpen = await togglePane($)
1104 return { text: isOpen ? tr().opened : tr().closed }
1105 })
1106
1107 on('tool.call', { tool: TOOL }, async ($, e) => {
1108 const input = e as unknown as ProgressInput
1109 // The pane keeps every run of the session; a new flow only marks when it began.
1110 const at = await $.clock.now()
1111 const next = await patchFlow($, p => {
1112 const merged = merge(p, input)
1113 return {
1114 ...merged,
1115 ...(isNewFlow(p, input) ? { startedAt: at } : {}),
1116 ...(merged.isFinished ? { finishedAt: at } : {}),
1117 }
1118 })
1119 if (next?.isFinished) stepAside($, next)
1120 if (next && input.tasks?.length) await autoOpen($, next.title)
1121 return { result: `ok: ${label(next ?? blank(), runningOf(await unitRuns($)))}` }
1122 })
1123
1124 // A worker's own progress: the call runs in the worker's loop, so agentId names it.
1125 on('tool.call', { tool: STEP_TOOL }, async ($, e) => {
1126 const input = e as unknown as { done?: number; total?: number; note?: string }
1127 const agentId = e.agentId
1128 if (!agentId) return { result: 'ignored: only subagents report steps' }
1129 await patchAgents($, list =>
1130 list.map(a => {
1131 if (a.agentId !== agentId) return a
1132 const total = Math.max(0, Math.round(input.total ?? a.stepTotal ?? 0))
1133 const done = Math.max(0, Math.round(input.done ?? a.stepDone ?? 0))
1134 return { ...a, stepTotal: total, stepDone: total ? Math.min(total, done) : done, stepNote: input.note?.trim() || undefined }
1135 }),
1136 )
1137 return { result: 'ok' }
1138 })
1139
1140 on('agent.spawn', async ($, e, next) => {
1141 // A resume (a parent woken when its background child answers, say) continues a run
1142 // already listed: its prompt is the waking message, which the engine keeps as sent.
1143 const isResume = e.resume !== undefined
1144 // A workflow agent answers its script, often many of them at once: the pane counts
1145 // them under the run, and their prompts stay as the script wrote them.
1146 const wf = e.workflow
1147 const started = await next(isResume || wf ? e : { ...e, prompt: briefed(e.prompt, options.stepBrief !== 'off') })
1148 if (started.deny !== undefined) return started
1149
1150 const at = await $.clock.now()
1151 const id = started.agentId ?? e.resume?.agentId ?? e.tool_use_id
1152 const list = await read($, agents)
1153 const wasIdle = !list.some(a => a.status === 'running')
1154 const held = list.find(a => a.id === id)
1155 if (isResume && held) {
1156 // The same run at work again: its start, totals, steps and round stay.
1157 await update($, agents, all =>
1158 all.map(a => (a.id === id ? { ...a, model: started.model || a.model, status: 'running' as const, endedAt: undefined } : a)),
1159 )
1160 await update($, now, () => at)
1161 startTicker($)
1162 return started
1163 }
1164 await update($, agents, all => {
1165 const round = wf ? 1 : 1 + all.filter(a => a.id !== id && e.description && norm(a.description) === norm(e.description)).length
1166 const run: AgentRun = {
1167 id,
1168 agentId: started.agentId ?? e.resume?.agentId,
1169 type: e.subagentType,
1170 description: e.description,
1171 ...(e.parentAgentId ? { parentId: e.parentAgentId } : {}),
1172 ...(wf ? { workflow: { runId: wf.runId, index: wf.agentIndex } } : {}),
1173 model: started.model,
1174 status: 'running',
1175 startedAt: at,
1176 contextTokens: 0,
1177 contextMax: windowOf(started.model),
1178 tokens: 0,
1179 costUsd: 0,
1180 steps: 0,
1181 round,
1182 }
1183 return prune([...all.filter(a => a.id !== run.id), run])
1184 })
1185 await update($, now, () => at)
1186 startTicker($)
1187 // A run started under a flow still planning moves it to delegating.
1188 await patchFlow($, prev => (prev && !prev.isFinished && prev.phase === 'plan' ? { ...prev, phase: 'delegate' } : prev))
1189 // Any subagent opens the panel: once per reported flow, else once per busy spell
1190 // (a run started while none was running), so closing it sticks until the next one.
1191 const f = await read($, flow)
1192 if (f && !f.isFinished) await autoOpen($, f.title)
1193 else if (wf) await autoOpen($, `wf:${wf.runId}`)
1194 else if (wasIdle) await autoOpen($, `run:${id}`)
1195 return started
1196 })
1197
1198 // A workflow run's name, from the Workflow tool's answer, heads its row in the pane.
1199 on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
1200 const answered = await next(e)types/index.d.ts 76 lines1export type Phase = 'plan' | 'design' | 'delegate' | 'review' | 'close'
2
3export type PlannedTask = {
4 title: string
5 tier: string
6 after: number[]
7}
8
9export type Flow = {
10 title: string
11 total: number
12 done: number
13 phase: Phase
14 isFinished: boolean
15 /** When the flow began; runs from before it are not its tasks. */
16 startedAt?: number
17 /** When the flow was reported finished; its band steps aside a little after. */
18 finishedAt?: number
19 tasks: PlannedTask[]
20}
21
22export type AgentStatus = 'running' | 'done' | 'failed'
23
24export type AgentRun = {
25 id: string
26 agentId?: string
27 type: string
28 description: string
29 model: string
30 effort?: string
31 status: AgentStatus
32 startedAt: number
33 endedAt?: number
34 contextTokens: number
35 contextMax: number
36 tokens: number
37 costUsd: number
38 steps: number
39 round: number
40 /** The agentId of the subagent that started this one; absent when the main loop did. */
41 parentId?: string
42 /** Set when a workflow script's `agent()` started it: its run and place in it, from 1. */
43 workflow?: { runId: string; index: number }
44 /** Self-reported by the worker through the `step` tool. */
45 stepDone?: number
46 stepTotal?: number
47 stepNote?: string
48}
49
50export type Panel = {
51 isCompact: boolean
52 isDoneCollapsed: boolean
53 /** The terminal draws each run without its grey rows; absent in a panel held from before. */
54 isSimple?: boolean
55 /** The terminal lists the pane's keys under its header; absent in a panel held from before. */
56 isHelpShown?: boolean
57 /** Every finished run drawn, not only the latest ten; absent in a panel held from before. */
58 isEarlierShown?: boolean
59 autoOpenedFor: string
60 /** Workflow runs drawn with their agents beneath; the rest show as one row. */
61 openGroups?: string[]
62}
63
64declare module 'claude-code' {
65 interface PluginState {
66 'agents-progress': {
67 flow: Flow | null
68 agents: AgentRun[]
69 panel: Panel
70 now: number
71 /** Each workflow run's name, by run id, as the Workflow tool answered it. */
72 workflows: Record<string, string>
73 }
74 }
75}
76