Live plan progress bars above the Claude Code prompt: stages, steps, a pixel fill and soft sounds for decision, error and done (qa-mods fork: a wider title…

Fourteen Claude Code mods, packaged as one plugin marketplace (qa-mods). Made for a manual QA workflow: guard rails around risky commands, evidence for what was tested, and a status band above the prompt.
Run in your own Terminal (a sandboxed Claude session cannot write ~/.claude).
claude plugin marketplace add oleksandrkodua/qa-mods
claude plugin install hud@qa-mods
Replace hud with any plugin from the table.
To install everything from a local clone, or to set up a fresh machine, see INSTALL.md and install-pack.sh.
| Plugin | What it does |
|---|---|
sandbox-guard | Denies writes to protected Claude config paths and hands back a Terminal command |
remote-gate | Asks before git push and wrangler --remote, showing folder, branch, remote and the commits that will go out |
blast-radius | Shows what a risky Bash command will touch before it runs |
retry-analyzer | Detects repeated identical failing tool calls and tells Claude to change strategy |
secret-redactor | Masks tokens and keys in tool output |
evidence-saver | Saves screenshots from tool results to a folder you pick |
replay-theater | /replay: step through the session's file edits one by one |
verification-guard | Checks claims like "tests pass" against tool calls that actually ran |
handoff | Offers /handoff as the context fills up; fills the prompt box with a HANDOFF.md prompt |
notify | A toast and a macOS notification when a long command or turn finishes |
quick-actions | Compact and Clear buttons, each asks to confirm first |
hud | Context fill and rate-limit windows above the prompt, a кеш 59:48 chip (m:ss) while the prompt cache is warm, five buttons, and /hud with the figures as text |
next-steps-uk | Fork of next-steps (MIT, Thariq Shihipar): suggested next prompts are always in Ukrainian. Install instead of next-steps |
plan-progress | Fork of plan-progress 0.7.6 (zycck, MIT): live progress bars above the prompt. Install instead of plan-progress@zycck-mods |
claude plugin test hud # from the repo root
cd hud && node --test tests/format.test.mjs tests/handoff-prompt.test.mjs
A bare node --test also picks up register.test.ts, which only runs under claude plugin test.
No license file for the original mods yet. The two forks keep their upstream MIT notices: next-steps-uk/NOTICE.md and plan-progress/NOTICE.md (plus plan-progress/LICENSE.upstream).
hooks/register.tsx 1864 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, Plan, PlanStage, PlanState, PlanStep, StepStatus } from '../types'
5
6const TOOL = 'mcp__plan-progress__plan_progress'
7const plans = atom({ plugin: 'plan-progress', key: 'plans' } as const, [])
8const MAX_BARS = 20 // fork (qa-mods): runaway guard only; upstream kept 3, qa.10 raised it to 5 and it pushed running bars out, so qa.12 lifted it
9// a space as wide as a digit, so ' 0%' and '100%' take the same room
10const FIGURE_SPACE = String.fromCharCode(0x2007)
11const isOpen = atom({ plugin: 'plan-progress', key: 'isOpen' } as const, true)
12const tick = atom({ plugin: 'plan-progress', key: 'tick' } as const, 0)
13// fork (qa-mods): bars whose long title the person opened in full
14const expanded = atom({ plugin: 'plan-progress', key: 'expanded' } as const, [] as string[])
15// fork (qa-mods): with 4+ bars the finished ones fold into one line "✓ N готово ▾"; this is true while the person has opened them
16const doneOpen = atom({ plugin: 'plan-progress', key: 'doneOpen' } as const, false)
17// fork (qa-mods): a finished bar stays a full green row this long after it ends, then folds into the "✓ N готово ▾" line
18const DONE_HOLD_MS = 60_000
19// fork (qa-mods): finished bars stay until the person closes them; only this many are remembered, the oldest goes first
20const MAX_DONE = 8
21const STRIP_H = 16
22const STRIP_GAP = 2
23// rows of strips per bar, the "+N more" row included: the band above the prompt has room for about 300 px
24const stripBudget = (bars: number) => (bars >= 3 ? 3 : bars === 2 ? 4 : 5)
25const FOLD_MS = 5000 // finished strips stay this long, failed ones stay until the bar closes
26
27// one lightness for every state (OKLCH L .55, hues of the desktop's violet, amber, red and green), so no state
28// shouts louder than another, and white on each reads at 4.5:1 or better
29const STATE_COLOR: Record<PlanState, string> = { running: '#7858CA', needs_input: '#AD6400', error: '#C5353E', done: '#18883A' }
30const INK = '#FFFFFF'
31const STATE_GLYPH: Record<PlanState, string> = { running: '●', needs_input: '?', error: '!', done: '✓' }
32// a bar closed "done" over a step in error is finished but not clean: it keeps the error colour and a ✕ instead of a green ✓
33const hasFailedStep = (p: Plan) => p.state === 'done' && p.stages.some(s => s.steps.some(x => x.status === 'error'))
34const lookOf = (p: Plan): PlanState => (hasFailedStep(p) ? 'error' : p.state)
35const glyphOf = (p: Plan) => (hasFailedStep(p) ? '✕' : STATE_GLYPH[p.state])
36const STATUSES: StepStatus[] = ['pending', 'active', 'done', 'error', 'skipped']
37const TRACK_H = 22
38const NARROW = 260 // fork (qa-mods): was 360; with it a title of ~30 characters pushed the track under the limit and the pill turned into a bare number
39
40const RULES = `# Progress bars
41Tasks needing more than ~3 edits or commands get a bar via ${TOOL}: create it once with the full breakdown (2-7 stages of steps {title, detail?}, or kind "todo" for one flat list; titles of at most 4 words, in the user's language; the first open step becomes active), then move it with short calls: {id, next:true} when the active step is finished, or {id, done:[...], active:"..."}, {id, failed:"...", note}. A failed step does not close the bar: carry on with {id, active:"..."} or close it with state "done" (a bar closed over a failed step shows a red ✕, not a green ✓, so report the failure to the user). When the plan changes, resend stages under the same id; steps sent without a status keep their done by title. Send state "needs_input" with a note before asking the user to decide. Never describe the bars to the user.`
42
43type Raw = Record<string, unknown>
44// the cut drops half a character left at the edge (an emoji is two UTF-16 units)
45const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max).replace(/[\uD800-\uDBFF]$/, '').trimEnd() : '')
46// fork (qa-mods): a title longer than max is cut at a word and ends with an ellipsis (upstream cut it mid-word at 80)
47const clip = (v: unknown, max: number) => {
48 const t = str(v, 1000)
49
50 if (t.length <= max) return t
51
52 const head = str(t, max - 1)
53 const at = head.lastIndexOf(' ')
54
55 return `${(at > max * 0.6 ? head.slice(0, at) : head).trimEnd()}…`
56}
57const status = (v: unknown): StepStatus => (STATUSES.includes(v as StepStatus) ? (v as StepStatus) : 'pending')
58const list = (v: unknown): Raw[] => (Array.isArray(v) ? v.filter(x => x && typeof x === 'object') : []) as Raw[]
59const isFinished = (s: StepStatus) => s === 'done' || s === 'skipped'
60
61const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()
62
63// short updates: {next:true}, {done:[titles]}, {active:title}, {failed:title} against the stored plan;
64// titles it cannot find come back in missing, so the call is refused instead of passing as a success
65function applyOps(stages: PlanStage[], input: Raw, now: number): { stages: PlanStage[]; missing: string[] } {
66 const next = stages.map(s => ({ ...s, steps: s.steps.map(st => ({ ...st })) }))
67 const steps = next.flatMap(s => s.steps)
68 const missing: string[] = []
69 // a step finishing now remembers when, for the time its checkpoint shows
70 const finish = (st: PlanStep) => {
71 if (!isFinished(st.status)) Object.assign(st, { status: 'done', doneAt: now })
72 }
73 // a step opened again forgets when it was finished, so its checkpoint shows no stale time
74 const reopen = (st: PlanStep, to: StepStatus) => {
75 st.status = to
76 delete st.doneAt
77 }
78 // a title used twice means the one still open
79 const find = (title: string) => {
80 const found = steps.find(st => same(st.title, title) && !isFinished(st.status)) ?? steps.find(st => same(st.title, title))
81 if (!found) missing.push(title)
82 return found
83 }
84 if (input.next === true) {
85 const at = steps.findIndex(st => st.status === 'active') >= 0 ? steps.findIndex(st => st.status === 'active') : steps.findIndex(st => !isFinished(st.status))
86 const cur = steps[at]
87 if (cur) finish(cur)
88 // past the last step, work goes back to one left open earlier
89 const following = steps.slice(at + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
90 if (following) following.status = 'active'
91 }
92 let lastDone = -1
93 for (const t of Array.isArray(input.done) ? input.done : []) {
94 const st = typeof t === 'string' ? find(t) : undefined
95 if (st?.status === 'active') lastDone = steps.indexOf(st)
96 if (st) finish(st)
97 }
98 // finishing the step in progress moves on, as next does, unless the call names the new one itself
99 if (lastDone >= 0 && typeof input.active !== 'string' && !steps.some(st => st.status === 'active')) {
100 const following = steps.slice(lastDone + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
101 if (following) following.status = 'active'
102 }
103 const active = typeof input.active === 'string' ? find(input.active) : undefined
104 if (active) {
105 const at = steps.indexOf(active)
106 steps.forEach((st, i) => {
107 if (st.status === 'active' && i !== at) {
108 if (i < at) finish(st)
109 else st.status = 'pending'
110 }
111 })
112 reopen(active, 'active')
113 }
114 const failed = typeof input.failed === 'string' ? find(input.failed) : undefined
115 if (failed) reopen(failed, 'error')
116
117 return { stages: next, missing }
118}
119
120// the new bar, or the refusal for a call that names steps the bar does not have
121function normalize(input: Raw, prev: Plan | null, now: number, id: string): Plan | string {
122 const sent = list(input.stages)
123 .map(s => ({
124 name: str(s.name, 80) || 'Stage',
125 steps: list(s.steps).map(st => ({
126 title: str(st.title) || 'Крок',
127 status: status(st.status),
128 detail: str(st.detail, 160) || undefined,
129 substeps: list(st.substeps).map(sub => ({ title: str(sub.title) || '…', status: status(sub.status) })),
130 })),
131 }))
132 .filter(s => s.steps.length > 0) as PlanStage[]
133 const isPartial = sent.length === 0 && prev !== null
134 // a resent plan keeps what was finished; short ops sent along with it apply on top
135 const base = isPartial ? prev.stages : pointAt(prev ? carryDone(sent, prev.stages) : sent)
136 const { stages, missing } = applyOps(base, input, now)
137 if (missing.length > 0 && base.length > 0) {
138 const titles = stages.flatMap(s => s.steps.map(st => st.title)).join(', ')
139 return `plan_progress: "${id}" has no step ${missing.map(t => `"${str(t, 60)}"`).join(', ')}. Its steps: ${titles.slice(0, 400)}`
140 }
141 const title = clip(input.title, 160) || prev?.title || 'План'
142 const steps = stages.flatMap(s => s.steps)
143 const isAllDone = steps.length > 0 && steps.every(s => isFinished(s.status))
144 const asked = input.state as PlanState
145 const failedNow = typeof input.failed === 'string'
146 const state: PlanState = ['running', 'needs_input', 'error', 'done'].includes(asked) ? asked : isAllDone ? 'done' : failedNow ? 'error' : 'running'
147
148 return {
149 id,
150 title,
151 kind: input.kind === 'todo' || (isPartial && prev?.kind === 'todo') ? 'todo' : 'plan',
152 stages,
153 state,
154 note: str(input.note, 160) || null,
155 startedAt: prev ? prev.startedAt : now,
156 endedAt: state === 'done' ? (prev?.endedAt ?? now) : null,
157 }
158}
159
160// a resent plan keeps what is finished: a step sent as pending under a title that was done stays done
161// a title used twice: each finished step carries over to one resent step of that title, in order
162function carryDone(stages: PlanStage[], before: PlanStage[]): PlanStage[] {
163 const finished = new Map<string, PlanStep[]>()
164 for (const st of before.flatMap(s => s.steps).filter(st => isFinished(st.status))) {
165 const key = st.title.trim().toLowerCase()
166 finished.set(key, [...(finished.get(key) ?? []), st])
167 }
168 return stages.map(s => ({
169 ...s,
170 steps: s.steps.map(st => {
171 const queue = finished.get(st.title.trim().toLowerCase())
172 const was = queue?.[0]
173 if (!queue || !was || !(st.status === 'pending' || st.status === was.status)) return st
174 queue.shift()
175 return { ...st, status: was.status, doneAt: was.doneAt }
176 }),
177 }))
178}
179
180// with nothing in progress, the first open step is the current one
181function pointAt(stages: PlanStage[]): PlanStage[] {
182 const steps = stages.flatMap(s => s.steps)
183 if (steps.some(st => st.status === 'active' || st.status === 'error')) return stages
184 const first = steps.find(st => st.status === 'pending')
185 return stages.map(s => ({ ...s, steps: s.steps.map(st => (st === first ? { ...st, status: 'active' as const } : st)) }))
186}
187
188// the bar an approved plan-mode plan lands on; a revised plan updates it instead of opening a second one
189const PLAN_ID = 'plan'
190
191const clean = (s: string) =>
192 s
193 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
194 .replace(/[*_`]/g, '')
195 .replace(/^\s*(\d+[.)]|[-*+]|\[[ xX]\])\s+/, '')
196 .replace(/^(\d+[.)]|\[[ xX]\])\s+/, '')
197 .trim()
198
199function parsePlan(markdown: string, now: number): Plan | null {
200 let title = ''
201 const headed: PlanStage[] = []
202 const items: { depth: number; text: string; status: StepStatus }[] = []
203 for (const line of markdown.split(/\r?\n/)) {
204 const h = line.match(/^(#{1,4})\s+(.*)$/)
205 if (h) {
206 const text = clean(h[2] ?? '')
207 if (h[1] === '#' && !title) title = text
208 else headed.push({ name: text, steps: [] })
209 continue
210 }
211 const li = line.match(/^(\s*)(\d+[.)]|[-*+])\s+(.*)$/)
212 if (!li) continue
213 const depth = Math.floor((li[1] ?? '').replace(/\t/g, ' ').length / 2)
214 const text = clean(li[3] ?? '').slice(0, 120)
215 if (!text) continue
216 // a ticked box is a step the plan already counts as done
217 const status: StepStatus = /^\[[xX]\]\s/.test(li[3] ?? '') ? 'done' : 'pending'
218 items.push({ depth, text, status })
219 const stage = headed[headed.length - 1]
220 if (!stage) continue
221 const step = stage.steps[stage.steps.length - 1]
222 if (depth === 0 || !step) stage.steps.push({ title: text, status, substeps: [] })
223 else step.substeps.push({ title: text, status })
224 }
225 let stages = headed.filter(s => s.steps.length > 0)
226 if (stages.length === 0) {
227 if (items.some(i => i.depth > 0)) {
228 for (const item of items) {
229 const stage = stages[stages.length - 1]
230 if (item.depth === 0 || !stage) stages.push({ name: item.text, steps: [] })
231 else stage.steps.push({ title: item.text, status: item.status, substeps: [] })
232 }
233 stages = stages.map(s => (s.steps.length ? s : { ...s, steps: [{ title: s.name, status: 'pending', substeps: [] }] }))
234 } else if (items.length > 0) {
235 stages = [{ name: 'Завдання', steps: items.map(i => ({ title: i.text, status: i.status, substeps: [] })) }]
236 }
237 }
238 if (stages.length === 0) return null
239
240 return { id: PLAN_ID, title: title || 'План', kind: stages.length === 1 ? 'todo' : 'plan', stages, state: 'running', note: null, startedAt: now }
241}
242
243function st(title: string, s: StepStatus): PlanStep {
244 return { title, status: s, substeps: [] }
245}
246
247// ---------- drawing ----------
248
249type Where = { pos: number; total: number; stage: number; step: number; stageSize: number }
250
251// pos counts the finished steps wherever they are; the current step is the active one, else the first still open
252function where(p: Plan): Where {
253 const steps = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
254 const pos = p.state === 'done' ? steps.length : steps.filter(x => isFinished(x.step.status)).length
255 const cur = p.state === 'done' ? undefined : (steps.find(x => x.step.status === 'active') ?? steps.find(x => !isFinished(x.step.status)))
256 const stage = (cur ?? steps[steps.length - 1])?.i ?? 0
257
258 return { pos, total: steps.length, stage, step: cur ? cur.j + 1 : (p.stages[stage]?.steps.length ?? 0), stageSize: p.stages[stage]?.steps.length ?? 0 }
259}
260
261const hex = (h: string) => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16))
262const mix = (a: number[], b: number[], m: number) => a.map((v, i) => Math.round(v + ((b[i] ?? 0) - v) * m))
263const rgb = (c: number[]) => `rgb(${c.join(',')})`
264const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c)
265const hash = (a: number, b: number, k: number) => {
266 const x = Math.sin(a * 127.1 + b * 311.7 + k * 74.7) * 43758.5453
267 return x - Math.floor(x)
268}
269const textWidth = (s: string, px = 6.7) => [...s].reduce((w, ch) => w + (/[ -鿿]/.test(ch) ? 12 : /[ilI.,:;'|!]/.test(ch) ? 3.4 : /[mwMWШЩЖМ]/.test(ch) ? 9.5 : /[Ѐ-ӿ]/.test(ch) ? 9.2 : px), 0)
270
271const ICON_PATH: Partial<Record<PlanState, string>> = {
272 needs_input: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01',
273 error: 'M18 6 6 18M6 6l12 12',
274 done: 'M20 6 9 17l-5-5',
275}
276
277// how long each finished step took (from the previous finish, or the plan's start) and each finished stage
278function stepTimes(p: Plan): { steps: Map<PlanStep, number>; stages: (number | undefined)[] } {
279 const ends = p.stages.flatMap(s => s.steps).flatMap(st => (st.doneAt === undefined ? [] : [st.doneAt])).sort((a, b) => a - b)
280 const startOf = (at: number) => Math.max(p.startedAt, ...ends.filter(t => t < at))
281 const steps = new Map<PlanStep, number>()
282 const stages = p.stages.map(s => {
283 for (const st of s.steps) if (st.doneAt !== undefined) steps.set(st, st.doneAt - startOf(st.doneAt))
284 const times = s.steps.map(st => st.doneAt)
285 if (times.some(t => t === undefined)) return undefined
286 const done = times as number[]
287 return Math.max(...done) - Math.min(...done.map(startOf))
288 })
289 return { steps, stages }
290}
291
292// the 2 px dots of one look go into one path: a fraction of the markup of a rect each, and one node instead of thousands
293function addDot(dots: Map<string, string>, cls: string, x: number, y: number) {
294 dots.set(cls, `${dots.get(cls) ?? ''}M${x} ${y}h2v2h-2z`)
295}
296
297// last drawn head position per plan, so a redraw glides from where the bar was
298const lastHead = new Map<string, { W: number; x: number }>()
299
300// the track draws in a sandboxed frame (for hover); its page must stay see-through in either theme
301const SEE_THROUGH = '<style>:root,html,body{background:transparent!important;color-scheme:light dark;margin:0;overflow:hidden}svg{display:block}</style>'
302
303// a clock that counts in the frame by itself, so the drawing never has to be redrawn each second (a redraw
304// reloads the frame and everything in it blinks): each digit is a reel of its figures behind a one-line window,
305// stepped by a CSS animation whose negative delay is the time already run. Plain SVG, since the host's frame
306// drops foreignObject. {{T:start}} becomes those seconds on every draw (liveSource)
307const CLOCK_W = 48 // "59х 59с"
308const LINE = 16
309const CLOCK_CSS = `.ckt{font-variant-numeric:tabular-nums}
310.rs1{animation:r10 10s steps(10) var(--d) infinite}.rs10{animation:r6 60s steps(6) var(--d) infinite}
311.cc{animation:cc 36000s linear var(--d) both}@keyframes cc{0%,.1666%{transform:translateX(-13.5px)}.1667%,1.6666%{transform:translateX(-3.25px)}1.6667%,9.9999%{transform:none}10%,99.9999%{transform:translateX(-3.25px)}100%{transform:none}}
312.rm1{animation:r10 600s steps(10) var(--d) infinite}.rm10{animation:r10 6000s steps(10) var(--d) infinite}.rmm{animation:hm 60s steps(1,end) var(--d) both}
313.rm6{animation:r6 3600s steps(6) var(--d) infinite}.rh1{animation:r10 36000s steps(10) var(--d) infinite}.rh10{animation:r10 360000s steps(10) var(--d) infinite}
314.ph1{animation:ho 3600s steps(1,end) var(--d) both}.ph2{animation:hm 3600s steps(1,end) var(--d) both}
315@keyframes r10{to{transform:translateY(-${LINE * 10}px)}}@keyframes r6{to{transform:translateY(-${LINE * 6}px)}}@keyframes hm{from{opacity:0}to{opacity:1}}@keyframes ho{from{opacity:1}to{opacity:0}}`
316
317// x is the clock's left edge, top the window's top. Under an hour it reads "12m 05s", the minutes part hidden for
318// the first minute; from an hour on "1h 05m", as elapsed() writes a finished time, up to 99h
319function liveClock(x: number, top: number, start: number, cls: string, textCls: string, isCentered = false): string {
320 const base = top + 12
321 const reel = (cx: number, figures: string[], reelCls: string) =>
322 `<g class="${reelCls}"><text class="${textCls} ckt" text-anchor="middle">${figures
323 .map((f, i) => `<tspan x="${cx.toFixed(1)}" y="${base + i * LINE}">${f}</tspan>`)
324 .join('')}</text></g>`
325 const unit = (ux: number, label: string) => `<text x="${ux.toFixed(1)}" y="${base}" class="${textCls}">${label}</text>`
326 const digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
327 const tens = ['', ...digits.slice(1)]
328 const id = `ck${start}x${Math.round(x)}y${Math.round(top)}`
329 const minutes =
330 `<g class="ph1"><g class="rmm">${reel(x + 3.5, tens, 'rm10')}${reel(x + 10.5, digits, 'rm1')}${unit(x + 14, 'х')}</g>` +
331 `${reel(x + 31, digits.slice(0, 6), 'rs10')}${reel(x + 38, digits, 'rs1')}${unit(x + 41.5, 'с')}</g>`
332 const hours =
333 `<g class="ph2">${reel(x + 3.5, tens, 'rh10')}${reel(x + 10.5, digits, 'rh1')}${unit(x + 14, 'г')}` +
334 `${reel(x + 31, digits.slice(0, 6), 'rm6')}${reel(x + 38, digits, 'rm1')}${unit(x + 41.5, 'х')}</g>`
335 return (
336 `<style>.${id}{--d:-{{T:${start}}}s}</style><g class="${cls} ${id}"><clipPath id="${id}"><rect x="${(x - 2).toFixed(1)}" y="${top}" width="${CLOCK_W + 4}" height="${LINE}"/></clipPath>` +
337 `<g clip-path="url(#${id})"${isCentered ? ' class="cc"' : ''}>${minutes}${hours}</g></g>`
338 )
339}
340
341// the desktop rebuilds a strip's picture on every redraw of the band, another plugin's invalidate included, so a
342// source reused from an earlier draw would restart its clocks at that draw's offset (issue #6): the offset is
343// taken from now on every draw
344function liveSource(template: string, now: number): string {
345 return template.replace(/\{\{T:(\d+)\}\}/g, (_, t: string) => Math.max(0, (now - Number(t)) / 1000).toFixed(1))
346}
347
348// a bar is drawn twice: the track itself as a plain picture, which the desktop keeps steady whatever else redraws,
349// and a see-through layer on top for the hover parts (checkpoint times, the pill's clock). That layer needs an
350// interactive frame, and the desktop rebuilds such frames on every redraw of the band; empty until hovered, the
351// rebuild is invisible. A plan is immutable, so both drawings at one width are reused until the plan changes
352type Track = { base: string; overlay: string }
353const drawn = new WeakMap<Plan, { W: number; track: Track }>()
354
355function trackSvg(p: Plan, W: number): Track {
356 const cached = drawn.get(p)
357 if (cached?.W === W) return cached.track
358 const track = drawTrack(p, W)
359 drawn.set(p, { W, track })
360 return track
361}
362
363function drawTrack(p: Plan, W: number): Track {
364 const H = TRACK_H
365 const w = where(p)
366 const done = p.state === 'done'
367 // the fill is exactly the finished share: a fresh plan starts empty
368 const frac = done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))
369 const fx = frac * W
370 const key = p.id
371 // a resize redraws at once: a head drawn at another width would glide in from the wrong place
372 const last = lastHead.get(key)
373 const from = last?.W === W ? last.x : fx
374 lastHead.set(key, { W, x: fx })
375
376 const acc = hex(STATE_COLOR[lookOf(p)])
377 const light = mix(acc, [255, 255, 255], 0.32)
378 const grey = [132, 130, 138]
379 const ease = 'calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .2 1"'
380 const glide = Math.abs(from - fx) > 0.5
381
382 const bounds: number[] = []
383 let acc2 = 0
384 p.stages.forEach((s, i) => {
385 acc2 += s.steps.length
386 if (i < p.stages.length - 1) bounds.push((acc2 / w.total) * W)
387 })
388
389 // pixels: 3px grid, 7 rows, denser towards the head, twinkling and warming from grey to the state colour
390 const buckets = [0, 1, 2, 3, 4].map(b => {
391 const m = b / 4
392 const dense = 0.22 + 0.78 * Math.pow(m, 1.5)
393 return { color: rgb(mix(grey, light, m)), opacity: (0.35 + 0.65 * dense).toFixed(2) }
394 })
395 const dots = new Map<string, string>()
396 for (let col = 0; col * 3 < fx; col++) {
397 const x = col * 3
398 const u = Math.min(1, (x + 1.5) / fx)
399 const dense = 0.22 + 0.78 * Math.pow(u, 1.5)
400 const bucket = Math.min(4, Math.floor(Math.min(1, Math.pow(u, 0.9) * 1.1) * 4.99))
401 for (let r = 0; r < 7; r++) {
402 if (hash(col, r, 1) > dense + 0.1) continue
403 addDot(dots, `b${bucket} t${Math.floor(hash(col, r, 2) * 4)}`, x, 1 + r * 3)
404 }
405 }
406 const px = [...dots].map(([cls, d]) => `<path class="${cls}" d="${d}"/>`).join('')
407
408 const took = stepTimes(p)
409 const tipRules: string[] = []
410 let marks = ''
411 let hits = ''
412 let tips = ''
413 let k = 0
414 p.stages.forEach((s, i) => {
415 s.steps.forEach((_, j) => {
416 if (k > 0) {
417 const x = (k / w.total) * W
418 const isStage = j === 0
419 // a stage boundary is a short capsule, a step a dot; bright once passed
420 const passed = x < fx - 1
421 const fill = passed ? rgb(mix(light, [255, 255, 255], 0.45)) : '#A8A69E'
422 const opacity = passed ? (isStage ? 0.95 : 0.8) : isStage ? 0.75 : 0.6
423 marks += isStage
424 ? `<rect x="${(x - 1.5).toFixed(1)}" y="${(H - 10) / 2}" width="3" height="10" rx="1.5" fill="${fill}" opacity="${opacity}"/>`
425 : `<circle cx="${x.toFixed(1)}" cy="${H / 2}" r="1.4" fill="${fill}" opacity="${opacity}"/>`
426 const before = p.stages[isStage ? i - 1 : i]
427 const ended = isStage ? before?.steps[before.steps.length - 1] : s.steps[j - 1]
428 const label = isStage ? (before?.name ?? '') : (ended?.title ?? '')
429 const ms = isStage ? took.stages[i - 1] : took.steps.get(ended as PlanStep)
430 const text = ms === undefined ? label : `${label} · ${elapsed(ms)}`
431 const tw = textWidth(text, 6.2) + 16
432 const tx = Math.max(0, Math.min(W - tw, x - tw / 2))
433 hits += `<rect class="h${k}" x="${(x - 5).toFixed(1)}" width="10" height="${H}" fill="#000" fill-opacity="0"/>`
434 tips += `<g class="tp p${k}"><rect x="${tx.toFixed(1)}" y="2" width="${tw.toFixed(1)}" height="${H - 4}" rx="${(H - 4) / 2}" fill="#1F1E1D" fill-opacity=".94"/><text x="${(tx + 8).toFixed(1)}" y="${H / 2 + 3.8}" class="tt">${esc(text)}</text></g>`
435 tipRules.push(`.h${k}:hover~.p${k}`)
436 }
437 k++
438 })
439 void i
440 })
441
442 // knob: a pill with stage and count, or a round dot with the stage number when narrow
443 const isNarrow = W < NARROW
444 const color = STATE_COLOR[lookOf(p)]
445 const icon = ICON_PATH[lookOf(p)]
446 const single = p.stages.length === 1
447 const number = single ? w.step : w.stage + 1
448 let knob = ''
449 let timePill = ''
450 let kw = H
451 if (isNarrow) {
452 const label = done ? '' : String(number)
453 knob = `<circle cx="0" cy="${H / 2}" r="${H / 2}" fill="${color}"/>${
454 done ? `<path d="${ICON_PATH[lookOf(p)]}" transform="translate(-6 5) scale(.5)" fill="none" stroke="${INK}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>` : `<text x="0" y="${H / 2 + 4.2}" text-anchor="middle" class="kt">${label}</text>`
455 }`
456 } else {
457 const name = done ? (p.endedAt ? elapsed(p.endedAt - p.startedAt) : 'Done') : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
458 // the pill carries the stage name alone; the fill and the percent already say how far along it is
459 const count = ''
460 const iconW = icon ? 16 : 0
461 const countW = count ? textWidth(count, 6.5) : -6
462 const maxW = Math.max(80, W * 0.55)
463 let shown = name
464 while (shown.length > 3 && 20 + iconW + textWidth(shown) + 6 + countW > maxW) shown = shown.slice(0, -1)
465 if (shown !== name) shown = shown.trimEnd() + '…'
466 // a running pill is wide enough for its clock too, so the hover swap does not change its size
467 const textW = done ? textWidth(shown) : Math.max(textWidth(shown), CLOCK_W)
468 kw = Math.round(20 + iconW + textW + 6 + countW)
469 const left = -(iconW + textW) / 2
470 const mid = left + iconW + textW / 2
471 knob = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>`
472 if (icon) knob += `<path d="${icon}" transform="translate(${left.toFixed(1)} 5) scale(.5)" fill="none" stroke="${INK}" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round"/>`
473 knob += `<text x="${mid.toFixed(1)}" y="${H / 2 + 4.2}" text-anchor="middle" class="kt">${esc(shown)}${count ? `<tspan class="kc" dx="6">${count}</tspan>` : ''}</text>`
474 // hovering the pill lays a copy of it over the stage name, carrying the time the plan has run so far
475 if (!done) {
476 const face = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>${
477 icon ? `<path d="${icon}" transform="translate(${left.toFixed(1)} 5) scale(.5)" fill="none" stroke="${INK}" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round"/>` : ''
478 }`
479 timePill = `<g class="kb"><rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" fill="#000" fill-opacity="0"/><g class="kv">${face}${liveClock(mid - CLOCK_W / 2, 3, p.startedAt, 'kc0', 'kt', true)}</g></g>`
480 }
481 }
482 const clampX = (x: number) => Math.max(kw / 2, Math.min(W - kw / 2, x))
483 const kx = clampX(fx)
484 const kFrom = clampX(from)
485
486 const style = `<style>
487.b0{fill:${buckets[0]?.color};fill-opacity:${buckets[0]?.opacity}}.b1{fill:${buckets[1]?.color};fill-opacity:${buckets[1]?.opacity}}
488.b2{fill:${buckets[2]?.color};fill-opacity:${buckets[2]?.opacity}}.b3{fill:${buckets[3]?.color};fill-opacity:${buckets[3]?.opacity}}
489.b4{fill:${buckets[4]?.color};fill-opacity:${buckets[4]?.opacity}}
490.t0,.t1,.t2,.t3{animation:tw 2.2s ease-in-out infinite}
491.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}
492@keyframes tw{0%,100%{opacity:1}50%{opacity:.45}}
493.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}
494.kc{font-weight:400;fill-opacity:.75}
495@media (prefers-reduced-motion:reduce){.t0,.t1,.t2,.t3{animation:none}}
496</style>`
497 const hoverStyle = `<style>
498.tp{opacity:0;transition:opacity .12s;pointer-events:none}${tipRules.length ? `${tipRules.join(',')}{opacity:1}` : ''}
499.tt{font:400 11px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#F0EEFC}
500.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}
501.kv{opacity:0;filter:blur(3px);transition:opacity .2s,filter .2s}.kb:hover .kv{opacity:1;filter:none}
502.kb,rect[class^="h"]{cursor:pointer}
503${CLOCK_CSS}
504</style>`
505 const glideFill = glide ? `<animate attributeName="width" from="${from.toFixed(1)}" to="${fx.toFixed(1)}" dur=".45s" ${ease} fill="freeze"/>` : ''
506 const glideKnob = glide ? `<animateTransform attributeName="transform" type="translate" from="${kFrom.toFixed(1)} 0" to="${kx.toFixed(1)} 0" dur=".45s" ${ease} fill="freeze"/>` : ''
507
508 const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">`
509 const base = `${open}${style}
510<defs><clipPath id="pill"><rect width="${W}" height="${H}" rx="${H / 2}"/></clipPath><clipPath id="fill"><rect width="${fx.toFixed(1)}" height="${H}">${glideFill}</rect></clipPath>
511<linearGradient id="base" x1="0" x2="${fx.toFixed(1)}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${rgb(acc)}" stop-opacity=".05"/><stop offset="1" stop-color="${rgb(acc)}" stop-opacity=".33"/></linearGradient></defs>
512<g clip-path="url(#pill)"><rect width="${W}" height="${H}" fill="#808080" fill-opacity=".16"/>
513<g clip-path="url(#fill)"><rect width="${fx.toFixed(1)}" height="${H}" fill="url(#base)"/>${px}</g>${marks}</g>
514<g transform="translate(${kx.toFixed(1)} 0)">${glideKnob}${knob}</g></svg>`
515 // the hover layer: checkpoint areas under the pill's copy, so the pill wins where they meet; tips on top
516 const overlay = `${open}${SEE_THROUGH}${hoverStyle}${hits}<g transform="translate(${kx.toFixed(1)} 0)">${timePill}</g>${tips}</svg>`
517
518 return { base, overlay }
519}
520
521const AGENT_COLOR: Record<AgentRun['state'], string> = {
522 running: STATE_COLOR.running,
523 waiting: STATE_COLOR.needs_input,
524 done: STATE_COLOR.done,
525 error: STATE_COLOR.error,
526}
527
528// the desktop drops an Svg whose alt is empty, so every drawing says what it shows
529function stripAlt(p: Plan, key: string): string {
530 const a = (p.agents ?? []).find(x => x.id === key)
531 return a ? `агент ${a.title}: ${a.state}, ${a.tool}` : 'ще агенти'
532}
533
534// an unfinished bar stops at 99%: 199 of 200 steps would otherwise round up to 100%
535function percent(p: Plan, w: { pos: number; total: number }): number {
536 if (p.state === 'done') return 100
537 return Math.min(99, Math.round((Math.min(w.pos, w.total) / Math.max(1, w.total)) * 100))
538}
539
540const elapsed = (ms: number) => {
541 const sec = Math.max(0, Math.round(ms / 1000))
542 if (sec < 60) return `${sec}с`
543 return sec < 3600 ? `${Math.floor(sec / 60)}х ${sec % 60}с` : `${Math.floor(sec / 3600)}г ${Math.floor((sec % 3600) / 60)}х`
544}
545
546// which strips show: all of a small batch; in a big one the unfinished first, the rest folded into one line
547function visibleAgents(p: Plan, now: number, max: number): { shown: AgentRun[]; hidden: AgentRun[] } | null {
548 const list = p.agents ?? []
549 if (list.length === 0) return null
550 const hasError = list.some(a => a.state === 'error')
551 if (p.agentsDoneAt && now - p.agentsDoneAt > FOLD_MS && !hasError) return null
552 if (list.length <= max) return { shown: list, hidden: [] }
553 const keep = new Set(list.filter(a => a.state !== 'done').slice(0, max - 1).map(a => a.id))
554 for (const a of [...list].reverse()) {
555 if (keep.size >= max - 1) break
556 keep.add(a.id)
557 }
558 return { shown: list.filter(a => keep.has(a.id)), hidden: list.filter(a => !keep.has(a.id)) }
559}
560
561// what each strip showed last time it was drawn, so a change morphs from the old status instead of jumping
562const lastStrip = new Map<string, { tool: string; color: string }>()
563const MORPH = '.2s'
564
565// a strip's markup per agent object: drawn once per change, so its morph plays once and later redraws match
566const drawnRows = new WeakMap<AgentRun, { key: string; html: string }>()
567
568
569// one tinted strip per agent: state colour, name, what it does now and for how long; not a progress bar
570// Lucide "bot", drawn at 12 px in the gutter before each strip
571const BOT = '<rect width="16" height="12" x="4" y="8" rx="2"/><path d="M12 8V4H8M2 14h2M20 14h2M15 13v2M9 13v2"/>'
572const GUTTER = 36 // icon and agent number, left of the strip
573
574// claude-haiku-4-5-20251001 -> haiku 4.5; an alias stays as given
575const modelName = (m: string) => {
576 const r = /^claude-([a-z]+)-(\d+)-(\d+)/.exec(m)
577 return r ? `${r[1]} ${r[2]}.${r[3]}` : m
578}
579
580// the agent's name, its model and effort in a dimmer parenthesis
581const nameMarkup = (name: string) => {
582 const at = name.indexOf(' (')
583 return at > 0 ? `${esc(name.slice(0, at))}<tspan class="st">${esc(name.slice(at))}</tspan>` : esc(name)
584}
585
586// one tinted strip per agent behind a bot icon and its number: the colour says how it went,
587// the word says what it does now (only while it runs or waits), the time how long it took
588type StripRow = { key: string; html: string; height: number }
589
590// each strip is its own drawing, so a change to one agent redraws that strip alone, never the bar or the others
591function stripsSvg(v: { shown: AgentRun[]; hidden: AgentRun[] }, all: AgentRun[], W: number): StripRow[] {
592 const isNarrow = W < NARROW
593 const SW = W - GUTTER
594 const rows: StripRow[] = []
595 const gutter = (y: number, label: string, color: string) =>
596 `<g transform="translate(1 ${y + 2}) scale(.5)" fill="none" stroke="${color}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">${BOT}</g>` +
597 `<text x="16" y="${y + 11.5}" class="sn sg" style="fill:${color}">${label}</text>`
598 v.shown.forEach((a, i) => {
599 // the first strip keeps a little room from the track above it
600 const y = i === 0 ? 5 : STRIP_GAP
601 const rowKey = `${W}|${y}|${all.indexOf(a)}`
602 const cachedRow = drawnRows.get(a)
603 if (cachedRow?.key === rowKey) {
604 rows.push({ key: a.id, html: cachedRow.html, height: y + STRIP_H })
605 return
606 }
607 const c = AGENT_COLOR[a.state]
608 const indent = a.depth > 0 ? 10 : 0
609 const word = a.state === 'running' || a.state === 'waiting' ? a.tool : ''
610 const dots = new Map<string, string>()
611 if (a.state === 'running') {
612 for (let col = 0; col * 3 < SW; col++) {
613 for (let r = 0; r < 4; r++) {
614 if (hash(col + i * 41, r, 5) > 0.2) continue
615 addDot(dots, `t${Math.floor(hash(col, r, 6) * 4)}`, GUTTER + col * 3, Math.round((y + 2.5 + r * 3.2) * 10) / 10)
616 }
617 }
618 }
619 const px = [...dots].map(([cls, d]) => `<path class="${cls}" fill="${c}" fill-opacity=".32" d="${d}"/>`).join('')
620 // a status change: the old word blurs out while the new one blurs in, and the tint flows to the new colour
621 const was = lastStrip.get(a.id)
622 lastStrip.set(a.id, { tool: word, color: c })
623 const isWordChanged = was !== undefined && was.tool !== word
624 const flow = (attr: string) => (was && was.color !== c ? `<animate attributeName="${attr}" from="${was.color}" to="${c}" dur="${MORPH}" fill="freeze"/>` : '')
625 // the tool word sits at the right, just before the clock, so the name and its model get the rest of the row
626 const toolEnd = W - 9 - CLOCK_W - 10
627 const wordW = Math.max(word ? textWidth(word, 6.2) : 0, isWordChanged && was.tool ? textWidth(was.tool, 6.2) : 0)
628 const nameX = GUTTER + 19 + indent
629 const nameRoom = isNarrow ? SW - 24 - indent : toolEnd - (wordW > 0 ? wordW + 12 : 0) - nameX
630 const spec = [a.model ? modelName(a.model) : '', a.effort ?? ''].filter(Boolean).join(' · ')
631 const full = (a.depth > 0 ? '↳ ' : '') + a.title + (spec ? ` (${spec})` : '')
632 let name = full
633 while (name.length > 4 && textWidth(name, 6.2) > nameRoom) name = name.slice(0, -1)
634 if (name !== full) name = name.trimEnd() + '…'
635 const time =
636 a.endedAt === null
637 ? liveClock(W - 9 - CLOCK_W, y, a.startedAt, 'sc', 'sn st')
638 : `<text x="${W - 9}" y="${y + 11.5}" text-anchor="end" class="sn st">${elapsed(a.endedAt - a.startedAt)}</text>`
639 const tool = isNarrow
640 ? ''
641 : (isWordChanged && was.tool ? `<text x="${toolEnd}" y="${y + 11.5}" text-anchor="end" class="sn mo" style="fill:${was.color}">${esc(was.tool)}</text>` : '') +
642 (word ? `<text x="${toolEnd}" y="${y + 11.5}" text-anchor="end" class="sn${isWordChanged ? ' mi' : ''}" style="fill:${c}">${esc(word)}</text>` : '') +
643 time
644 const html =
645 gutter(y, String(all.indexOf(a) + 1), '#A8A69E') +
646 `<rect x="${GUTTER}" y="${y}" width="${SW}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="${c}" fill-opacity=".15">${flow('fill')}</rect>${px}` +
647 `<circle cx="${GUTTER + 10 + indent}" cy="${y + STRIP_H / 2}" r="3" fill="${c}"${a.state === 'running' ? ' class="sd"' : ''}>${flow('fill')}</circle>` +
648 `<text x="${nameX}" y="${y + 11.5}" class="sn">${nameMarkup(name)}</text>` +
649 tool
650 drawnRows.set(a, { key: rowKey, html })
651 rows.push({ key: a.id, html, height: y + STRIP_H })
652 })
653 if (v.hidden.length > 0) {
654 const y = v.shown.length === 0 ? 5 : STRIP_GAP
655 const doneCount = v.hidden.filter(a => a.state === 'done').length
656 rows.push({
657 key: '+',
658 height: y + STRIP_H,
659 html:
660 gutter(y, `+${v.hidden.length}`, '#8A8984') +
661 `<rect x="${GUTTER}" y="${y}" width="${SW}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="#808080" fill-opacity=".14"/>` +
662 `<text x="${GUTTER + 10}" y="${y + 11.5}" class="sn st">ще ${plural(v.hidden.length, ['агент', 'агенти', 'агентів'])} · ${doneCount} готово</text>`,
663 })
664 }
665 return rows
666}
667
668const STRIP_STYLE = `<style>.sn{font:400 11.5px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#F0EEFC}.st{fill-opacity:.65}.sg{font-weight:500;font-variant-numeric:tabular-nums}
669.sd{animation:sp 1.1s ease-in-out infinite}@keyframes sp{50%{opacity:.3}}
670.mi{animation:mi ${MORPH} ease-out both}@keyframes mi{from{opacity:0;filter:blur(3px)}}
671.mo{animation:mo ${MORPH} ease-in both}@keyframes mo{to{opacity:0;filter:blur(3px)}}
672.t0,.t1,.t2,.t3{animation:tw 2.2s ease-in-out infinite}.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}
673@keyframes tw{0%,100%{opacity:1}50%{opacity:.45}}
674${CLOCK_CSS}
675@media (prefers-reduced-motion:reduce){.sd,.mi,.mo,.t0,.t1,.t2,.t3{animation:none}.mo{opacity:0}}</style>`
676
677// Ukrainian plural: 1 агент, 2-4 агенти, 5+ і 11-14 агентів
678function plural(n: number, forms: [string, string, string]) {
679 const m10 = n % 10
680 const m100 = n % 100
681 const form = m10 === 1 && m100 !== 11 ? forms[0] : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? forms[1] : forms[2]
682
683 return `${n} ${form}`
684}
685
686const DEFAULT = 0x01000000
687let isLight = false
688const termBg = () => (isLight ? [255, 255, 255] : [24, 24, 27])
689const termFg = () => (isLight ? [34, 34, 38] : [240, 238, 252])
690const pack = (c: number[]) => ((c[0] ?? 0) << 16) | ((c[1] ?? 0) << 8) | (c[2] ?? 0)
691const isWide = (cp: number) => cp > 0xffff || (cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) || (cp >= 0xffe0 && cp <= 0xffe6)
692const cellText = (s: string) => [...s].map(ch => (isWide(ch.codePointAt(0) ?? 63) || (ch.codePointAt(0) ?? 0) < 32 ? '·' : ch)).join('')
693const cellsOf = (s: string) => [...s].reduce((w, ch) => w + (isWide(ch.codePointAt(0) ?? 0) ? 2 : 1), 0)
694const fit = (s: string, w: number) => {
695 const chars = [...cellText(s)]
696 if (chars.length <= w) return chars.join('')
697 return w <= 1 ? '…'.slice(0, w) : chars.slice(0, w - 1).join('').trimEnd() + '…'
698}
699
700type Cell = [number, number, number]
701
702class Grid {
703 cells: Cell[]
704 constructor(
705 readonly columns: number,
706 readonly rows: number,
707 ) {
708 this.cells = Array.from({ length: columns * rows }, () => [32, DEFAULT, DEFAULT] as Cell)
709 }
710 set(x: number, y: number, ch: string | number, fg: number, bg: number) {
711 if (x < 0 || x >= this.columns || y < 0 || y >= this.rows) return
712 this.cells[y * this.columns + x] = [typeof ch === 'number' ? ch : (ch.codePointAt(0) ?? 32), fg, bg]
713 }
714 bg(x: number, y: number) {
715 return this.cells[y * this.columns + x]?.[2] ?? DEFAULT
716 }
717 text(x: number, y: number, s: string, fg: number, bg?: number) {
718 let i = 0
719 for (const ch of cellText(s)) {
720 this.set(x + i, y, ch, fg, bg ?? this.bg(x + i, y))
721 i++
722 }
723 return i
724 }
725 encode() {
726 const words = new Uint32Array(this.cells.length * 3)
727 this.cells.forEach((c, i) => words.set(c, i * 3))
728 return (new Uint8Array(words.buffer) as Uint8Array & { toBase64: () => string }).toBase64()
729 }
730}
731
732const BRAILLE_BITS = [
733 [0x01, 0x08],
734 [0x02, 0x10],
735 [0x04, 0x20],
736 [0x40, 0x80],
737]
738
739function pill(g: Grid, y: number, from: number, to: number, bgAt: (x: number) => number[]) {
740 for (let x = from; x < to; x++) g.set(x, y, ' ', DEFAULT, pack(bgAt(x)))
741}
742
743const LEVELS = 8
744const q = (m: number) => Math.round(Math.max(0, Math.min(1, m)) * LEVELS) / LEVELS
745const wave = (t: number, periodMs: number, offset = 0) => 0.5 + 0.5 * Math.sin(((t / periodMs) + offset) * Math.PI * 2)
746const easeOut = (x: number) => 1 - Math.pow(1 - Math.max(0, Math.min(1, x)), 4)
747
748const glide = new Map<string, { from: number; to: number; at: number }>()
749const GLIDE_MS = 450
750
751function headAt(id: string, target: number, t: number): number {
752 const g = glide.get(id)
753 if (!g) {
754 glide.set(id, { from: target, to: target, at: t })
755 return target
756 }
757 const cur = g.from + (g.to - g.from) * easeOut((t - g.at) / GLIDE_MS)
758 if (Math.abs(g.to - target) > 0.01) {
759 glide.set(id, { from: cur, to: target, at: t })
760 return cur
761 }
762 return cur
763}
764
765
766function trackCells(p: Plan, W: number, t: number): string {
767 const g = new Grid(W, 1)
768 const w = where(p)
769 const done = p.state === 'done'
770 const target = (done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))) * W
771 const fx = headAt(p.id, target, t)
772 const back = termBg()
773 const acc = hex(STATE_COLOR[lookOf(p)])
774 const light = mix(acc, [255, 255, 255], 0.35)
775 const grey = [120, 118, 128]
776 const track = mix(back, [128, 128, 128], isLight ? 0.14 : 0.18)
777 const fill = mix(track, acc, done ? 0.3 : 0.17)
778 const under = (x: number) => (x + 0.5 < fx ? fill : track)
779 pill(g, 0, 0, W, under)
780
781 const TWINKLE = done ? [3200, 3800, 4400, 3500] : [2200, 2800, 1900, 3300]
782 const DELAY = [0, 700, 1300, 400]
783 const dim = done ? 0.2 : 0.55
784 for (let col = 0; col < Math.min(W, Math.ceil(fx)); col++) {
785 const u = Math.min(1, (col + 0.5) / Math.max(1, fx))
786 const dense = done ? 0.8 : 0.22 + 0.78 * Math.pow(u, 1.5)
787 let bits = 0
788 for (let r = 0; r < 4; r++) {
789 for (let c = 0; c < 2; c++) {
790 const sx = col * 2 + c
791 if (sx / 2 >= fx || hash(sx, r, 1) > dense * 0.6) continue
792 bits |= BRAILLE_BITS[r]?.[c] ?? 0
793 }
794 }
795 if (bits === 0) continue
796 const cls = Math.floor(hash(col, 0, 2) * 4)
797 const period = TWINKLE[cls] ?? 2200
798 const blink = 1 - dim * wave(t + (DELAY[cls] ?? 0), period, 0.25)
799 const bucket = done ? 1 : q(Math.min(1, Math.pow(u, 0.9) * 1.1))
800 const tone = mix(grey, light, bucket)
801 const opacity = (0.35 + 0.65 * dense) * blink
802 g.set(col, 0, 0x2800 + bits, pack(mix(fill, tone, q(opacity))), pack(fill))
803 }
804
805 let k = 0
806 p.stages.forEach(s => {
807 if (k > 0) {
808 const x = Math.round((k / w.total) * W)
809 if (x > 0 && x < W - 1) {
810 const passed = x < fx - 0.5
811 g.set(x, 0, '│', pack(passed ? mix(light, [255, 255, 255], 0.5) : mix(track, isLight ? [0, 0, 0] : [255, 255, 255], 0.3)), pack(under(x)))
812 }
813 }
814 k += s.steps.length
815 })
816
817 const base = hex(STATE_COLOR[lookOf(p)])
818 const color = base
819 const single = p.stages.length === 1
820 const number = single ? Math.min(w.total, w.pos + 1) : w.stage + 1
821 const icon = hasFailedStep(p) ? '✕' : p.state === 'done' ? '✓' : p.state === 'error' ? '✕' : p.state === 'needs_input' ? '?' : ''
822 let name = ''
823 let count = ''
824 if (W < 28) {
825 name = icon || String(number)
826 } else {
827 const agents = p.agents ?? []
828 name = done ? 'Done' : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
829 const baseCount = p.id === AGENTS ? `${w.pos}/${w.total}` : done ? `${w.total}/${w.total}` : single ? `${number}/${w.total}` : `${w.step}/${w.stageSize}`
830 count = baseCount + (agents.length > 0 && p.id !== AGENTS ? ` · ${agents.filter(a => a.state === 'done').length}/${agents.length}` : '')
831 }
832 const lead = icon && W >= 28 ? `${icon} ` : ''
833 const maxName = Math.max(3, Math.floor(W * (W < 60 ? 0.75 : 0.55)) - cellsOf(lead) - cellsOf(count) - 5)
834 const shown = lead + fit(name, maxName)
835 const kw = cellsOf(shown) + (count ? count.length + 1 : 0) + 2
836 const kx = Math.round(Math.max(0, Math.min(W - kw, fx - kw / 2)))
837 const white = pack([255, 255, 255])
838 pill(g, 0, kx, kx + kw, () => color)
839 let at = kx + 1
840 at += g.text(at, 0, shown, white, pack(color))
841 if (count) g.text(at + 1, 0, count, pack(mix([255, 255, 255], color, 0.3)), pack(color))
842 return g.encode()
843}
844
845function stripCells(v: { shown: AgentRun[]; hidden: AgentRun[] }, W: number, now: number): { cells: string; rows: number } {
846 const rows = v.shown.length + (v.hidden.length > 0 ? 1 : 0)
847 const g = new Grid(W, rows)
848 const back = termBg()
849 const text = pack(termFg())
850 v.shown.forEach((a, y) => {
851 const c = hex(AGENT_COLOR[a.state])
852 const tint = mix(back, c, 0.18)
853 pill(g, y, 0, W, () => tint)
854 const running = a.state === 'running' || a.state === 'waiting'
855 if (running) {
856 for (let col = 1; col < W - 1; col++) {
857 let bits = 0
858 let glow = 0
859 for (let r = 0; r < 4; r++) {
860 for (let cc = 0; cc < 2; cc++) {
861 const sx = col * 2 + cc + y * 83
862 if (hash(sx, r, 5) >= 0.08) continue
863 const b = 1 - 0.55 * wave(now, 1900 + hash(sx, r, 6) * 1400, hash(sx, r, 7))
864 bits |= BRAILLE_BITS[r]?.[cc] ?? 0
865 glow = Math.max(glow, b)
866 }
867 }
868 if (bits) g.set(col, y, 0x2800 + bits, pack(mix(tint, c, 0.2 + 0.4 * q(glow))), pack(tint))
869 }
870 }
871 const indent = a.depth > 0 ? 2 : 0
872 const dotColor = running ? mix(tint, c, 0.3 + 0.7 * q(wave(now, 1100))) : c
873 g.text(2 + indent, y, '●', pack(dotColor), pack(tint))
874 const time = elapsed((a.endedAt ?? now) - a.startedAt)
875 const narrow = W < 30
876 const tx = W - 2 - time.length
877 // the tool word sits at the right, just before the time, so the name and its model get the rest of the row
878 const word = narrow || !running ? '' : fit(a.tool, Math.max(0, Math.floor(W * 0.25)))
879 const toolAt = tx - 1 - word.length
880 let at = 4 + indent
881 const spec = [a.model ? modelName(a.model) : '', a.effort ?? ''].filter(Boolean).join(' · ')
882 const full = (a.depth > 0 ? '↳ ' : '') + a.title + (spec ? ` (${spec})` : '')
883 const name = fit(full, Math.max(3, (narrow ? W - 2 : word ? toolAt - 1 : tx - 1) - at))
884 // the model and effort are drawn dimmer than the name
885 const cut = spec ? name.indexOf(' (') : -1
886 const head = cut > 0 ? name.slice(0, cut) : name
887 for (let i = -1; i < name.length + 1 && at + i < W - 1; i++) g.set(at + i, y, ' ', DEFAULT, pack(tint))
888 at += g.text(at, y, head, text, pack(tint))
889 if (head !== name) g.text(at, y, name.slice(head.length), pack(mix(termFg(), tint, 0.4)), pack(tint))
890 if (narrow) return
891 if (word) {
892 for (let i = -1; i <= word.length; i++) g.set(toolAt + i, y, ' ', DEFAULT, pack(tint))
893 g.text(toolAt, y, word, pack(c), pack(tint))
894 }
895 for (let i = -1; i < time.length; i++) g.set(tx + i, y, ' ', DEFAULT, pack(tint))
896 g.text(tx, y, time, pack(mix(termFg(), tint, 0.35)), pack(tint))
897 })
898 if (v.hidden.length > 0) {
899 const y = v.shown.length
900 const tint = mix(back, [128, 128, 128], 0.16)
901 pill(g, y, 0, W, () => tint)
902 const doneCount = v.hidden.filter(a => a.state === 'done').length
903 g.text(2, y, fit(`+ще ${plural(v.hidden.length, ['агент', 'агенти', 'агентів'])} · ${doneCount} готово`, W - 4), pack(mix(termFg(), tint, 0.35)), pack(tint))
904 }
905 return { cells: g.encode(), rows }
906}
907
908type Band = { requestId: string; W: number; list: readonly Plan[] }
909let band: Band | null = null
910let isFrameBusy = false
911// a bar twinkles only while Claude works on it; one waiting on the person or left open after the turn stands still
912let isTurnLive = false
913let frames: { cancel: () => void } | null = null
914
915const hasRunningAgents = (p: Plan) => (p.agents ?? []).some(a => a.state === 'running' || a.state === 'waiting')
916const isGliding = (p: Plan, t: number) => {
917 const g = glide.get(p.id)
918 return g !== undefined && g.from !== g.to && t - g.at < GLIDE_MS + 100
919}
920const isAnimated = (p: Plan, t: number) => (isTurnLive && p.state === 'running') || hasRunningAgents(p) || isGliding(p, t)
921
922// the 30 fps clock runs only while a terminal band has something moving; the second timer starts and stops it
923function syncFrames($: EngineInterface, now: number) {
924 const isWanted = band !== null && band.list.some(p => isAnimated(p, now))
925 if (isWanted && !frames) frames = $.clock.every(33, () => void animate($))
926 if (!isWanted && frames) {
927 frames.cancel()
928 frames = null
929 }
930}
931
932// ---------- terminal tint ----------
933// the track's light or dark tint: a theme the person picked wins; "auto", and the default "dark" inside Terminal.app
934// (whose stock profiles follow macOS), take the macOS appearance. The appearance is read only while a terminal bar
935// is on screen, at most every APPEARANCE_MS, and never again once the command turns out to be missing (not a Mac)
936const APPEARANCE_MS = 5000
937let themeSetting = 'dark'
938let mac: 'unknown' | 'yes' | 'no' = 'unknown'
939let termProgram = ''
940let isSystemDark: boolean | null = null
941let appearanceAt = -Infinity
942let isProbing = false
943
944const followsSystem = () => mac !== 'no' && (themeSetting === 'auto' || (themeSetting === 'dark' && (mac === 'unknown' || termProgram === 'Apple_Terminal')))
945const tintIsLight = () => (followsSystem() && isSystemDark !== null ? !isSystemDark : /light/i.test(themeSetting))
946
947async function probeAppearance($: EngineInterface, now: number) {
948 if (isProbing || !followsSystem() || now - appearanceAt < APPEARANCE_MS) return
949 isProbing = true
950 appearanceAt = now
951 try {
952 const r = await $.process.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: 2000 }).catch(() => null)
953 if (!r) {
954 // no such command: not a Mac, so the theme setting alone decides from here on
955 mac = 'no'
956 return
957 }
958 if (mac === 'unknown') {
959 const t = await $.process.run(['/bin/sh', '-c', 'printf %s "$TERM_PROGRAM"'], { timeoutMs: 2000 }).catch(() => null)
960 termProgram = t?.stdout.trim() ?? ''
961 mac = 'yes'
962 }
963 // the key is missing in light mode, so anything but "Dark" reads as light
964 isSystemDark = /dark/i.test(r.stdout)
965 } finally {
966 isProbing = false
967 }
968}
969
970// reads the appearance when due and repaints the bars at once if the tint changed
971async function syncTint($: EngineInterface, now: number) {
972 if (band) await probeAppearance($, now)
973 const next = tintIsLight()
974 if (next === isLight) return
975 isLight = next
976 const b = band
977 if (b) await blitPlans($, b, b.list, now)
978}
979
980function blitPlans($: EngineInterface, b: Band, list: readonly Plan[], now: number) {
981 return Promise.all(
982 list.flatMap(p => {
983 const v = visibleAgents(p, now, stripBudget(b.list.length))
984 const strips = v ? stripCells(v, b.W, now) : null
985 const calls = [$.ui.blit({ requestId: b.requestId, key: `track-${p.id}`, cells: trackCells(p, b.W, now) })]
986 if (strips) calls.push($.ui.blit({ requestId: b.requestId, key: `strips-${p.id}`, cells: strips.cells }))
987 return calls.map(c => c.catch(() => undefined))
988 }),
989 )
990}
991
992async function animate($: EngineInterface) {
993 const b = band
994 if (!b || isFrameBusy) return
995 const now = await $.clock.now()
996 const live = b.list.filter(p => isAnimated(p, now))
997 if (live.length === 0) return
998 isFrameBusy = true
999 try {
1000 await blitPlans($, b, live, now)
1001 } finally {
1002 isFrameBusy = false
1003 }
1004}
1005
1006
1007// ---------- engine glue ----------
1008
1009// the engine's player (afplay on macOS); the Windows PowerShell fallback of upstream is removed in the qa-mods fork
1010// set while a demo reel records: every sound with its moment, so a video can carry them
1011let soundLog: { at: number; name: string }[] | null = null
1012
1013function play($: EngineInterface, name: 'decision' | 'error' | 'done') {
1014 if (soundLog) void $.clock.now().then(at => soundLog?.push({ at, name }))
1015 void $.audio.play({ asset: `sounds/${name}.wav` }).catch(() => undefined)
1016}
1017
1018// the agents bar is the mod's own; the model never owes it an update
1019const AGENTS = 'agents:auto' // slug() never yields ':', so no model id can take it
1020const isOpenPlan = (p: Plan) => p.id !== AGENTS && p.state === 'running' && !p.stages.flatMap(s => s.steps).every(s => isFinished(s.status))
1021// a bar left in `error` (the model sent {failed}) is still unfinished work: the reminders cover it too, or it stays
1022// stuck at its old percent for the rest of the chat (seen in a VS Code chat, 15.10.2026). Agent strips still go only to a running bar.
1023const needsUpdate = (p: Plan) => isOpenPlan(p) || (p.id !== AGENTS && p.state === 'error' && !p.stages.flatMap(s => s.steps).every(s => isFinished(s.status)))
1024
1025const slug = (s: string) =>
1026 s
1027 .toLowerCase()
1028 .replace(/[^\p{L}\p{N}]+/gu, '-')
1029 .replace(/^-|-$/g, '')
1030 .slice(0, 40) || 'plan'
1031
1032// adds or replaces one bar by id; keeps at most MAX_BARS, dropping finished ones first
1033// computed inside update() from the latest list, so concurrent writers (parallel agents) do not drop each other
1034function placeBar(list: readonly Plan[], next: Plan): Plan[] {
1035 const prev = list.find(p => p.id === next.id)
1036 // an update keeps its row and, unless it brings its own, the agent strips already on it; a new bar goes to the bottom
1037 const kept = prev && !('agents' in next) ? { ...next, agents: prev.agents, agentsDoneAt: prev.agentsDoneAt } : next
1038 const rest = prev ? list.map(p => (p.id === next.id ? kept : p)) : [...list, next]
1039 // the oldest finished bar goes first, then the oldest running one; the bar just placed and a bar waiting on the
1040 // person or showing an error stay while any other can go, though the mod's own Agents bar gives way to them
1041 // fork (qa-mods): finished bars no longer count against MAX_BARS, so a sixth bar cannot push a green one out;
1042 // they stay until closed with ✕, and only the MAX_DONE newest are kept
1043 const live = (p: Plan) => p.state !== 'done'
1044 const pick = (ok: (p: Plan) => boolean) => rest.findIndex(p => p.id !== next.id && live(p) && ok(p))
1045 while (rest.filter(live).length > MAX_BARS) {
1046 const ownAgents = next.id === AGENTS ? rest.findIndex(p => p.id === AGENTS) : -1
1047 const at = [pick(p => p.state === 'running'), ownAgents, pick(() => true)].find(i => i >= 0) ?? rest.findIndex(live)
1048 rest.splice(at, 1)
1049 }
1050 while (rest.filter(p => !live(p)).length > MAX_DONE) {
1051 const at = rest.findIndex(p => p.id !== next.id && !live(p))
1052 if (at < 0) break
1053 rest.splice(at, 1)
1054 }
1055 return rest
1056}
1057
1058// fork (qa-mods): the steps of one bar for the expanded view; a footer gives the stage, the time and the note
1059const STEP_GLYPH: Record<StepStatus, string> = { pending: '○', active: '●', done: '✓', error: '✕', skipped: '–' }
1060const STEP_COLOR: Record<StepStatus, string | undefined> = { pending: undefined, active: STATE_COLOR.running, done: STATE_COLOR.done, error: STATE_COLOR.error, skipped: undefined }
1061function detailBox(p: Plan, w: ReturnType<typeof where>, now: number, ui: { Box: any; Text: any }) {
1062 const { Box, Text } = ui
1063 const rows = p.stages.flatMap(s => s.steps.map(st => ({ st, key: `${s.name}-${st.title}` })))
1064 const spent = elapsed((p.endedAt ?? now) - p.startedAt)
1065 const footer =
1066 p.state === 'done'
1067 ? `Завершено за ${spent}`
1068 : `Крок ${Math.min(w.pos + 1, w.total)} з ${w.total} · етап ${w.stage + 1} з ${p.stages.length} · ${spent}${p.note ? ` · ${p.note}` : ''}`
1069 return (
1070 <Box key={`detail-${p.id}`} flexDirection="column" paddingLeft={3}>
1071 {rows.map(({ st, key }) => (
1072 <Text key={key} dimColor={st.status === 'pending' || st.status === 'skipped'}>
1073 <Text color={STEP_COLOR[st.status]}>{STEP_GLYPH[st.status]}</Text>
1074 {` ${st.title}`}
1075 {st.detail ? <Text dimColor>{` — ${st.detail}`}</Text> : null}
1076 </Text>
1077 ))}
1078 <Text dimColor>{footer}</Text>
1079 </Box>
1080 )
1081}
1082
1083function chime($: EngineInterface, prev: PlanState | undefined, next: PlanState) {
1084 if (next === prev) return
1085 if (next === 'needs_input') play($, 'decision')
1086 if (next === 'error') play($, 'error')
1087 if (next === 'done') play($, 'done')
1088}
1089
1090async function putPlan($: EngineInterface, next: Plan) {
1091 await editPlan($, next.id, () => next)
1092}
1093
1094// builds a bar from the latest stored one inside update(), so back-to-back calls never work from a stale copy;
1095// make returns a string to refuse, and the list stays as it was
1096async function editPlan($: EngineInterface, id: string, make: (prev: Plan | null) => Plan | string, isQuiet = false): Promise<Plan | string> {
1097 let prev: Plan | undefined
1098 let made = '' as Plan | string
1099 await update($, plans, list => {
1100 prev = list.find(p => p.id === id)
1101 made = make(prev ?? null)
1102 return typeof made === 'string' ? [...list] : placeBar(list, made)
1103 })
1104 if (typeof made === 'string') return made
1105 if (!isQuiet) chime($, prev?.state, made.state)
1106 if (!prev) await update($, isOpen, () => true)
1107 return made
1108}
1109
1110// ---------- agents: drawn from engine events alone, no model calls ----------
1111// each subagent lives on a bar as one state strip: the open task bar it was started under,
1112// the bar of its parent agent, or the mod's own "Agents" bar when no task is open.
1113// Module maps: a reload forgets running agents, whose strips then stay until the bar is closed.
1114const agentHome = new Map<string, string>() // agentId -> bar id
1115// an agent's calls in flight, tool_use_id first: the tool, and whether a permission dialog for it is in front of the person.
1116// Kept per call, since one agent may run several calls at once and only some of them ask.
1117type Flight = { agentId: string; tool: string; isAsked: boolean }
1118const flights = new Map<string, Flight>()
1119let flightCount = 0
1120let foldUntil = 0 // keep ticking until finished strips have folded
1121
1122// the mod's own bar mirrors its agents as steps, finished first, so percent and count read done/total
1123function syncAuto(p: Plan, now: number): Plan {
1124 const agents = p.agents ?? []
1125 const isOver = agents.length > 0 && agents.every(a => a.state === 'done' || a.state === 'error')
1126 const agentsDoneAt = isOver ? (p.agentsDoneAt ?? now) : null
1127 if (p.id !== AGENTS) return { ...p, agentsDoneAt }
1128 const rank = (a: AgentRun) => (a.state === 'done' ? 0 : a.state === 'error' ? 1 : 2)
1129 const steps: PlanStep[] = [...agents]
1130 .sort((a, b) => rank(a) - rank(b))
1131 .map(a => ({ title: a.title, status: a.state === 'done' ? 'done' : a.state === 'error' ? 'error' : 'active', substeps: [] }))
1132 const state: PlanState = isOver
1133 ? agents.some(a => a.state === 'error') ? 'error' : 'done'
1134 : agents.some(a => a.state === 'waiting') ? 'needs_input' : 'running'
1135 // the pill says how many are still at work; the bar's title already says "Agents"
1136 const running = agents.filter(a => a.state === 'running' || a.state === 'waiting').length
1137 return { ...p, agentsDoneAt, stages: [{ name: isOver ? 'Агенти' : `${running} працює`, steps }], state }
1138}
1139
1140function addRun(p: Plan, run: AgentRun, parentId: string | undefined, now: number): Plan {
1141 // a batch that has finished makes room for the next one
1142 const list = p.agentsDoneAt ? [] : [...(p.agents ?? [])]
1143 let at = list.length
1144 const parentAt = parentId ? list.findIndex(a => a.id === parentId) : -1
1145 if (parentAt >= 0) {
1146 at = parentAt + 1
1147 while (at < list.length && (list[at]?.depth ?? 0) > 0) at++
1148 }
1149 list.splice(at, 0, run)
1150 return syncAuto({ ...p, agents: list, agentsDoneAt: null }, now)
1151}
1152
1153// an agent's strip from its calls in flight: amber while any of them has a dialog up, else the latest tool;
1154// a finished agent stays as it is
1155async function showAgent($: EngineInterface, agentId: string, endedTool?: string) {
1156 const mine = [...flights.values()].filter(f => f.agentId === agentId)
1157 const isAsked = mine.some(f => f.isAsked)
1158 const tool = isAsked ? 'Needs approval' : (mine.at(-1)?.tool ?? endedTool)
1159 await editAgent($, agentId, a =>
1160 a.state === 'running' || a.state === 'waiting' ? { ...a, state: isAsked ? 'waiting' : 'running', tool: tool ?? a.tool } : a,
1161 )
1162}
1163
1164function forgetFlights(agentId: string) {
1165 for (const [id, f] of flights) if (f.agentId === agentId) flights.delete(id)
1166}
1167
1168// changes one agent's strip inside the latest list; silent, since a subagent answers to Claude, not to the person
1169async function editAgent($: EngineInterface, agentId: string, change: (a: AgentRun) => AgentRun) {
1170 const home = agentHome.get(agentId)
1171 if (!home) return
1172 const now = await $.clock.now()
1173 let isFolding = false
1174 await update($, plans, list =>
1175 list.map(p => {
1176 if (p.id !== home || !p.agents?.some(a => a.id === agentId)) return p
1177 const next = syncAuto({ ...p, agents: p.agents.map(a => (a.id === agentId ? change(a) : a)) }, now)
1178 isFolding = !p.agentsDoneAt && next.agentsDoneAt !== null
1179 return next
1180 }),
1181 )
1182 if (isFolding) foldUntil = now + FOLD_MS + 200
1183}
1184
1185// module maps outlive the bars they describe: a bar pushed out past MAX_BARS, a cleared list, an agent
1186// whose finish never arrived (killed, or started before a reload); drop what no bar holds any more
1187function forgetGone(list: readonly Plan[]) {
1188 const bars = new Set(list.map(p => p.id))
1189 const live = new Set(list.flatMap(p => (p.agents ?? []).filter(a => a.state === 'running' || a.state === 'waiting').map(a => a.id)))
1190 const shown = new Set(list.flatMap(p => (p.agents ?? []).map(a => a.id)))
1191 for (const id of lastHead.keys()) if (!bars.has(id)) lastHead.delete(id)
1192 for (const id of glide.keys()) if (!bars.has(id)) glide.delete(id)
1193 for (const id of lastStrip.keys()) if (!shown.has(id)) lastStrip.delete(id)
1194 for (const [id, home] of agentHome) {
1195 if (bars.has(home) && live.has(id)) continue
1196 agentHome.delete(id)
1197 forgetFlights(id)
1198 }
1199}
1200types/index.d.ts 49 lines1export type StepStatus = 'pending' | 'active' | 'done' | 'error' | 'skipped'
2export type PlanSubstep = { title: string; status: StepStatus }
3// doneAt: when the step was finished, so a checkpoint can tell how long it took
4export type PlanStep = { title: string; status: StepStatus; substeps: PlanSubstep[]; doneAt?: number; detail?: string }
5export type PlanStage = { name: string; steps: PlanStep[] }
6export type PlanState = 'running' | 'needs_input' | 'error' | 'done'
7// one subagent shown as a state strip under a bar; depth 1 sits under its parent agent
8export type AgentRun = {
9 id: string
10 title: string
11 state: 'running' | 'waiting' | 'done' | 'error'
12 tool: string
13 startedAt: number
14 endedAt: number | null
15 depth: number
16 // the model it runs on and its effort, as the engine resolved them
17 model?: string
18 effort?: string
19}
20export type Plan = {
21 id: string
22 title: string
23 kind: 'plan' | 'todo'
24 stages: PlanStage[]
25 state: PlanState
26 note: string | null
27 startedAt: number
28 // when the plan was finished; the pill then shows the time it took
29 endedAt?: number | null
30 agents?: AgentRun[]
31 // when the current batch of agents all finished; their strips fold a few seconds later
32 agentsDoneAt?: number | null
33}
34
35declare module 'claude-code' {
36 interface PluginState {
37 'plan-progress': {
38 plans: Plan[]
39 isOpen: boolean
40 // bumped every second while agents run, so elapsed times and folding redraw
41 tick: number
42 // ids of the bars whose long title the person opened in full
43 expanded: string[]
44 // the finished bars are shown (not folded into one line)
45 doneOpen: boolean
46 }
47 }
48}
49