SLOPSHOPPER

plan-progress

Live plan progress bars above the Claude Code prompt: stages, steps, a pixel fill and soft sounds for decision, error and done

bandspinnerguardcommandtoastprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plan-progress
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /progress ⎿ plan-progress: No plan yet. A bar appears when Claude starts a task with several steps. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

plan-progress

Live progress bars above the Claude Code prompt. Claude splits a task into stages and steps, and the bar fills as it works. The subagents for each task are listed under its bar.

plan-progress: two tasks with their agents, a question, an error, a plan rewritten mid-run, both tasks done

Adapted from zycck/claude-mods (commit 3539d02) by Kirill Serditov, MIT licensed. See LICENSE.

  • One row per task: state, title, bar, percent, close button
  • The pill on the bar shows the current stage and step; hover it for the time spent so far
  • Stages are capsules, steps are dots; hover one to see when it was reached
  • A finished bar turns green and shows the total time, then leaves after 30 s (doneBarSeconds in /config)
  • Four states: running, needs input, error, done
  • Each subagent gets a row under its task: name, model and effort, current tool, time; fold them with the chevron
  • The plan can change mid-run; finished steps are kept by title
  • Bars are saved per session and come back when the session is resumed
  • Short sounds for a question, an error and completion
  • Works in the desktop app and in the terminal

Install

Requires Claude Code 2.1.286 or newer.

/plugin install plan-progress@arhun-plugins

If you installed the upstream copy (plan-progress@zycck-mods), uninstall it first so the two don't both draw bars.

Commands

  • /progress shows or hides the bars
  • /progress-clear removes all bars
  • /progress-agents folds the agent strips under the bars, or shows them again (the chevron next to a bar's ✕ does it for that bar)
  • /plan-progress-autoclose turns off finished bars leaving on their own, or turns it back on; the choice is kept across sessions

The footer's Progress button, which did the same as /progress, is hidden for now (a decision; SHOW_FOOTER_BUTTON in hooks/register.tsx brings it back).

How it works

The mod registers a plan_progress tool. Claude sends the plan once, then short updates such as {id, next: true} or {id, done: ["Routes"]}. An unknown step name is refused with the list of the bar's steps. A plan approved in plan mode becomes the bar plan. Agent rows come from engine events and cost no tokens.

On the desktop the bar is an SVG image with a hover layer on top. In the terminal it is a character grid that animates only while Claude is working.

Tests

See tests/README.md: the real module driven against a stub engine.

Source 2 files
hooks/register.tsx 2128 lines
1import { 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 = 3
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)
13const STRIP_H = 16
14const STRIP_GAP = 2
15// rows of strips per bar, the "+N more" row included: the band above the prompt has room for about 300 px
16const stripBudget = (bars: number) => (bars >= 3 ? 3 : bars === 2 ? 4 : 5)
17const FOLD_MS = 5000 // finished strips stay this long, failed ones stay until the bar closes
18// Decision (2026-10-15): the footer buttons (Progress here, Cache in cache-warm) are hidden; /progress shows and
19// hides the bars. The code stays so the button can come back by setting this to true.
20const SHOW_FOOTER_BUTTON = false
21
22// one lightness for every state (OKLCH L .55, hues of the desktop's violet, amber, red and green), so no state
23// shouts louder than another, and white on each reads at 4.5:1 or better
24const STATE_COLOR: Record<PlanState, string> = { running: '#7858CA', needs_input: '#AD6400', error: '#C5353E', done: '#18883A' }
25const INK = '#FFFFFF'
26
27// the Omarchy theme in use, read from its colors.toml: a running bar takes its accent, the terminal track its
28// background and foreground, and its mode says light or dark. Null anywhere else, where the defaults above stay
29type Omarchy = { accent: string; background: number[]; foreground: number[]; isLight: boolean }
30let omarchy: Omarchy | null = null
31const stateColor = (s: PlanState) => (s === 'running' && omarchy ? omarchy.accent : STATE_COLOR[s])
32
33function parseOmarchy(toml: string): Omarchy | null {
34  const color = (key: string) => new RegExp(`^\\s*${key}\\s*=\\s*["'](#[0-9a-fA-F]{6})["']`, 'm').exec(toml)?.[1]?.toLowerCase()
35  const accent = color('accent')
36  if (!accent) return null
37  const background = hex(color('background') ?? '#1b1b1b')
38  const foreground = hex(color('foreground') ?? '#e0e0e0')
39  const mode = /^\s*mode\s*=\s*["'](light|dark)["']/m.exec(toml)?.[1]
40  return { accent, background, foreground, isLight: mode ? mode === 'light' : luminance(background) > 0.5 }
41}
42
43const luminance = (c: number[]) => (0.2126 * (c[0] ?? 0) + 0.7152 * (c[1] ?? 0) + 0.0722 * (c[2] ?? 0)) / 255
44
45// WCAG 2.x contrast, measured on the 4-bit colour the engine paints a Raster cell in
46const q17 = (c: number[]) => c.map(v => Math.round(v / 17) * 17)
47const relLum = (c: number[]) => {
48  const l = q17(c).map(v => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4))
49  return 0.2126 * (l[0] ?? 0) + 0.7152 * (l[1] ?? 0) + 0.0722 * (l[2] ?? 0)
50}
51const contrast = (a: number[], b: number[]) => (Math.max(relLum(a), relLum(b)) + 0.05) / (Math.min(relLum(a), relLum(b)) + 0.05)
52// text over a theme's colours: the first candidate that reads at AA (4.5:1) on bg, else the one that reads best. The
53// theme's own colours are never changed; the text only picks among them
54function readable(bg: number[], ...candidates: number[][]): number[] {
55  const ok = candidates.find(c => contrast(c, bg) >= 4.5)
56  return ok ?? candidates.reduce((a, b) => (contrast(b, bg) > contrast(a, bg) ? b : a))
57}
58// text on a pill: white, else the theme's background, else its foreground (a yellow or a pastel accent)
59const inkOn = (c: number[]) => (omarchy ? readable(c, [255, 255, 255], omarchy.background, omarchy.foreground) : [255, 255, 255])
60// a word in a colour of its own on a strip: that colour, else it mixed toward the theme's text, else the text
61const wordOn = (bg: number[], c: number[]) =>
62  omarchy ? readable(bg, c, mix(c, omarchy.foreground, 0.3), mix(c, omarchy.foreground, 0.6), omarchy.foreground) : c
63// the model and the time: the theme's text dimmed toward the strip as far as AA allows
64const dimOn = (bg: number[], c: number[]) =>
65  omarchy ? readable(bg, mix(omarchy.foreground, bg, 0.4), mix(omarchy.foreground, bg, 0.25), omarchy.foreground) : c
66const STATE_GLYPH: Record<PlanState, string> = { running: '●', needs_input: '?', error: '!', done: '✓' }
67const STATUSES: StepStatus[] = ['pending', 'active', 'done', 'error', 'skipped']
68const TRACK_H = 22
69const NARROW = 360
70
71const RULES = `# Progress bars
72Tasks 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}, 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}. 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.`
73
74type Raw = Record<string, unknown>
75// the cut drops half a character left at the edge (an emoji is two UTF-16 units)
76const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max).replace(/[\uD800-\uDBFF]$/, '').trimEnd() : '')
77const status = (v: unknown): StepStatus => (STATUSES.includes(v as StepStatus) ? (v as StepStatus) : 'pending')
78const list = (v: unknown): Raw[] => (Array.isArray(v) ? v.filter(x => x && typeof x === 'object') : []) as Raw[]
79const isFinished = (s: StepStatus) => s === 'done' || s === 'skipped'
80
81const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()
82// the title as drawn at the left of a bar: first letter upper case, the stored title (ids, alt texts) left as sent
83const shownTitle = (t: string) => t.charAt(0).toLocaleUpperCase() + t.slice(1)
84
85// short updates: {next:true}, {done:[titles]}, {active:title}, {failed:title} against the stored plan;
86// titles it cannot find come back in missing, so the call is refused instead of passing as a success
87function applyOps(stages: PlanStage[], input: Raw, now: number): { stages: PlanStage[]; missing: string[] } {
88  const next = stages.map(s => ({ ...s, steps: s.steps.map(st => ({ ...st })) }))
89  const steps = next.flatMap(s => s.steps)
90  const missing: string[] = []
91  // a step finishing now remembers when, for the time its checkpoint shows
92  const finish = (st: PlanStep) => {
93    if (!isFinished(st.status)) Object.assign(st, { status: 'done', doneAt: now })
94  }
95  // a step opened again forgets when it was finished, so its checkpoint shows no stale time
96  const reopen = (st: PlanStep, to: StepStatus) => {
97    st.status = to
98    delete st.doneAt
99  }
100  // a title used twice means the one still open
101  const find = (title: string) => {
102    const found = steps.find(st => same(st.title, title) && !isFinished(st.status)) ?? steps.find(st => same(st.title, title))
103    if (!found) missing.push(title)
104    return found
105  }
106  if (input.next === true) {
107    const at = steps.findIndex(st => st.status === 'active') >= 0 ? steps.findIndex(st => st.status === 'active') : steps.findIndex(st => !isFinished(st.status))
108    const cur = steps[at]
109    if (cur) finish(cur)
110    // past the last step, work goes back to one left open earlier
111    const following = steps.slice(at + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
112    if (following) following.status = 'active'
113  }
114  let lastDone = -1
115  for (const t of Array.isArray(input.done) ? input.done : []) {
116    const st = typeof t === 'string' ? find(t) : undefined
117    if (st?.status === 'active') lastDone = steps.indexOf(st)
118    if (st) finish(st)
119  }
120  // finishing the step in progress moves on, as next does, unless the call names the new one itself
121  if (lastDone >= 0 && typeof input.active !== 'string' && !steps.some(st => st.status === 'active')) {
122    const following = steps.slice(lastDone + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
123    if (following) following.status = 'active'
124  }
125  const active = typeof input.active === 'string' ? find(input.active) : undefined
126  if (active) {
127    const at = steps.indexOf(active)
128    steps.forEach((st, i) => {
129      if (st.status === 'active' && i !== at) {
130        if (i < at) finish(st)
131        else st.status = 'pending'
132      }
133    })
134    reopen(active, 'active')
135  }
136  const failed = typeof input.failed === 'string' ? find(input.failed) : undefined
137  if (failed) reopen(failed, 'error')
138
139  return { stages: next, missing }
140}
141
142// the new bar, or the refusal for a call that names steps the bar does not have
143function normalize(input: Raw, prev: Plan | null, now: number, id: string): Plan | string {
144  const sent = list(input.stages)
145    .map(s => ({
146      name: str(s.name, 80) || 'Stage',
147      steps: list(s.steps).map(st => ({
148        title: str(st.title) || 'Step',
149        status: status(st.status),
150        substeps: list(st.substeps).map(sub => ({ title: str(sub.title) || '…', status: status(sub.status) })),
151      })),
152    }))
153    .filter(s => s.steps.length > 0) as PlanStage[]
154  const isPartial = sent.length === 0 && prev !== null
155  // a resent plan keeps what was finished; short ops sent along with it apply on top
156  const base = isPartial ? prev.stages : pointAt(prev ? carryDone(sent, prev.stages) : sent)
157  const { stages, missing } = applyOps(base, input, now)
158  if (missing.length > 0 && base.length > 0) {
159    const titles = stages.flatMap(s => s.steps.map(st => st.title)).join(', ')
160    return `plan_progress: "${id}" has no step ${missing.map(t => `"${str(t, 60)}"`).join(', ')}. Its steps: ${titles.slice(0, 400)}`
161  }
162  const title = str(input.title, 80) || prev?.title || 'Plan'
163  const steps = stages.flatMap(s => s.steps)
164  const isAllDone = steps.length > 0 && steps.every(s => isFinished(s.status))
165  const asked = input.state as PlanState
166  const failedNow = typeof input.failed === 'string'
167  const state: PlanState = ['running', 'needs_input', 'error', 'done'].includes(asked) ? asked : isAllDone ? 'done' : failedNow ? 'error' : 'running'
168
169  return {
170    id,
171    title,
172    kind: input.kind === 'todo' || (isPartial && prev?.kind === 'todo') ? 'todo' : 'plan',
173    stages,
174    state,
175    note: str(input.note, 160) || null,
176    startedAt: prev ? prev.startedAt : now,
177    endedAt: state === 'done' ? (prev?.endedAt ?? now) : null,
178  }
179}
180
181// a resent plan keeps what is finished: a step sent as pending under a title that was done stays done
182// a title used twice: each finished step carries over to one resent step of that title, in order
183function carryDone(stages: PlanStage[], before: PlanStage[]): PlanStage[] {
184  const finished = new Map<string, PlanStep[]>()
185  for (const st of before.flatMap(s => s.steps).filter(st => isFinished(st.status))) {
186    const key = st.title.trim().toLowerCase()
187    finished.set(key, [...(finished.get(key) ?? []), st])
188  }
189  return stages.map(s => ({
190    ...s,
191    steps: s.steps.map(st => {
192      const queue = finished.get(st.title.trim().toLowerCase())
193      const was = queue?.[0]
194      if (!queue || !was || !(st.status === 'pending' || st.status === was.status)) return st
195      queue.shift()
196      return { ...st, status: was.status, doneAt: was.doneAt }
197    }),
198  }))
199}
200
201// with nothing in progress, the first open step is the current one
202function pointAt(stages: PlanStage[]): PlanStage[] {
203  const steps = stages.flatMap(s => s.steps)
204  if (steps.some(st => st.status === 'active' || st.status === 'error')) return stages
205  const first = steps.find(st => st.status === 'pending')
206  return stages.map(s => ({ ...s, steps: s.steps.map(st => (st === first ? { ...st, status: 'active' as const } : st)) }))
207}
208
209// the bar an approved plan-mode plan lands on; a revised plan updates it instead of opening a second one
210const PLAN_ID = 'plan'
211
212const clean = (s: string) =>
213  s
214    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
215    .replace(/[*_`]/g, '')
216    .replace(/^\s*(\d+[.)]|[-*+]|\[[ xX]\])\s+/, '')
217    .replace(/^(\d+[.)]|\[[ xX]\])\s+/, '')
218    .trim()
219
220function parsePlan(markdown: string, now: number): Plan | null {
221  let title = ''
222  const headed: PlanStage[] = []
223  const items: { depth: number; text: string; status: StepStatus }[] = []
224  for (const line of markdown.split(/\r?\n/)) {
225    const h = line.match(/^(#{1,4})\s+(.*)$/)
226    if (h) {
227      const text = clean(h[2] ?? '')
228      if (h[1] === '#' && !title) title = text
229      else headed.push({ name: text, steps: [] })
230      continue
231    }
232    const li = line.match(/^(\s*)(\d+[.)]|[-*+])\s+(.*)$/)
233    if (!li) continue
234    const depth = Math.floor((li[1] ?? '').replace(/\t/g, '  ').length / 2)
235    const text = clean(li[3] ?? '').slice(0, 120)
236    if (!text) continue
237    // a ticked box is a step the plan already counts as done
238    const status: StepStatus = /^\[[xX]\]\s/.test(li[3] ?? '') ? 'done' : 'pending'
239    items.push({ depth, text, status })
240    const stage = headed[headed.length - 1]
241    if (!stage) continue
242    const step = stage.steps[stage.steps.length - 1]
243    if (depth === 0 || !step) stage.steps.push({ title: text, status, substeps: [] })
244    else step.substeps.push({ title: text, status })
245  }
246  let stages = headed.filter(s => s.steps.length > 0)
247  if (stages.length === 0) {
248    if (items.some(i => i.depth > 0)) {
249      for (const item of items) {
250        const stage = stages[stages.length - 1]
251        if (item.depth === 0 || !stage) stages.push({ name: item.text, steps: [] })
252        else stage.steps.push({ title: item.text, status: item.status, substeps: [] })
253      }
254      stages = stages.map(s => (s.steps.length ? s : { ...s, steps: [{ title: s.name, status: 'pending', substeps: [] }] }))
255    } else if (items.length > 0) {
256      stages = [{ name: 'Tasks', steps: items.map(i => ({ title: i.text, status: i.status, substeps: [] })) }]
257    }
258  }
259  if (stages.length === 0) return null
260
261  return { id: PLAN_ID, title: title || 'Plan', kind: stages.length === 1 ? 'todo' : 'plan', stages, state: 'running', note: null, startedAt: now }
262}
263
264function st(title: string, s: StepStatus): PlanStep {
265  return { title, status: s, substeps: [] }
266}
267
268// ---------- drawing ----------
269
270type Where = { pos: number; total: number; stage: number; step: number; stageSize: number }
271
272// pos counts the finished steps wherever they are; the current step is the active one, else the first still open
273function where(p: Plan): Where {
274  const steps = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
275  const pos = p.state === 'done' ? steps.length : steps.filter(x => isFinished(x.step.status)).length
276  const cur = p.state === 'done' ? undefined : (steps.find(x => x.step.status === 'active') ?? steps.find(x => !isFinished(x.step.status)))
277  const stage = (cur ?? steps[steps.length - 1])?.i ?? 0
278
279  return { pos, total: steps.length, stage, step: cur ? cur.j + 1 : (p.stages[stage]?.steps.length ?? 0), stageSize: p.stages[stage]?.steps.length ?? 0 }
280}
281
282const hex = (h: string) => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16))
283const mix = (a: number[], b: number[], m: number) => a.map((v, i) => Math.round(v + ((b[i] ?? 0) - v) * m))
284const rgb = (c: number[]) => `rgb(${c.join(',')})`
285const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
286const hash = (a: number, b: number, k: number) => {
287  const x = Math.sin(a * 127.1 + b * 311.7 + k * 74.7) * 43758.5453
288  return x - Math.floor(x)
289}
290const textWidth = (s: string, px = 6.7) => [...s].reduce((w, ch) => w + (/[ -鿿]/.test(ch) ? 12 : /[ilI.,:;'|!]/.test(ch) ? 3.4 : /[mwMWШЩЖМ]/.test(ch) ? 9.5 : px), 0)
291
292const ICON_PATH: Partial<Record<PlanState, string>> = {
293  needs_input: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01',
294  error: 'M18 6 6 18M6 6l12 12',
295  done: 'M20 6 9 17l-5-5',
296}
297
298// how long each finished step took (from the previous finish, or the plan's start) and each finished stage
299function stepTimes(p: Plan): { steps: Map<PlanStep, number>; stages: (number | undefined)[] } {
300  const ends = p.stages.flatMap(s => s.steps).flatMap(st => (st.doneAt === undefined ? [] : [st.doneAt])).sort((a, b) => a - b)
301  const startOf = (at: number) => Math.max(p.startedAt, ...ends.filter(t => t < at))
302  const steps = new Map<PlanStep, number>()
303  const stages = p.stages.map(s => {
304    for (const st of s.steps) if (st.doneAt !== undefined) steps.set(st, st.doneAt - startOf(st.doneAt))
305    const times = s.steps.map(st => st.doneAt)
306    if (times.some(t => t === undefined)) return undefined
307    const done = times as number[]
308    return Math.max(...done) - Math.min(...done.map(startOf))
309  })
310  return { steps, stages }
311}
312
313// 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
314function addDot(dots: Map<string, string>, cls: string, x: number, y: number) {
315  dots.set(cls, `${dots.get(cls) ?? ''}M${x} ${y}h2v2h-2z`)
316}
317
318// last drawn head position per plan, so a redraw glides from where the bar was
319const lastHead = new Map<string, { W: number; x: number }>()
320
321// the track draws in a sandboxed frame (for hover); its page must stay see-through in either theme
322const SEE_THROUGH = '<style>:root,html,body{background:transparent!important;color-scheme:light dark;margin:0;overflow:hidden}svg{display:block}</style>'
323
324// a clock that counts in the frame by itself, so the drawing never has to be redrawn each second (a redraw
325// reloads the frame and everything in it blinks): each digit is a reel of its figures behind a one-line window,
326// stepped by a CSS animation whose negative delay is the time already run. Plain SVG, since the host's frame
327// drops foreignObject. {{T:start}} becomes those seconds on every draw (liveSource)
328const CLOCK_W = 48 // "59m 59s"
329const LINE = 16
330const CLOCK_CSS = `.ckt{font-variant-numeric:tabular-nums}
331.rs1{animation:r10 10s steps(10) var(--d) infinite}.rs10{animation:r6 60s steps(6) var(--d) infinite}
332.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}}
333.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}
334.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}
335.ph1{animation:ho 3600s steps(1,end) var(--d) both}.ph2{animation:hm 3600s steps(1,end) var(--d) both}
336@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}}`
337
338// x is the clock's left edge, top the window's top. Under an hour it reads "12m 05s", the minutes part hidden for
339// the first minute; from an hour on "1h 05m", as elapsed() writes a finished time, up to 99h
340function liveClock(x: number, top: number, start: number, cls: string, textCls: string, isCentered = false): string {
341  const base = top + 12
342  const reel = (cx: number, figures: string[], reelCls: string) =>
343    `<g class="${reelCls}"><text class="${textCls} ckt" text-anchor="middle">${figures
344      .map((f, i) => `<tspan x="${cx.toFixed(1)}" y="${base + i * LINE}">${f}</tspan>`)
345      .join('')}</text></g>`
346  const unit = (ux: number, label: string) => `<text x="${ux.toFixed(1)}" y="${base}" class="${textCls}">${label}</text>`
347  const digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
348  const tens = ['', ...digits.slice(1)]
349  const id = `ck${start}x${Math.round(x)}y${Math.round(top)}`
350  const minutes =
351    `<g class="ph1"><g class="rmm">${reel(x + 3.5, tens, 'rm10')}${reel(x + 10.5, digits, 'rm1')}${unit(x + 14, 'm')}</g>` +
352    `${reel(x + 31, digits.slice(0, 6), 'rs10')}${reel(x + 38, digits, 'rs1')}${unit(x + 41.5, 's')}</g>`
353  const hours =
354    `<g class="ph2">${reel(x + 3.5, tens, 'rh10')}${reel(x + 10.5, digits, 'rh1')}${unit(x + 14, 'h')}` +
355    `${reel(x + 31, digits.slice(0, 6), 'rm6')}${reel(x + 38, digits, 'rm1')}${unit(x + 41.5, 'm')}</g>`
356  return (
357    `<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>` +
358    `<g clip-path="url(#${id})"${isCentered ? ' class="cc"' : ''}>${minutes}${hours}</g></g>`
359  )
360}
361
362// the desktop rebuilds a strip's picture on every redraw of the band, another plugin's invalidate included, so a
363// source reused from an earlier draw would restart its clocks at that draw's offset (issue #6): the offset is
364// taken from now on every draw
365function liveSource(template: string, now: number): string {
366  return template.replace(/\{\{T:(\d+)\}\}/g, (_, t: string) => Math.max(0, (now - Number(t)) / 1000).toFixed(1))
367}
368
369// a bar is drawn twice: the track itself as a plain picture, which the desktop keeps steady whatever else redraws,
370// and a see-through layer on top for the hover parts (checkpoint times, the pill's clock). That layer needs an
371// interactive frame, and the desktop rebuilds such frames on every redraw of the band; empty until hovered, the
372// rebuild is invisible. A plan is immutable, so both drawings at one width are reused until the plan changes
373type Track = { base: string; overlay: string }
374const drawn = new WeakMap<Plan, { W: number; color: string; track: Track }>()
375
376function trackSvg(p: Plan, W: number): Track {
377  const cached = drawn.get(p)
378  const color = stateColor(p.state)
379  if (cached?.W === W && cached.color === color) return cached.track
380  const track = drawTrack(p, W)
381  drawn.set(p, { W, color, track })
382  return track
383}
384
385function drawTrack(p: Plan, W: number): Track {
386  const H = TRACK_H
387  const w = where(p)
388  const done = p.state === 'done'
389  // the fill is exactly the finished share: a fresh plan starts empty
390  const frac = done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))
391  const fx = frac * W
392  const key = p.id
393  // a resize redraws at once: a head drawn at another width would glide in from the wrong place
394  const last = lastHead.get(key)
395  const from = last?.W === W ? last.x : fx
396  lastHead.set(key, { W, x: fx })
397
398  const acc = hex(stateColor(p.state))
399  const light = mix(acc, [255, 255, 255], 0.32)
400  const grey = [132, 130, 138]
401  const ease = 'calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .2 1"'
402  const glide = Math.abs(from - fx) > 0.5
403
404  const bounds: number[] = []
405  let acc2 = 0
406  p.stages.forEach((s, i) => {
407    acc2 += s.steps.length
408    if (i < p.stages.length - 1) bounds.push((acc2 / w.total) * W)
409  })
410
411  // pixels: 3px grid, 7 rows, denser towards the head, twinkling and warming from grey to the state colour
412  const buckets = [0, 1, 2, 3, 4].map(b => {
413    const m = b / 4
414    const dense = 0.22 + 0.78 * Math.pow(m, 1.5)
415    return { color: rgb(mix(grey, light, m)), opacity: (0.35 + 0.65 * dense).toFixed(2) }
416  })
417  const dots = new Map<string, string>()
418  for (let col = 0; col * 3 < fx; col++) {
419    const x = col * 3
420    const u = Math.min(1, (x + 1.5) / fx)
421    const dense = 0.22 + 0.78 * Math.pow(u, 1.5)
422    const bucket = Math.min(4, Math.floor(Math.min(1, Math.pow(u, 0.9) * 1.1) * 4.99))
423    for (let r = 0; r < 7; r++) {
424      if (hash(col, r, 1) > dense + 0.1) continue
425      addDot(dots, `b${bucket} t${Math.floor(hash(col, r, 2) * 4)}`, x, 1 + r * 3)
426    }
427  }
428  const px = [...dots].map(([cls, d]) => `<path class="${cls}" d="${d}"/>`).join('')
429
430  const took = stepTimes(p)
431  const tipRules: string[] = []
432  let marks = ''
433  let hits = ''
434  let tips = ''
435  let k = 0
436  p.stages.forEach((s, i) => {
437    s.steps.forEach((_, j) => {
438      if (k > 0) {
439        const x = (k / w.total) * W
440        const isStage = j === 0
441        // a stage boundary is a short capsule, a step a dot; bright once passed
442        const passed = x < fx - 1
443        const fill = passed ? rgb(mix(light, [255, 255, 255], 0.45)) : '#A8A69E'
444        const opacity = passed ? (isStage ? 0.95 : 0.8) : isStage ? 0.75 : 0.6
445        marks += isStage
446          ? `<rect x="${(x - 1.5).toFixed(1)}" y="${(H - 10) / 2}" width="3" height="10" rx="1.5" fill="${fill}" opacity="${opacity}"/>`
447          : `<circle cx="${x.toFixed(1)}" cy="${H / 2}" r="1.4" fill="${fill}" opacity="${opacity}"/>`
448        const before = p.stages[isStage ? i - 1 : i]
449        const ended = isStage ? before?.steps[before.steps.length - 1] : s.steps[j - 1]
450        const label = isStage ? (before?.name ?? '') : (ended?.title ?? '')
451        const ms = isStage ? took.stages[i - 1] : took.steps.get(ended as PlanStep)
452        const text = ms === undefined ? label : `${label} · ${elapsed(ms)}`
453        const tw = textWidth(text, 6.2) + 16
454        const tx = Math.max(0, Math.min(W - tw, x - tw / 2))
455        hits += `<rect class="h${k}" x="${(x - 5).toFixed(1)}" width="10" height="${H}" fill="#000" fill-opacity="0"/>`
456        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>`
457        tipRules.push(`.h${k}:hover~.p${k}`)
458      }
459      k++
460    })
461    void i
462  })
463
464  // knob: a pill with stage and count, or a round dot with the stage number when narrow
465  const isNarrow = W < NARROW
466  const color = stateColor(p.state)
467  const icon = ICON_PATH[p.state]
468  const single = p.stages.length === 1
469  const number = single ? w.step : w.stage + 1
470  let knob = ''
471  let timePill = ''
472  let kw = H
473  if (isNarrow) {
474    const label = done ? '' : String(number)
475    knob = `<circle cx="0" cy="${H / 2}" r="${H / 2}" fill="${color}"/>${
476      done ? `<path d="${ICON_PATH.done}" 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>`
477    }`
478  } else {
479    const name = done ? (p.endedAt ? elapsed(p.endedAt - p.startedAt) : 'Done') : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
480    // the pill carries the stage name alone (the fill and the percent already say how far along it is), and, while
481    // the person has folded the bar's agent strips away, how many of its agents are still at work
482    const agents = p.isFolded && p.id !== AGENTS ? (p.agents ?? []) : []
483    const running = agents.filter(a => a.state === 'running' || a.state === 'waiting').length
484    const count = agents.length === 0 ? '' : running > 0 ? `${running} running` : `${agents.length} done`
485    const iconW = icon ? 16 : 0
486    const countW = count ? textWidth(count, 6.5) : -6
487    const maxW = Math.max(80, W * 0.55)
488    let shown = name
489    while (shown.length > 3 && 20 + iconW + textWidth(shown) + 6 + countW > maxW) shown = shown.slice(0, -1)
490    if (shown !== name) shown = shown.trimEnd() + '…'
491    // a running pill is wide enough for its clock too, so the hover swap does not change its size
492    const textW = done ? textWidth(shown) : Math.max(textWidth(shown), CLOCK_W)
493    kw = Math.round(20 + iconW + textW + 6 + countW)
494    const left = -(iconW + textW) / 2
495    const mid = left + iconW + textW / 2
496    knob = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>`
497    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"/>`
498    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>`
499    // hovering the pill lays a copy of it over the stage name, carrying the time the plan has run so far
500    if (!done) {
501      const face = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>${
502        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"/>` : ''
503      }`
504      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>`
505    }
506  }
507  const clampX = (x: number) => Math.max(kw / 2, Math.min(W - kw / 2, x))
508  const kx = clampX(fx)
509  const kFrom = clampX(from)
510
511  const style = `<style>
512.b0{fill:${buckets[0]?.color};fill-opacity:${buckets[0]?.opacity}}.b1{fill:${buckets[1]?.color};fill-opacity:${buckets[1]?.opacity}}
513.b2{fill:${buckets[2]?.color};fill-opacity:${buckets[2]?.opacity}}.b3{fill:${buckets[3]?.color};fill-opacity:${buckets[3]?.opacity}}
514.b4{fill:${buckets[4]?.color};fill-opacity:${buckets[4]?.opacity}}
515.t0,.t1,.t2,.t3{animation:tw 2.2s ease-in-out infinite}
516.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}
517@keyframes tw{0%,100%{opacity:1}50%{opacity:.45}}
518.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}
519.kc{font-weight:400}
520@media (prefers-reduced-motion:reduce){.t0,.t1,.t2,.t3{animation:none}}
521</style>`
522  const hoverStyle = `<style>
523.tp{opacity:0;transition:opacity .12s;pointer-events:none}${tipRules.length ? `${tipRules.join(',')}{opacity:1}` : ''}
524.tt{font:400 11px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#F0EEFC}
525.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}
526.kv{opacity:0;filter:blur(3px);transition:opacity .2s,filter .2s}.kb:hover .kv{opacity:1;filter:none}
527.kb,rect[class^="h"]{cursor:pointer}
528${CLOCK_CSS}
529</style>`
530  const glideFill = glide ? `<animate attributeName="width" from="${from.toFixed(1)}" to="${fx.toFixed(1)}" dur=".45s" ${ease} fill="freeze"/>` : ''
531  const glideKnob = glide ? `<animateTransform attributeName="transform" type="translate" from="${kFrom.toFixed(1)} 0" to="${kx.toFixed(1)} 0" dur=".45s" ${ease} fill="freeze"/>` : ''
532
533  const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">`
534  const base = `${open}${style}
535<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>
536<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>
537<g clip-path="url(#pill)"><rect width="${W}" height="${H}" fill="#808080" fill-opacity=".16"/>
538<g clip-path="url(#fill)"><rect width="${fx.toFixed(1)}" height="${H}" fill="url(#base)"/>${px}</g>${marks}</g>
539<g transform="translate(${kx.toFixed(1)} 0)">${glideKnob}${knob}</g></svg>`
540  // the hover layer: checkpoint areas under the pill's copy, so the pill wins where they meet; tips on top
541  const overlay = `${open}${SEE_THROUGH}${hoverStyle}${hits}<g transform="translate(${kx.toFixed(1)} 0)">${timePill}</g>${tips}</svg>`
542
543  return { base, overlay }
544}
545
546const AGENT_COLOR: Record<AgentRun['state'], string> = {
547  running: STATE_COLOR.running,
548  waiting: STATE_COLOR.needs_input,
549  done: STATE_COLOR.done,
550  error: STATE_COLOR.error,
551}
552const agentColor = (s: AgentRun['state']) => (s === 'running' ? stateColor('running') : AGENT_COLOR[s])
553
554// strip text that reads at WCAG AA (4.5:1) on its tint, in a dark and a light scheme (issue #13). The desktop draws
555// a strip as a picture over the app's background, which no event tells the plugin: the picture carries both sets,
556// its media query picks one, and it lays its own opaque page under the tint, so a wrong guess still pairs the text
557// with its backing. The terminal picks by isLight
558type Scheme = { page: string; ink: string; dim: string; gutter: string; more: string; word: Record<AgentRun['state'], string> }
559const SCHEMES: Record<'dark' | 'light', Scheme> = {
560  dark: { page: '#1F1E1D', ink: '#F0EEFC', dim: '#A7A5AE', gutter: '#A8A69E', more: '#9A9993', word: { running: '#9C85D8', waiting: '#C0883B', done: '#4FA569', error: '#D67278' } },
561  light: { page: '#FFFFFF', ink: '#222226', dim: '#5B5B5E', gutter: '#5F5E59', more: '#6F6D66', word: { running: '#6A4DB2', waiting: '#905300', done: '#157632', error: '#B13038' } },
562}
563
564// the desktop drops an Svg whose alt is empty, so every drawing says what it shows
565function stripAlt(p: Plan, key: string): string {
566  const a = (p.agents ?? []).find(x => x.id === key)
567  return a ? `agent ${a.title}: ${a.state}, ${a.tool}` : 'more agents'
568}
569
570// an unfinished bar stops at 99%: 199 of 200 steps would otherwise round up to 100%
571function percent(p: Plan, w: { pos: number; total: number }): number {
572  if (p.state === 'done') return 100
573  return Math.min(99, Math.round((Math.min(w.pos, w.total) / Math.max(1, w.total)) * 100))
574}
575
576const elapsed = (ms: number) => {
577  const sec = Math.max(0, Math.round(ms / 1000))
578  if (sec < 60) return `${sec}s`
579  return sec < 3600 ? `${Math.floor(sec / 60)}m ${sec % 60}s` : `${Math.floor(sec / 3600)}h ${Math.floor((sec % 3600) / 60)}m`
580}
581
582// which strips show: all of a small batch; in a big one the unfinished first, the rest folded into one line
583function visibleAgents(p: Plan, now: number, max: number): { shown: AgentRun[]; hidden: AgentRun[] } | null {
584  const list = p.agents ?? []
585  if (list.length === 0) return null
586  const hasError = list.some(a => a.state === 'error')
587  if (p.agentsDoneAt && now - p.agentsDoneAt > FOLD_MS && !hasError) return null
588  if (list.length <= max) return { shown: list, hidden: [] }
589  const keep = new Set(list.filter(a => a.state !== 'done').slice(0, max - 1).map(a => a.id))
590  for (const a of [...list].reverse()) {
591    if (keep.size >= max - 1) break
592    keep.add(a.id)
593  }
594  return { shown: list.filter(a => keep.has(a.id)), hidden: list.filter(a => !keep.has(a.id)) }
595}
596
597// the strips drawn under a bar: none while the person has folded them away (the bar's pill still counts its agents)
598const shownAgents = (p: Plan, now: number, max: number) => (p.isFolded ? null : visibleAgents(p, now, max))
599// a bar gets a fold button while it has strips to show or fold; folded with none left (the batch over, or after a
600// restart) it keeps the choice for its next agents but shows no button that would do nothing
601const canFold = (p: Plan, now: number, max: number) => visibleAgents(p, now, max) !== null
602
603// what each strip showed last time it was drawn, so a change morphs from the old status instead of jumping
604const lastStrip = new Map<string, { tool: string; color: string; state: AgentRun['state'] }>()
605const MORPH = '.2s'
606
607// a strip's markup per agent object: drawn once per change, so its morph plays once and later redraws match
608const drawnRows = new WeakMap<AgentRun, { key: string; html: string }>()
609
610
611// one tinted strip per agent: state colour, name, what it does now and for how long; not a progress bar
612// Lucide "bot", drawn at 12 px in the gutter before each strip
613const BOT = '<rect width="16" height="12" x="4" y="8" rx="2"/><path d="M12 8V4H8M2 14h2M20 14h2M15 13v2M9 13v2"/>'
614
615// the desktop's fold control: Lucide "chevron-up" (fold) or "chevron-down" (show); a Button's label is text only, so
616// the picture is centred in the cell and a blank Button over it, centred the same way, takes the presses and draws its
617// own hover and focus ring around it (a picture laid over the Button would take the pointer)
618const FOLD_W = 16
619const FOLD_H = 16
620const foldChip = (isFolded: boolean) =>
621  `<svg xmlns="http://www.w3.org/2000/svg" width="${FOLD_W}" height="${FOLD_H}" viewBox="0 0 ${FOLD_W} ${FOLD_H}"><style>.fc{stroke:#C2C0B6}` +
622  `@media (prefers-color-scheme:light){.fc{stroke:#3D3D3A}}</style>` +
623  `<g transform="translate(${(FOLD_W - 16) / 2} ${(FOLD_H - 16) / 2}) scale(${16 / 24})" fill="none" class="fc" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">` +
624  `<path d="${isFolded ? 'm6 9 6 6 6-6' : 'm18 15-6-6-6 6'}"/></g></svg>`
625const GUTTER = 36 // icon and agent number, left of the strip
626
627// claude-haiku-4-5-20251001 -> haiku 4.5; an alias stays as given
628const modelName = (m: string) => {
629  const r = /^claude-([a-z]+)-(\d+)-(\d+)/.exec(m)
630  return r ? `${r[1]} ${r[2]}.${r[3]}` : m
631}
632
633// the agent's name, its model and effort in a dimmer parenthesis
634const nameMarkup = (name: string) => {
635  const at = name.indexOf(' (')
636  return at > 0 ? `${esc(name.slice(0, at))}<tspan class="st">${esc(name.slice(at))}</tspan>` : esc(name)
637}
638
639// one tinted strip per agent behind a bot icon and its number: the colour says how it went,
640// the word says what it does now (only while it runs or waits), the time how long it took
641type StripRow = { key: string; html: string; height: number }
642
643// each strip is its own drawing, so a change to one agent redraws that strip alone, never the bar or the others
644function stripsSvg(v: { shown: AgentRun[]; hidden: AgentRun[] }, all: AgentRun[], W: number): StripRow[] {
645  const isNarrow = W < NARROW
646  const SW = W - GUTTER
647  const rows: StripRow[] = []
648  // the icon and number take their colour from the scheme's class (gu for an agent, gm for the more line)
649  const gutter = (y: number, label: string, cls: string) =>
650    `<g class="${cls}"><g transform="translate(1 ${y + 2}) scale(.5)" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">${BOT}</g>` +
651    `<text x="16" y="${y + 11.5}" class="sn sg">${label}</text></g>`
652  // the scheme's page under a tint, so the tint and the text over it look the same on any background; drawn first, so
653  // a "+N" wider than the gutter still shows whole
654  const backing = (y: number) => `<rect class="sb" x="${GUTTER}" y="${y}" width="${SW}" height="${STRIP_H}" rx="${STRIP_H / 2}"/>`
655  v.shown.forEach((a, i) => {
656    // the first strip keeps a little room from the track above it
657    const y = i === 0 ? 5 : STRIP_GAP
658    const rowKey = `${W}|${y}|${all.indexOf(a)}`
659    const cachedRow = drawnRows.get(a)
660    if (cachedRow?.key === rowKey) {
661      rows.push({ key: a.id, html: cachedRow.html, height: y + STRIP_H })
662      return
663    }
664    const c = agentColor(a.state)
665    const indent = a.depth > 0 ? 10 : 0
666    const word = a.state === 'running' || a.state === 'waiting' ? a.tool : ''
667    const dots = new Map<string, string>()
668    if (a.state === 'running') {
669      for (let col = 0; col * 3 < SW; col++) {
670        for (let r = 0; r < 4; r++) {
671          if (hash(col + i * 41, r, 5) > 0.2) continue
672          addDot(dots, `t${Math.floor(hash(col, r, 6) * 4)}`, GUTTER + col * 3, Math.round((y + 2.5 + r * 3.2) * 10) / 10)
673        }
674      }
675    }
676    const px = [...dots].map(([cls, d]) => `<path class="${cls}" fill="${c}" fill-opacity=".32" d="${d}"/>`).join('')
677    // a status change: the old word blurs out while the new one blurs in, and the tint flows to the new colour
678    const was = lastStrip.get(a.id)
679    lastStrip.set(a.id, { tool: word, color: c, state: a.state })
680    const isWordChanged = was !== undefined && was.tool !== word
681    const flow = (attr: string) => (was && was.color !== c ? `<animate attributeName="${attr}" from="${was.color}" to="${c}" dur="${MORPH}" fill="freeze"/>` : '')
682    // the tool word sits at the right, just before the clock, so the name and its model get the rest of the row
683    const toolEnd = W - 9 - CLOCK_W - 10
684    const wordW = Math.max(word ? textWidth(word, 6.2) : 0, isWordChanged && was.tool ? textWidth(was.tool, 6.2) : 0)
685    const nameX = GUTTER + 19 + indent
686    const nameRoom = isNarrow ? SW - 24 - indent : toolEnd - (wordW > 0 ? wordW + 12 : 0) - nameX
687    const spec = [a.model ? modelName(a.model) : '', a.effort ?? ''].filter(Boolean).join(' · ')
688    const full = (a.depth > 0 ? '↳ ' : '') + a.title + (spec ? ` (${spec})` : '')
689    let name = full
690    while (name.length > 4 && textWidth(name, 6.2) > nameRoom) name = name.slice(0, -1)
691    if (name !== full) name = name.trimEnd() + '…'
692    const time =
693      a.endedAt === null
694        ? liveClock(W - 9 - CLOCK_W, y, a.startedAt, 'sc', 'sn st')
695        : `<text x="${W - 9}" y="${y + 11.5}" text-anchor="end" class="sn st">${elapsed(a.endedAt - a.startedAt)}</text>`
696    const tool = isNarrow
697      ? ''
698      : (isWordChanged && was.tool ? `<text x="${toolEnd}" y="${y + 11.5}" text-anchor="end" class="sn mo w-${was.state}">${esc(was.tool)}</text>` : '') +
699        (word ? `<text x="${toolEnd}" y="${y + 11.5}" text-anchor="end" class="sn w-${a.state}${isWordChanged ? ' mi' : ''}">${esc(word)}</text>` : '') +
700        time
701    const html =
702      backing(y) +
703      gutter(y, String(all.indexOf(a) + 1), 'gu') +
704      `<rect x="${GUTTER}" y="${y}" width="${SW}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="${c}" fill-opacity=".15">${flow('fill')}</rect>${px}` +
705      `<circle cx="${GUTTER + 10 + indent}" cy="${y + STRIP_H / 2}" r="3" fill="${c}"${a.state === 'running' ? ' class="sd"' : ''}>${flow('fill')}</circle>` +
706      `<text x="${nameX}" y="${y + 11.5}" class="sn">${nameMarkup(name)}</text>` +
707      tool
708    drawnRows.set(a, { key: rowKey, html })
709    rows.push({ key: a.id, html, height: y + STRIP_H })
710  })
711  if (v.hidden.length > 0) {
712    const y = v.shown.length === 0 ? 5 : STRIP_GAP
713    const doneCount = v.hidden.filter(a => a.state === 'done').length
714    rows.push({
715      key: '+',
716      height: y + STRIP_H,
717      html:
718        backing(y) +
719        gutter(y, `+${v.hidden.length}`, 'gm') +
720        `<rect x="${GUTTER}" y="${y}" width="${SW}" height="${STRIP_H}" rx="${STRIP_H / 2}" fill="#808080" fill-opacity=".14"/>` +
721        `<text x="${GUTTER + 10}" y="${y + 11.5}" class="sn st">${plural(v.hidden.length, 'more agent')} · ${doneCount} done</text>`,
722    })
723  }
724  return rows
725}
726
727// a scheme's colours as the strip's classes; in the stylesheet the light set follows the dark one, so it wins where
728// its query holds, and the dim and tool word follow the name they colour over
729const schemeCss = (s: Scheme) =>
730  `.sb{fill:${s.page}}.sn{fill:${s.ink}}.st{fill:${s.dim}}.gu{color:${s.gutter}}.gm{color:${s.more}}` +
731  Object.entries(s.word).map(([state, c]) => `.w-${state}{fill:${c}}`).join('')
732const STRIP_STYLE = `<style>.sn{font:400 11.5px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif}.sg{font-weight:500;font-variant-numeric:tabular-nums}
733${schemeCss(SCHEMES.dark)}@media (prefers-color-scheme:light){${schemeCss(SCHEMES.light)}}.gu .sn,.gm .sn{fill:currentColor}
734.sd{animation:sp 1.1s ease-in-out infinite}@keyframes sp{50%{opacity:.3}}
735.mi{animation:mi ${MORPH} ease-out both}@keyframes mi{from{opacity:0;filter:blur(3px)}}
736.mo{animation:mo ${MORPH} ease-in both}@keyframes mo{to{opacity:0;filter:blur(3px)}}
737.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}
738@keyframes tw{0%,100%{opacity:1}50%{opacity:.45}}
739${CLOCK_CSS}
740@media (prefers-reduced-motion:reduce){.sd,.mi,.mo,.t0,.t1,.t2,.t3{animation:none}.mo{opacity:0}}</style>`
741
742function plural(n: number, word: string) {
743  return `${n} ${word}${n === 1 ? '' : 's'}`
744}
745
746const DEFAULT = 0x01000000
747let isLight = false
748const termBg = () => omarchy?.background ?? (isLight ? [255, 255, 255] : [24, 24, 27])
749const termFg = () => omarchy?.foreground ?? (isLight ? [34, 34, 38] : [240, 238, 252])
750const scheme = () => SCHEMES[isLight ? 'light' : 'dark']
751const pack = (c: number[]) => ((c[0] ?? 0) << 16) | ((c[1] ?? 0) << 8) | (c[2] ?? 0)
752// a Raster cell takes one printable BMP character exactly one column wide, as the engine measures it
753// (Bun.stringWidth, ambiguous narrow); any other character refuses the whole tree and every bar vanishes.
754// NOT_ONE lists the printable BMP characters whose width is not one, as base-36 "start-extra" ranges
755const NOT_ONE = '4t,lc-33,w3-6,13l-18,14v,14x-1,150-1,153,16o-5,174-a,17g,18r-k,19s,1cm-7,1cv-5,1d3-1,1d6-3,1e7,1e9,1f4-q,1ie-a,1kb-8,1kt,1li-3,1ln-8,1lx-2,1m1-4,1nd-2,1p3-8,1qi-1k,1tm-2,1tq-f,1u9-6,1uq-1,1vk-2,1x6-2,1xa-f,1xt-6,1ya-1,1z2,1z4-2,20q-2,20u-f,21d-6,21u-1,228-1,22d,22o-2,24a-2,24e-f,24x-6,25e-1,262-8,27u-2,27y-f,28h-6,28y-1,29s-2,2be-2,2bi-f,2c1-6,2ci-1,2dc-2,2dg,2ey-2,2f2-f,2fl-6,2g2-1,2gw-2,2ii-2,2im-f,2j5-6,2jm-1,2kg-2,2m2-2,2m6-f,2n6-1,2o1,2q2,2qa-2,2qe,2sx,2t0-6,2tj-7,2wh,2wk-8,2x4-6,2zc-1,305,307,309,31t-d,328-4,32e-1,32l-a,32x-z,346,371-3,376-5,37d-1,37h-1,388-1,38e-2,38x-3,39e,39h-1,39p,3a5,3cw-73,3tp-2,4k2-2,4ky-1,4lu-1,4mq-1,4ok-1,4on-6,4p2,4p5-a,4pp,4qz-4,4ud-1,4vd,4yo-2,4yv-1,4z6,4zd-2,55j-1,55n,57a,57c-6,57k,57m,57p-7,583-9,58f,59s-2b,5dg,5di-4,5do,5du,5ez-8,5fk-1,5gi-3,5go-1,5gr-2,5ie,5ig-1,5il,5in-2,5kc-7,5km-1,5ow-2,5p0-c,5pe-6,5pp,5pw,5q0-1,5vk-1r,6bv-4,6cq-4,6e8-f,6hc-1b,6xm-1,6y1-1,73d-3,73k,73n,7i5-1,7is-1,7jk-7,7k8-b,7lr,7m2-5,7mb,7mp,7my-1,7nh-1,7no-1,7ny,7o4,7oq,7oy-1,7p1,7p6,7p9,7ph,7pm-1,7qg,7rg,7ri,7rn-2,7rr,7th-2,7u8,7un,8ij-1,8k0,8k5,8vj-2,8zj,928-v,96o-p,97f-2g,9a8-5x,9gw-26,9j5-2d,9ll-2u,9ol-16,9pt-2l,9sg-2d,9v3-1b,9wg-13,9xs-mkc,wi8-1i,wvj-3,wvo-9,wwu-1,wz4-1,x6q,x6u,x6z,x7p-1,x7w,xc4-1,xcw-h,xdr,xeu-7,xfr-a,xgg-s,xhc-2,xir,xiu-3,xj0-1,xk5,xm1-5,xm9-1,xmd-1,xmr,xn0,xoc,xps,xpu-2,xpz-1,xq6-1,xq9,xrg-1,xrq,xyd,xyg,xyl,xz4-8mb,16ls-27,1d6o-e7,1dlq,1e68-p,1e74-1e,1e8k-i,1e94-3,1edb,1edd-2n,1ejk-6'
756const notOne = NOT_ONE.split(',').map(r => {
757  const [a = '0', n] = r.split('-')
758  const from = parseInt(a, 36)
759  return [from, from + (n ? parseInt(n, 36) : 0)] as const
760})
761function isNotOne(cp: number) {
762  let lo = 0
763  let hi = notOne.length - 1
764  while (lo <= hi) {
765    const mid = (lo + hi) >> 1
766    const [from, to] = notOne[mid] ?? [0, 0]
767    if (cp < from) hi = mid - 1
768    else if (cp > to) lo = mid + 1
769    else return true
770  }
771  return false
772}
773// marks and format characters (accents written apart, variation selectors, joiners, soft hyphens) take no cell
774// of their own and go; anything else that cannot fill exactly one cell is drawn as a middle dot
775const cellChar = (ch: string) => {
776  if (/\p{M}|\p{Cf}/u.test(ch)) return ''
777  const cp = ch.codePointAt(0) ?? 63
778  const isControl = cp < 0x20 || (cp >= 0x7f && cp <= 0x9f)
779  return isControl || cp > 0xffff || (cp >= 0xd800 && cp <= 0xdfff) || isNotOne(cp) ? '·' : ch
780}
781// an emoji sequence (a variation selector, a keycap, joined people, a skin tone, a flag) is one picture two columns
782// wide, so it is found a grapheme cluster at a time; everything else is measured a character at a time, as the
783// engine measures it, since a cluster of letters (a Hindi conjunct, Thai SARA AM) is several columns
784const segmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null
785const clusters = (s: string): string[] => (segmenter ? Array.from(segmenter.segment(s), x => x.segment) : [...s])
786const isEmojiCluster = (c: string) =>
787  /\u20E3|\p{Regional_Indicator}/u.test(c) ||
788  (/\p{Extended_Pictographic}/u.test(c) && (/[\uFE0F\u200D\u{1F3FB}-\u{1F3FF}]/u.test(c) || (c.codePointAt(0) ?? 0) > 0xffff))
789// the cells a string takes inside a Raster: a dot for an emoji sequence, each other character as cellChar draws it
790const cellText = (s: string) => clusters(s).map(c => (isEmojiCluster(c) ? '·' : [...c].map(cellChar).join(''))).join('')
791const cellsOf = (s: string) => [...cellText(s)].length
792// the columns one character takes as plain Text: none for marks, format and control characters and the vowel and
793// final jamo of a Hangul syllable written apart; two for wide ones, and for any character beyond the basic plane
794// but mathematical letters (a guess too wide only pads the title box, one too narrow cuts the title)
795function charColumns(ch: string): number {
796  const cp = ch.codePointAt(0) ?? 0
797  if (/\p{M}|\p{Cf}/u.test(ch) || cp < 0x20 || (cp >= 0x7f && cp <= 0x9f)) return 0
798  if ((cp >= 0x1160 && cp <= 0x11ff) || (cp >= 0xd7b0 && cp <= 0xd7ff)) return 0
799  if (cp > 0xffff) return cp >= 0x1d400 && cp <= 0x1d7ff ? 1 : 2
800  return isNotOne(cp) ? 2 : 1
801}
802// the columns a string takes as plain Text, where the terminal draws a wide character (CJK, emoji) over two
803const columnsOf = (s: string) => clusters(s).reduce((w, c) => w + (isEmojiCluster(c) ? 2 : [...c].reduce((n, ch) => n + charColumns(ch), 0)), 0)
804const fit = (s: string, w: number) => {
805  const chars = [...cellText(s)]
806  if (chars.length <= w) return chars.join('')
807  return w <= 1 ? '…'.slice(0, w) : chars.slice(0, w - 1).join('').trimEnd() + '…'
808}
809
810type Cell = [number, number, number]
811
812class Grid {
813  cells: Cell[]
814  constructor(
815    readonly columns: number,
816    readonly rows: number,
817  ) {
818    this.cells = Array.from({ length: columns * rows }, () => [32, DEFAULT, DEFAULT] as Cell)
819  }
820  set(x: number, y: number, ch: string | number, fg: number, bg: number) {
821    if (x < 0 || x >= this.columns || y < 0 || y >= this.rows) return
822    this.cells[y * this.columns + x] = [typeof ch === 'number' ? ch : (ch.codePointAt(0) ?? 32), fg, bg]
823  }
824  bg(x: number, y: number) {
825    return this.cells[y * this.columns + x]?.[2] ?? DEFAULT
826  }
827  text(x: number, y: number, s: string, fg: number, bg?: number) {
828    let i = 0
829    for (const ch of cellText(s)) {
830      this.set(x + i, y, ch, fg, bg ?? this.bg(x + i, y))
831      i++
832    }
833    return i
834  }
835  encode() {
836    const words = new Uint32Array(this.cells.length * 3)
837    this.cells.forEach((c, i) => words.set(c, i * 3))
838    return (new Uint8Array(words.buffer) as Uint8Array & { toBase64: () => string }).toBase64()
839  }
840}
841
842const BRAILLE_BITS = [
843  [0x01, 0x08],
844  [0x02, 0x10],
845  [0x04, 0x20],
846  [0x40, 0x80],
847]
848
849function pill(g: Grid, y: number, from: number, to: number, bgAt: (x: number) => number[]) {
850  for (let x = from; x < to; x++) g.set(x, y, ' ', DEFAULT, pack(bgAt(x)))
851}
852
853const LEVELS = 8
854const q = (m: number) => Math.round(Math.max(0, Math.min(1, m)) * LEVELS) / LEVELS
855const wave = (t: number, periodMs: number, offset = 0) => 0.5 + 0.5 * Math.sin(((t / periodMs) + offset) * Math.PI * 2)
856const easeOut = (x: number) => 1 - Math.pow(1 - Math.max(0, Math.min(1, x)), 4)
857
858const glide = new Map<string, { from: number; to: number; at: number }>()
859const GLIDE_MS = 450
860// the twinkle moment of each bar's last moving frame, kept while it stands still
861const stillPhase = new Map<string, number>()
862
863// a head glides to a new place only while frames can carry the glide; otherwise it is drawn there at once
864function headAt(id: string, target: number, t: number, canGlide: boolean): number {
865  const g = glide.get(id)
866  if (!g || (!canGlide && Math.abs(g.to - target) > 0.01)) {
867    glide.set(id, { from: target, to: target, at: t })
868    return target
869  }
870  const cur = g.from + (g.to - g.from) * easeOut((t - g.at) / GLIDE_MS)
871  if (Math.abs(g.to - target) > 0.01) {
872    glide.set(id, { from: cur, to: target, at: t })
873    return cur
874  }
875  return cur
876}
877
878
879function trackCells(p: Plan, W: number, t: number): string {
880  const g = new Grid(W, 1)
881  const w = where(p)
882  const done = p.state === 'done'
883  const target = (done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))) * W
884  // after the turn a change lands at once: a glide would keep frames going through the engine's end-of-turn redraw
885  const fx = headAt(p.id, target, t, isTurnLive || hasRunningAgents(p))
886  // only a moving bar twinkles with the clock; one that stands still keeps the twinkle of its last frame, so a
887  // redraw (the end of a turn is one) rewrites none of its cells, even right after it stopped moving
888  const phase = isAnimated(p, t) ? t : (stillPhase.get(p.id) ?? 0)
889  stillPhase.set(p.id, phase)
890  const back = termBg()
891  const acc = hex(stateColor(p.state))
892  const light = mix(acc, [255, 255, 255], 0.35)
893  const grey = [120, 118, 128]
894  const track = mix(back, [128, 128, 128], isLight ? 0.14 : 0.18)
895  const fill = mix(track, acc, done ? 0.3 : 0.17)
896  const under = (x: number) => (x + 0.5 < fx ? fill : track)
897  pill(g, 0, 0, W, under)
898
899  const TWINKLE = done ? [3200, 3800, 4400, 3500] : [2200, 2800, 1900, 3300]
900  const DELAY = [0, 700, 1300, 400]
901  const dim = done ? 0.2 : 0.55
902  for (let col = 0; col < Math.min(W, Math.ceil(fx)); col++) {
903    const u = Math.min(1, (col + 0.5) / Math.max(1, fx))
904    const dense = done ? 0.8 : 0.22 + 0.78 * Math.pow(u, 1.5)
905    let bits = 0
906    for (let r = 0; r < 4; r++) {
907      for (let c = 0; c < 2; c++) {
908        const sx = col * 2 + c
909        if (sx / 2 >= fx || hash(sx, r, 1) > dense * 0.6) continue
910        bits |= BRAILLE_BITS[r]?.[c] ?? 0
911      }
912    }
913    if (bits === 0) continue
914    const cls = Math.floor(hash(col, 0, 2) * 4)
915    const period = TWINKLE[cls] ?? 2200
916    const blink = 1 - dim * wave(phase + (DELAY[cls] ?? 0), period, 0.25)
917    const bucket = done ? 1 : q(Math.min(1, Math.pow(u, 0.9) * 1.1))
918    const tone = mix(grey, light, bucket)
919    const opacity = (0.35 + 0.65 * dense) * blink
920    g.set(col, 0, 0x2800 + bits, pack(mix(fill, tone, q(opacity))), pack(fill))
921  }
922
923  let k = 0
924  p.stages.forEach(s => {
925    if (k > 0) {
926      const x = Math.round((k / w.total) * W)
927      if (x > 0 && x < W - 1) {
928        const passed = x < fx - 0.5
929        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)))
930      }
931    }
932    k += s.steps.length
933  })
934
935  const base = hex(stateColor(p.state))
936  const color = base
937  const single = p.stages.length === 1
938  const number = single ? Math.min(w.total, w.pos + 1) : w.stage + 1
939  const icon = p.state === 'done' ? '✓' : p.state === 'error' ? '✕' : p.state === 'needs_input' ? '?' : ''
940  let name = ''
941  let count = ''
942  if (W < 28) {
943    name = icon || String(number)
944  } else {
945    const agents = p.agents ?? []
946    name = done ? 'Done' : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
947    const baseCount = p.id === AGENTS ? `${w.pos}/${w.total}` : done ? `${w.total}/${w.total}` : single ? `${number}/${w.total}` : `${w.step}/${w.stageSize}`
948    count = baseCount + (agents.length > 0 && p.id !== AGENTS ? ` · ${agents.filter(a => a.state === 'done').length}/${agents.length}` : '')
949  }
950  const lead = icon && W >= 28 ? `${icon} ` : ''
951  const maxName = Math.max(3, Math.floor(W * (W < 60 ? 0.75 : 0.55)) - cellsOf(lead) - cellsOf(count) - 5)
952  const shown = lead + fit(name, maxName)
953  const kw = cellsOf(shown) + (count ? count.length + 1 : 0) + 2
954  const kx = Math.round(Math.max(0, Math.min(W - kw, fx - kw / 2)))
955  const white = pack(inkOn(color))
956  pill(g, 0, kx, kx + kw, () => color)
957  let at = kx + 1
958  at += g.text(at, 0, shown, white, pack(color))
959  if (count) g.text(at + 1, 0, count, white, pack(color))
960  return g.encode()
961}
962
963function stripCells(v: { shown: AgentRun[]; hidden: AgentRun[] }, W: number, now: number): { cells: string; rows: number } {
964  const rows = v.shown.length + (v.hidden.length > 0 ? 1 : 0)
965  const g = new Grid(W, rows)
966  const back = termBg()
967  const text = pack(termFg())
968  v.shown.forEach((a, y) => {
969    const c = hex(agentColor(a.state))
970    const tint = mix(back, c, 0.18)
971    pill(g, y, 0, W, () => tint)
972    const running = a.state === 'running' || a.state === 'waiting'
973    if (running) {
974      for (let col = 1; col < W - 1; col++) {
975        let bits = 0
976        let glow = 0
977        for (let r = 0; r < 4; r++) {
978          for (let cc = 0; cc < 2; cc++) {
979            const sx = col * 2 + cc + y * 83
980            if (hash(sx, r, 5) >= 0.08) continue
981            const b = 1 - 0.55 * wave(now, 1900 + hash(sx, r, 6) * 1400, hash(sx, r, 7))
982            bits |= BRAILLE_BITS[r]?.[cc] ?? 0
983            glow = Math.max(glow, b)
984          }
985        }
986        if (bits) g.set(col, y, 0x2800 + bits, pack(mix(tint, c, 0.2 + 0.4 * q(glow))), pack(tint))
987      }
988    }
989    const indent = a.depth > 0 ? 2 : 0
990    const dotColor = running ? mix(tint, c, 0.3 + 0.7 * q(wave(now, 1100))) : c
991    g.text(2 + indent, y, '●', pack(dotColor), pack(tint))
992    const time = elapsed((a.endedAt ?? now) - a.startedAt)
993    const narrow = W < 30
994    const tx = W - 2 - time.length
995    // the tool word sits at the right, just before the time, so the name and its model get the rest of the row
996    const word = narrow || !running ? '' : fit(a.tool, Math.max(0, Math.floor(W * 0.25)))
997    const toolAt = tx - 1 - word.length
998    let at = 4 + indent
999    const spec = [a.model ? modelName(a.model) : '', a.effort ?? ''].filter(Boolean).join(' · ')
1000    const full = (a.depth > 0 ? '↳ ' : '') + a.title + (spec ? ` (${spec})` : '')
1001    const name = fit(full, Math.max(3, (narrow ? W - 2 : word ? toolAt - 1 : tx - 1) - at))
1002    // the model and effort are drawn dimmer than the name
1003    const cut = spec ? name.indexOf(' (') : -1
1004    const head = cut > 0 ? name.slice(0, cut) : name
1005    for (let i = -1; i < name.length + 1 && at + i < W - 1; i++) g.set(at + i, y, ' ', DEFAULT, pack(tint))
1006    at += g.text(at, y, head, text, pack(tint))
1007    const dim = pack(dimOn(tint, hex(scheme().dim)))
1008    if (head !== name) g.text(at, y, name.slice(head.length), dim, pack(tint))
1009    if (narrow) return
1010    if (word) {
1011      for (let i = -1; i <= word.length; i++) g.set(toolAt + i, y, ' ', DEFAULT, pack(tint))
1012      g.text(toolAt, y, word, pack(wordOn(tint, hex(a.state === 'running' && omarchy ? omarchy.accent : scheme().word[a.state]))), pack(tint))
1013    }
1014    for (let i = -1; i < time.length; i++) g.set(tx + i, y, ' ', DEFAULT, pack(tint))
1015    g.text(tx, y, time, dim, pack(tint))
1016  })
1017  if (v.hidden.length > 0) {
1018    const y = v.shown.length
1019    const tint = mix(back, [128, 128, 128], 0.16)
1020    pill(g, y, 0, W, () => tint)
1021    const doneCount = v.hidden.filter(a => a.state === 'done').length
1022    g.text(2, y, fit(`+${plural(v.hidden.length, 'more agent')} · ${doneCount} done`, W - 4), pack(dimOn(tint, hex(scheme().dim))), pack(tint))
1023  }
1024  return { cells: g.encode(), rows }
1025}
1026
1027type Band = { requestId: string; W: number; list: readonly Plan[] }
1028let band: Band | null = null
1029let isFrameBusy = false
1030// a bar twinkles only while Claude works on it; one waiting on the person or left open after the turn stands still
1031let isTurnLive = false
1032let frames: { cancel: () => void } | null = null
1033// when the engine last refused frames of this band for good; the frames rest a second before they try again
1034let refusedAt: number | null = null
1035// refused frames in a row: one sent between a redraw and its commit is refused once and the next goes through
1036let refusedInRow = 0
1037const REFUSED_MAX = 6
1038
1039const hasRunningAgents = (p: Plan) => (p.agents ?? []).some(a => a.state === 'running' || a.state === 'waiting')
1040const isGliding = (p: Plan, t: number) => {
1041  const g = glide.get(p.id)
1042  return g !== undefined && g.from !== g.to && t - g.at < GLIDE_MS + 100
1043}
1044const isAnimated = (p: Plan, t: number) => (isTurnLive && p.state === 'running') || hasRunningAgents(p) || isGliding(p, t)
1045
1046// the 30 fps clock runs only while a terminal band has something moving; the second timer starts and stops it
1047function syncFrames($: EngineInterface, now: number) {
1048  const isRested = refusedAt === null || now - refusedAt >= 1000
1049  const isWanted = band !== null && isRested && band.list.some(p => isAnimated(p, now))
1050  if (isWanted && !frames) frames = $.clock.every(33, () => void animate($))
1051  if (!isWanted && frames) {
1052    frames.cancel()
1053    frames = null
1054  }
1055}
1056
1057// ---------- terminal tint ----------
1058// the track's light or dark tint: a theme the person picked wins; "auto", and the default "dark" inside Terminal.app
1059// (whose stock profiles follow macOS), take the macOS appearance. Off a Mac, "auto" takes the desktop's
1060// color-scheme (GNOME and the desktops that share its setting). The appearance is read only while a terminal bar
1061// is on screen, at most every APPEARANCE_MS, and never again once neither command is there
1062const APPEARANCE_MS = 5000
1063let themeSetting = 'dark'
1064let system: 'unknown' | 'mac' | 'gnome' | 'none' = 'unknown'
1065let termProgram = ''
1066let isSystemDark: boolean | null = null
1067let appearanceAt = -Infinity
1068let isProbing = false
1069
1070const followsSystem = () =>
1071  system !== 'none' &&
1072  (themeSetting === 'auto' || (themeSetting === 'dark' && (system === 'unknown' || (system === 'mac' && termProgram === 'Apple_Terminal'))))
1073// an Omarchy theme paints the terminal itself, so its mode wins over the setting and the macOS appearance
1074const tintIsLight = () => (omarchy ? omarchy.isLight : followsSystem() && isSystemDark !== null ? !isSystemDark : /light/i.test(themeSetting))
1075
1076// the Omarchy theme is read like the appearance: while a terminal bar is on screen, at most every APPEARANCE_MS, so a
1077// theme switch follows within seconds; a machine without the file (or a file without an accent) is never read again
1078const OMARCHY_COLORS = 'cat "${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/current/theme/colors.toml"'
1079let hasOmarchy = true
1080let omarchyAt = -Infinity
1081
1082async function readOmarchy($: EngineInterface, now: number) {
1083  if (!hasOmarchy || now - omarchyAt < APPEARANCE_MS) return
1084  omarchyAt = now
1085  const r = await $.process.run(['/bin/sh', '-c', OMARCHY_COLORS], { timeoutMs: 2000 }).catch(() => null)
1086  const found = r && r.exitCode === 0 ? parseOmarchy(r.stdout) : null
1087  if (!found) {
1088    hasOmarchy = false
1089    omarchy = null
1090    return
1091  }
1092  const was = omarchy
1093  if (was && was.accent === found.accent && was.isLight === found.isLight && String(was.background) === String(found.background) && String(was.foreground) === String(found.foreground)) return
1094  omarchy = found
1095}
1096
1097// the macOS appearance: the key is missing in light mode, so anything but "Dark" reads as light; null off a Mac
1098async function readMac($: EngineInterface) {
1099  const r = await $.process.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: 2000 }).catch(() => null)
1100  return r ? /dark/i.test(r.stdout) : null
1101}
1102
1103// the desktop's color-scheme: 'prefer-dark' or 'prefer-light'; 'default' says nothing, so the theme setting decides
1104async function readGnome($: EngineInterface) {
1105  const r = await $.process.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: 2000 }).catch(() => null)
1106  if (!r || r.exitCode !== 0) return undefined
1107  return /prefer-dark/.test(r.stdout) ? true : /prefer-light/.test(r.stdout) ? false : null
1108}
1109
1110async function probeAppearance($: EngineInterface, now: number) {
1111  if (isProbing || !followsSystem() || now - appearanceAt < APPEARANCE_MS) return
1112  isProbing = true
1113  appearanceAt = now
1114  try {
1115    if (system !== 'gnome') {
1116      const dark = await readMac($)
1117      if (dark !== null) {
1118        if (system === 'unknown') {
1119          const t = await $.process.run(['/bin/sh', '-c', 'printf %s "$TERM_PROGRAM"'], { timeoutMs: 2000 }).catch(() => null)
1120          termProgram = t?.stdout.trim() ?? ''
1121          system = 'mac'
1122        }
1123        isSystemDark = dark
1124        return
1125      }
1126    }
1127    const dark = await readGnome($)
1128    if (dark === undefined) {
1129      // neither command: the theme setting alone decides from here on
1130      system = 'none'
1131      return
1132    }
1133    system = 'gnome'
1134    isSystemDark = dark
1135  } finally {
1136    isProbing = false
1137  }
1138}
1139
1140// reads the appearance when due and repaints the bars at once if the tint changed
1141async function syncTint($: EngineInterface, now: number) {
1142  const before = omarchy
1143  if (band) await readOmarchy($, now)
1144  if (band && !omarchy) await probeAppearance($, now)
1145  const next = tintIsLight()
1146  if (next === isLight && omarchy === before) return
1147  isLight = next
1148  const b = band
1149  if (b) await blitPlans($, b, b.list, now)
1150}
1151
1152// the size goes along, so a band redrawn at another width answers with a deny naming both sizes
1153function blitPlans($: EngineInterface, b: Band, list: readonly Plan[], now: number) {
1154  return Promise.all(
1155    list.flatMap(p => {
1156      const v = shownAgents(p, now, stripBudget(b.list.length))
1157      const strips = v ? stripCells(v, b.W, now) : null
1158      const calls = [$.ui.blit({ requestId: b.requestId, key: `track-${p.id}`, cells: trackCells(p, b.W, now), columns: b.W, rows: 1 })]
1159      if (strips) calls.push($.ui.blit({ requestId: b.requestId, key: `strips-${p.id}`, cells: strips.cells, columns: b.W, rows: strips.rows }))
1160      return calls.map(c => c.catch(() => undefined))
1161    }),
1162  )
1163}
1164
1165// blits the engine keeps refusing (the band hidden or unmounted, redrawn at another size, or its tree refused) stop
1166// the frames: the 1 s timer tries one frame again a second later, and a redraw lays the band out anew at once. A
1167// band shown again without a redraw (folded and unfolded) so comes back within a second instead of staying still
1168function stopFrames(b: Band, now: number) {
1169  if (band !== b) return
1170  refusedAt = now
1171  refusedInRow = 0
1172  frames?.cancel()
1173  frames = null
1174}
1175
1176async function animate($: EngineInterface) {
1177  const b = band
1178  if (!b || isFrameBusy) return
1179  isFrameBusy = true
1180  try {
1181    const now = await $.clock.now()
1182    // a redraw while the clock was read laid the band out anew: this frame belongs to the old one
1183    if (band !== b) return
1184    const live = b.list.filter(p => isAnimated(p, now))
1185    if (live.length === 0) return
1186    const answers = await blitPlans($, b, live, now)
1187    if (!answers.some(a => a?.deny)) {
1188      refusedInRow = 0
1189      refusedAt = null
1190    } else if (++refusedInRow >= REFUSED_MAX) stopFrames(b, now)
1191  } finally {
1192    isFrameBusy = false
1193  }
1194}
1195
1196
1197// ---------- engine glue ----------
1198
1199// the engine's player first (afplay on macOS); PowerShell where it cannot play
1200// set while a demo reel records: every sound with its moment, so a video can carry them
types/index.d.ts 47 lines
1export 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 }
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  // the person folded the bar's agent strips away (its ▾ button, /progress-agents); the bar keeps one line
34  isFolded?: boolean
35}
36
37declare module 'claude-code' {
38  interface PluginState {
39    'plan-progress': {
40      plans: Plan[]
41      isOpen: boolean
42      // bumped every second while agents run, so elapsed times and folding redraw
43      tick: number
44    }
45  }
46}
47