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

panebandspinnerguardcommandtoast
★ 62v1.0.0MITupdated 2026-10-20zycck/claude-mods/plugins/plan-progress
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plan-progress
│ ┃ Plan progress ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ Appearance │ plan-progress │ │ ┃ Effects [ twinkle ] ● plan-progress: plan-│ plan-progress: the │ │ ┃ Twinkling dots in the bar and the agent rows ⏺ Read(src/auth.ts) │ mcp__plan-progress__plan_progress tool did │ │ ┃ Speed [ speed ] ⎿ Read 6 lines │ not reach this session, so Claude cannot │ │ ┃ Show ⚡ – tok/s in the footer ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ Behavior ⏺ Bash(bun test) │ ┃ Auto-close [ autoclose ] ⎿ 3 pass, 1 fail │ ┃ A finished bar leaves on its own │ ┃ Stays for [ 10 s ][ 30 s ][ 60 s ] ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ How long a finished bar stays │ ┃ Sounds [ sounds ] ✻ Worked for 42s · done 4:20 PM │ ┃ A chime on an error, a question and the fin… │ ┃ › /progress │ ┃ About ⎿ plan-progress: No plan yet. A bar appears when Claude starts a t │ ┃ Check for updates [ updateCheck ] │ ┃ Look for a new release every 6 hours │ ┃ Version [ ↻ ? ] │ ┃ Press it to look for a newer release │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚡   – tok/s ⚙ ⟨Claude Code's own drawing⟩

Draws

Pane · Plan progress
Appearance Effects [ twinkle ] Twinkling dots in the bar and the agent rows Speed [ speed ] Show ⚡ – tok/s in the footer Behavior Auto-close [ autoclose ] A finished bar leaves on its own Stays for [ 10 s ][ 30 s ][ 60 s ] How long a finished bar stays Sounds [ sounds ] A chime on an error, a question and the finish About Check for updates [ updateCheck ] Look for a new release every 6 hours Version [ ↻ ? ] Press it to look for a newer release
README

Claude Code mods

English · Русский · 简体中文 · 日本語 · 한국어 · Español · Português · Deutsch · Français

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

Watch with sound (MP4, 14 s)

  • 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 a passed one to see how long it took, one ahead to see what starts there
  • A finished bar turns green, shows the total time and stays until it is closed; with /plan-progress-autoclose on, it leaves after doneBarSeconds (30 s by default, in /config)
  • The dots of the fill and of the subagent rows twinkle; turn twinkle off in /config to draw them still
  • Four states: running, needs input, error, done
  • Each subagent gets a row under its task: name, model and effort, current tool, time
  • 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
  • The footer shows how fast the main conversation writes, ⚡ N tok/s; subagents are not counted
  • The ⚙ next to it (in the desktop app and the fullscreen terminal) opens a settings window: effects, auto-close and its seconds, sounds, the figure itself, the mod's version and the update check; /plan-progress-settings opens it anywhere. The window speaks the language set in /config, else the app's, else the system's
  • Updates: the version in the settings window, pressed, looks for a newer release, and Update installs it and reloads the mod in place (if the reload does not take, it asks for a restart). Once every 6 hours the mod also checks by itself and marks the ⚙ with 🔹 (● in the terminal) when a new version is out. A check is one request to the GitHub API (api.github.com/repos/zycck/claude-mods/releases), with no account or session data in it; turn it off with Check for updates in the window or with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC. A copy installed from a folder is not checked
  • Works in the desktop app and in the terminal
  • In the terminal the bar follows a light or dark GNOME desktop with the auto theme, and takes the colors of the active Omarchy theme

Install

Requires Claude Code 2.1.295 or newer (claude --version; claude update to upgrade). On older versions parts of the mod do not work: the settings window stays empty, and before 2.1.286 the hooks module does not load at all, no bars appear and the startup banner says plan-progress: hooks module did not load.

/plugin marketplace add zycck/claude-mods
/plugin install plan-progress@zycck-mods

Update:

claude plugin marketplace update zycck-mods
claude plugin update plan-progress@zycck-mods

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 button next to a bar's ✕ does it for that bar)
  • /plan-progress-autoclose turns on finished bars leaving on their own (off by default), or turns it off again; the choice is kept across sessions
  • /plan-progress-settings opens the settings window, as the ⚙ in the footer does (in the terminal the ⚙ is shown only in fullscreen)

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

plugins/plan-progress/tests runs the real module against a stub engine: node compile.cjs ../hooks/register.tsx register.mjs, then node regress.mjs and node scenarios.mjs.

License

MIT

Source 2 files
hooks/register.tsx 3875 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentStatus, EngineInterface, Register, TurnStepChunk } from 'claude-code'
3
4import type { AgentRun, Plan, PlanStage, PlanState, PlanStep, Prefs, Speed, StepStatus, VersionState } 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 speed = atom({ plugin: 'plan-progress', key: 'speed' } as const, { rate: null, isLive: false } as Speed)
14// the settings window's choices as the session holds them (null until the session starts)
15const prefs = atom({ plugin: 'plan-progress', key: 'prefs' } as const, null as Prefs | null)
16const STRIP_H = 16
17const STRIP_GAP = 2
18// rows of strips per bar, the "+N more" row included: the band above the prompt has room for about 300 px
19const stripBudget = (bars: number) => (bars >= 3 ? 3 : bars === 2 ? 4 : 5)
20const FOLD_MS = 5000 // finished strips stay this long, failed ones stay until the bar closes
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 and title; 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). Control characters go first: an
76// ESC or a C1 code would reach the terminal as a command (colour, cursor), and U+FFFE/U+FFFF are no text at all
77const str = (v: unknown, max = 120) =>
78  typeof v === 'string'
79    ? v
80        .replace(/\s+/g, ' ')
81        .replace(/[\u0000-\u001F\u007F-\u009F\uFFFE\uFFFF]/g, '')
82        .trim()
83        .slice(0, max)
84        .replace(/[\uD800-\uDBFF]$/, '')
85        .trimEnd()
86    : ''
87const status = (v: unknown): StepStatus => (STATUSES.includes(v as StepStatus) ? (v as StepStatus) : 'pending')
88const list = (v: unknown): Raw[] => (Array.isArray(v) ? v.filter(x => x && typeof x === 'object') : []) as Raw[]
89const isFinished = (s: StepStatus) => s === 'done' || s === 'skipped'
90
91const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()
92
93// short updates: {next:true}, {done:[titles]}, {active:title}, {failed:title} against the stored plan;
94// titles it cannot find come back in missing, so the call is refused instead of passing as a success
95function applyOps(stages: PlanStage[], input: Raw, now: number): { stages: PlanStage[]; missing: string[] } {
96  const next = stages.map(s => ({ ...s, steps: s.steps.map(st => ({ ...st })) }))
97  const steps = next.flatMap(s => s.steps)
98  const missing: string[] = []
99  // a step finishing now remembers when, for the time its checkpoint shows
100  const finish = (st: PlanStep) => {
101    if (!isFinished(st.status)) Object.assign(st, { status: 'done', doneAt: now })
102  }
103  // a step opened again forgets when it was finished, so its checkpoint shows no stale time
104  const reopen = (st: PlanStep, to: StepStatus) => {
105    st.status = to
106    delete st.doneAt
107  }
108  // a title used twice means the one still open
109  const find = (title: string) => {
110    const found = steps.find(st => same(st.title, title) && !isFinished(st.status)) ?? steps.find(st => same(st.title, title))
111    if (!found) missing.push(title)
112    return found
113  }
114  if (input.next === true) {
115    const at = steps.findIndex(st => st.status === 'active') >= 0 ? steps.findIndex(st => st.status === 'active') : steps.findIndex(st => !isFinished(st.status))
116    const cur = steps[at]
117    if (cur) finish(cur)
118    // past the last step, work goes back to one left open earlier; a call that names the new step itself picks it,
119    // so a step jumped over is not finished on the way
120    const following = steps.slice(at + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
121    if (following && typeof input.active !== 'string') following.status = 'active'
122  }
123  let lastDone = -1
124  for (const t of Array.isArray(input.done) ? input.done : []) {
125    const st = typeof t === 'string' ? find(t) : undefined
126    if (st?.status === 'active') lastDone = steps.indexOf(st)
127    if (st) finish(st)
128  }
129  // finishing the step in progress moves on, as next does, unless the call names the new one itself
130  if (lastDone >= 0 && typeof input.active !== 'string' && !steps.some(st => st.status === 'active')) {
131    const following = steps.slice(lastDone + 1).find(st => st.status === 'pending') ?? steps.find(st => st.status === 'pending')
132    if (following) following.status = 'active'
133  }
134  const active = typeof input.active === 'string' ? find(input.active) : undefined
135  if (active) {
136    const at = steps.indexOf(active)
137    steps.forEach((st, i) => {
138      if (st.status === 'active' && i !== at) {
139        if (i < at) finish(st)
140        else st.status = 'pending'
141      }
142    })
143    reopen(active, 'active')
144  }
145  const failed = typeof input.failed === 'string' ? find(input.failed) : undefined
146  if (failed) reopen(failed, 'error')
147
148  return { stages: next, missing }
149}
150
151// the new bar, or the refusal for a call that names steps the bar does not have
152function normalize(input: Raw, prev: Plan | null, now: number, id: string): Plan | string {
153  const sent = list(input.stages)
154    .map(s => ({
155      name: str(s.name, 80) || 'Stage',
156      steps: list(s.steps).map(st => ({
157        title: str(st.title) || 'Step',
158        status: status(st.status),
159        substeps: list(st.substeps).map(sub => ({ title: str(sub.title) || '…', status: status(sub.status) })),
160      })),
161    }))
162    .filter(s => s.steps.length > 0) as PlanStage[]
163  const isPartial = sent.length === 0 && prev !== null
164  // the next task under a finished bar's id carries nothing of the last one over; the same plan grown by a step does
165  const was = prev && !isPartial && isNextTask(prev, str(input.title, 400), sent) ? null : prev
166  // a resent plan keeps what was finished; short ops sent along with it apply on top
167  const base = isPartial ? prev.stages : pointAt(was ? carryDone(sent, was.stages) : sent)
168  const { stages, missing } = applyOps(base, input, now)
169  if (missing.length > 0 && base.length > 0) {
170    const titles = stages.flatMap(s => s.steps.map(st => st.title)).join(', ')
171    return `plan_progress: "${id}" has no step ${missing.map(t => `"${str(t, 60)}"`).join(', ')}. Its steps: ${str(titles, 400)}`
172  }
173  const title = str(input.title, 80) || prev?.title || 'Plan'
174  const steps = stages.flatMap(s => s.steps)
175  const isAllDone = steps.length > 0 && steps.every(s => isFinished(s.status))
176  const asked = input.state as PlanState
177  const failedNow = typeof input.failed === 'string'
178  const state: PlanState = ['running', 'needs_input', 'error', 'done'].includes(asked) ? asked : isAllDone ? 'done' : failedNow ? 'error' : 'running'
179
180  return {
181    id,
182    title,
183    kind: input.kind === 'todo' || (isPartial && prev?.kind === 'todo') ? 'todo' : 'plan',
184    stages,
185    state,
186    note: str(input.note, 160) || null,
187    startedAt: was ? was.startedAt : now,
188    endedAt: state === 'done' ? (was?.endedAt ?? now) : null,
189    ...(prev && !was ? afresh(prev) : {}),
190  }
191}
192
193// a whole plan sent to a finished bar: another task when it has another title or leaves out a step the last one
194// finished. One that keeps the title and every finished step is the plan grown after it finished ("also commit it"),
195// which the rules tell Claude to resend under the same id. The same plan sent again with no statuses (at most its
196// first step active), bringing no step the bar did not have, is a new run of it ("deploy again", the plan approved a
197// second time): carried over, it would be finished from the start, its time counting the first run and the gap. A
198// later step sent active, or any sent done, is a redo of that step and carries over
199function isNextTask(prev: Plan, title: string, stages: PlanStage[]): boolean {
200  if (prev.state !== 'done') return false
201  // a title is stored cut at 80, and a plan-mode one without its markdown, links and list marker, cut after that: the
202  // same title resent either way, with them or without, is still the same plan
203  const sentAs = [str(title, 80), str(clean(title), 80)]
204  const keptAs = [prev.title, clean(prev.title)]
205  if (title && !sentAs.some(a => keptAs.some(b => same(a, b)))) return true
206  const key = (st: PlanStep) => st.title.trim().toLowerCase()
207  const steps = stages.flatMap(s => s.steps)
208  const sent = new Set(steps.map(key))
209  const finished = prev.stages.flatMap(s => s.steps).filter(st => isFinished(st.status))
210  if (finished.length === 0 || finished.some(st => !sent.has(key(st)))) return true
211  const left = new Map<string, number>()
212  for (const st of prev.stages.flatMap(s => s.steps)) left.set(key(st), (left.get(key(st)) ?? 0) + 1)
213  const isGrown = steps.some(st => {
214    const n = left.get(key(st)) ?? 0
215    left.set(key(st), n - 1)
216    return n <= 0
217  })
218  return !isGrown && steps.length > 0 && steps.every((st, i) => st.status === 'pending' || (st.status === 'active' && i === 0))
219}
220// what the next task under a finished bar's id keeps of the last one's strips: only agents still at work (a failed
221// strip of the last task would otherwise stay under the new one for good); the fold starts over. A teammate resting
222// between its turns stays too, and with nothing at work beside it, it folds away when its batch did
223function afresh(prev: Plan): Pick<Plan, 'agents' | 'agentsDoneAt' | 'isFolded'> {
224  const agents = keepStrips(prev.agents ?? [], a => a.state === 'running' || a.state === 'waiting' || resting.has(a.id))
225  const isOver = agents.length > 0 && agents.every(a => a.state === 'done' || a.state === 'error')
226  return { agents, agentsDoneAt: isOver ? (prev.agentsDoneAt ?? null) : null, isFolded: false }
227}
228// the strips that stay, in order: one whose parent strip goes moves up under its nearest ancestor that stays, or to
229// the top, never drawn under a row that is no longer there
230function keepStrips(agents: readonly AgentRun[], isKept: (a: AgentRun) => boolean): AgentRun[] {
231  // the depth a child of the latest strip at each depth goes to: under it, or where it stood when it goes itself
232  const childAt: number[] = []
233  return agents.flatMap(a => {
234    const depth = a.depth > 0 ? (childAt[a.depth - 1] ?? 0) : 0
235    const keep = isKept(a)
236    childAt.length = a.depth
237    childAt[a.depth] = keep ? depth + 1 : depth
238    return keep ? [depth === a.depth ? a : { ...a, depth }] : []
239  })
240}
241
242// a resent plan keeps what is finished: a step sent as pending under a title that was done stays done
243// a title used twice: each finished step carries over to one resent step of that title, in order
244function carryDone(stages: PlanStage[], before: PlanStage[]): PlanStage[] {
245  const finished = new Map<string, PlanStep[]>()
246  for (const st of before.flatMap(s => s.steps).filter(st => isFinished(st.status))) {
247    const key = st.title.trim().toLowerCase()
248    finished.set(key, [...(finished.get(key) ?? []), st])
249  }
250  return stages.map(s => ({
251    ...s,
252    steps: s.steps.map(st => {
253      const queue = finished.get(st.title.trim().toLowerCase())
254      const was = queue?.[0]
255      if (!queue || !was || !(st.status === 'pending' || st.status === was.status)) return st
256      queue.shift()
257      return { ...st, status: was.status, doneAt: was.doneAt }
258    }),
259  }))
260}
261
262// with nothing in progress, the first open step is the current one
263function pointAt(stages: PlanStage[]): PlanStage[] {
264  const steps = stages.flatMap(s => s.steps)
265  if (steps.some(st => st.status === 'active' || st.status === 'error')) return stages
266  const first = steps.find(st => st.status === 'pending')
267  return stages.map(s => ({ ...s, steps: s.steps.map(st => (st === first ? { ...st, status: 'active' as const } : st)) }))
268}
269
270// the bar an approved plan-mode plan lands on; a revised plan updates it instead of opening a second one
271const PLAN_ID = 'plan'
272
273const clean = (s: string) =>
274  s
275    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
276    .replace(/[*_`]/g, '')
277    .replace(/^\s*(\d+[.)]|[-*+]|\[[ xX]\])\s+/, '')
278    .replace(/^(\d+[.)]|\[[ xX]\])\s+/, '')
279    .trim()
280
281function parsePlan(markdown: string, now: number): Plan | null {
282  let title = ''
283  const headed: PlanStage[] = []
284  const heads: { level: number; isNumbered: boolean }[] = []
285  const items: { depth: number; text: string; status: StepStatus }[] = []
286  let fence = ''
287  for (const line of markdown.split(/\r?\n/)) {
288    // a code block's shell comments and diff lines only look like headings and list items
289    // a backtick run closed on its own line is inline code, not a fence (a backtick fence's info string has no backtick)
290    const f = line.match(/^\s*(`{3,})([^`]*)$/) ?? line.match(/^\s*(~{3,})(.*)$/)
291    const mark = f?.[1] ?? ''
292    if (fence) {
293      if (mark[0] === fence[0] && mark.length >= fence.length && !f?.[2]?.trim()) fence = ''
294      continue
295    }
296    if (mark) {
297      fence = mark
298      continue
299    }
300    const h = line.match(/^(#{1,4})\s+(.*)$/)
301    if (h) {
302      // capped as the tool caps them: a heading may become a step (120), the title 80, which isNextTask compares
303      const text = str(clean(h[2] ?? ''))
304      if (h[1] === '#' && !title) title = str(text, 80)
305      else {
306        headed.push({ name: text, steps: [] })
307        heads.push({ level: (h[1] ?? '').length, isNumbered: /^(\d+[.):]|step\s+\d+[.):]?)\s/i.test(h[2] ?? '') })
308      }
309      continue
310    }
311    const li = line.match(/^(\s*)(\d+[.)]|[-*+])\s+(.*)$/)
312    if (!li) continue
313    const depth = Math.floor((li[1] ?? '').replace(/\t/g, '  ').length / 2)
314    const text = str(clean(li[3] ?? ''))
315    if (!text) continue
316    // a ticked box is a step the plan already counts as done
317    const status: StepStatus = /^\[[xX]\]\s/.test(li[3] ?? '') ? 'done' : 'pending'
318    items.push({ depth, text, status })
319    const stage = headed[headed.length - 1]
320    if (!stage) continue
321    const step = stage.steps[stage.steps.length - 1]
322    if (depth === 0 || !step) stage.steps.push({ title: text, status, substeps: [] })
323    else step.substeps.push({ title: text, status })
324  }
325  // steps written as numbered headings with prose under them ("### 1. Add X" under "## Implementation") have no list
326  // and would be dropped as empty stages: when most of a section's numbered headings are such ones, they all become
327  // that section's steps, their list items its substeps; deepest first, and a top level with no section gets "Steps".
328  // Numbered sections that mostly carry lists ("1. Context" in prose, then "2. Changes" with a list) stay stages
329  const folded = new Set<number>()
330  const root: PlanStage = { name: 'Steps', steps: [] }
331  let rootAt = -1
332  for (let level = 4; level >= 1; level--) {
333    for (let p = -1; p < headed.length; p++) {
334      if (p >= 0 && (heads[p]?.level ?? 0) >= level) continue
335      const kids: number[] = []
336      for (let i = p + 1; i < headed.length && (heads[i]?.level ?? 0) >= level; i++) if (heads[i]?.level === level && heads[i]?.isNumbered && !folded.has(i)) kids.push(i)
337      if (kids.filter(i => headed[i]?.steps.length === 0).length * 2 <= kids.length) continue
338      if (p < 0 && rootAt < 0) rootAt = kids[0] ?? -1
339      const into = headed[p] ?? root
340      for (const i of kids) {
341        const kid = headed[i]
342        if (!kid) continue
343        into.steps.push({ title: kid.name, status: 'pending', substeps: kid.steps.map(s => ({ title: s.title, status: s.status })) })
344        folded.add(i)
345      }
346    }
347  }
348  let stages = headed.flatMap((s, i) => (i === rootAt ? [root] : folded.has(i) ? [] : [s])).filter(s => s.steps.length > 0)
349  if (stages.length === 0) {
350    if (items.some(i => i.depth > 0)) {
351      for (const item of items) {
352        const stage = stages[stages.length - 1]
353        if (item.depth === 0 || !stage) stages.push({ name: item.text, steps: [] })
354        else stage.steps.push({ title: item.text, status: item.status, substeps: [] })
355      }
356      stages = stages.map(s => (s.steps.length ? s : { ...s, steps: [{ title: s.name, status: 'pending', substeps: [] }] }))
357    } else if (items.length > 0) {
358      stages = [{ name: 'Tasks', steps: items.map(i => ({ title: i.text, status: i.status, substeps: [] })) }]
359    }
360  }
361  if (stages.length === 0) return null
362
363  return { id: PLAN_ID, title: title || 'Plan', kind: stages.length === 1 ? 'todo' : 'plan', stages, state: 'running', note: null, startedAt: now }
364}
365
366function st(title: string, s: StepStatus): PlanStep {
367  return { title, status: s, substeps: [] }
368}
369
370// ---------- drawing ----------
371
372type Where = { pos: number; total: number; stage: number; step: number; stageSize: number }
373
374// pos counts the finished steps wherever they are; the current step is the active one, else the first still open
375function where(p: Plan): Where {
376  const steps = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
377  const pos = p.state === 'done' ? steps.length : steps.filter(x => isFinished(x.step.status)).length
378  const cur = p.state === 'done' ? undefined : (steps.find(x => x.step.status === 'active') ?? steps.find(x => !isFinished(x.step.status)))
379  const stage = (cur ?? steps[steps.length - 1])?.i ?? 0
380
381  return { pos, total: steps.length, stage, step: cur ? cur.j + 1 : (p.stages[stage]?.steps.length ?? 0), stageSize: p.stages[stage]?.steps.length ?? 0 }
382}
383
384// what the pill shows: the stage its place on the track falls in (the finished share), so its name never runs ahead
385// of the pill or lags behind it when Claude finishes steps out of order; the step counts within that stage. The
386// model's own lines keep where(), which names the step actually in progress
387function atHead(p: Plan): Where {
388  const w = where(p)
389  if (p.state === 'done') return w
390  let start = 0
391  for (let i = 0; i < p.stages.length; i++) {
392    const size = p.stages[i]?.steps.length ?? 0
393    if (w.pos < start + size || i === p.stages.length - 1) return { ...w, stage: i, step: Math.max(1, Math.min(size, w.pos - start + 1)), stageSize: size }
394    start += size
395  }
396  return w
397}
398
399// the step the pill stands at, named after its stage behind a small separator; none on a finished bar
400const pillStep = (p: Plan, w: Where) => (p.state === 'done' ? '' : (p.stages[w.stage]?.steps[w.step - 1]?.title ?? ''))
401
402const hex = (h: string) => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16))
403const mix = (a: number[], b: number[], m: number) => a.map((v, i) => Math.round(v + ((b[i] ?? 0) - v) * m))
404const rgb = (c: number[]) => `rgb(${c.join(',')})`
405// XML has no place for C0 controls (an ANSI colour code's ESC, a bell) or U+FFFE/U+FFFF, escaped or not: one in a
406// title would leave the whole picture unparsable, drawn as a broken image
407const esc = (s: string) =>
408  s.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
409const hash = (a: number, b: number, k: number) => {
410  const x = Math.sin(a * 127.1 + b * 311.7 + k * 74.7) * 43758.5453
411  return x - Math.floor(x)
412}
413const 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)
414
415// a closer guess at a label's width in the system UI face the desktop draws a picture's text in (Segoe UI, SF Pro):
416// spaces, the middle dot and narrow letters count narrow, wide capitals wide. Measured against Segoe UI it lands
417// within a few percent; the margin on top keeps a wider face (SF Pro) inside the pill. Drawn text is centred on its
418// box, so what is left of the error splits evenly between the two sides. Korean and full-width letters are an em wide
419// like Chinese, an emoji (past the basic plane, or a dingbat like ✅) wider still, and the joiners and accents that
420// ride on a letter take no room; lowercase Cyrillic ш щ ж ю ы м ф count wide, near their capitals
421const glyphW = (ch: string) =>
422  /[\u0300-\u036F\u200B-\u200D\uFE00-\uFE0F]/.test(ch) ? 0
423  : ch.length > 1 || /[\u2600-\u27BF]/.test(ch) ? 16.5
424  : /[ -鿿가-힣\uFF01-\uFF60\uFFE0-\uFFE6]/.test(ch) ? 12
425  : /[\s·.,:;'|!iljI]/.test(ch) ? 3.3
426  : /[frt]/.test(ch) ? 4.4
427  : /[MWШЩЖЮФ…]/.test(ch) ? 10.8
428  : /[шщжю]/.test(ch) ? 10.4
429  : /[mwМЫымф]/.test(ch) ? 9.6
430  : /[0-9]/.test(ch) ? 6.6
431  : /[A-ZА-ЯЁ]/.test(ch) ? 7.6
432  : 6.3
433const labelWidth = (s: string, size = 12, isBold = true) => (([...s].reduce((w, ch) => w + glyphW(ch), 0) * size) / 12) * (isBold ? 1 : 0.96) * 1.06
434// a label cut to width, as labelWidth measures it, then given an ellipsis; at least three characters stay. It drops
435// whole grapheme clusters, so an emoji is never split into a lone half (which shows as "�" and breaks the picture's
436// encoding), and takes each one's width off as it goes, so a long label costs one pass and not one measure a letter
437const fitLabel = (s: string, width: number, size = 12, isBold = true) => {
438  if (labelWidth(s, size, isBold) <= width) return s
439  const scale = (size / 12) * (isBold ? 1 : 0.96) * 1.06
440  const parts = clusters(s).map(c => ({ c, w: [...c].reduce((sum, ch) => sum + glyphW(ch), 0) * scale }))
441  let w = parts.reduce((sum, x) => sum + x.w, 0)
442  let n = parts.length
443  // the ellipsis takes its own room, so the cut label with it still fits
444  const room = width - glyphW('…') * scale
445  while (n > 3 && w > room) w -= parts[--n]?.w ?? 0
446  return n === parts.length ? s : parts.slice(0, n).map(x => x.c).join('').trimEnd() + '…'
447}
448// the text without its last grapheme cluster, for the cuts measured with textWidth
449const dropLast = (s: string) => clusters(s).slice(0, -1).join('')
450// a strip's text (11.5 px, regular) cut so that it ends, ellipsis and all, within width. Measured both ways and the
451// wider taken: textWidth reads Korean and full-width letters as Latin, labelWidth knows them
452const stripW = (s: string) => Math.max(textWidth(s, 6.2), labelWidth(s, 11.5, false))
453const fitStrip = (s: string, width: number) => {
454  if (stripW(s) <= width) return s
455  let cut = s
456  while (cut.length > 4 && stripW(cut + '…') > width) cut = dropLast(cut)
457  return cut.trimEnd() + '…'
458}
459
460const ICON_PATH: Partial<Record<PlanState, string>> = {
461  needs_input: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01',
462  error: 'M18 6 6 18M6 6l12 12',
463  done: 'M20 6 9 17l-5-5',
464}
465
466// how long each finished step took (from the previous finish, or the plan's start) and each finished stage
467function stepTimes(p: Plan): { steps: Map<PlanStep, number>; stages: (number | undefined)[] } {
468  const ends = p.stages.flatMap(s => s.steps).flatMap(st => (st.doneAt === undefined ? [] : [st.doneAt])).sort((a, b) => a - b)
469  const startOf = (at: number) => Math.max(p.startedAt, ...ends.filter(t => t < at))
470  const steps = new Map<PlanStep, number>()
471  const stages = p.stages.map(s => {
472    for (const st of s.steps) if (st.doneAt !== undefined) steps.set(st, st.doneAt - startOf(st.doneAt))
473    const times = s.steps.map(st => st.doneAt)
474    if (times.some(t => t === undefined)) return undefined
475    const done = times as number[]
476    return Math.max(...done) - Math.min(...done.map(startOf))
477  })
478  return { steps, stages }
479}
480
481// 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
482function addDot(dots: Map<string, string>, cls: string, x: number, y: number) {
483  dots.set(cls, `${dots.get(cls) ?? ''}M${x} ${y}h2v2h-2z`)
484}
485
486// the fill is a still grid of 2 px dots, 3 px apart in 7 rows, and brightness streams over it from the head towards
487// the start the way it does on Claude Code's effort slider: a wave of a few brightness steps scrolls left one column
488// per step, and every dot flickers on its own, stepping up and back down to the grid. It is all patterns and masks,
489// so the picture is the same size at any width
490const STREAM_COLS = 233 // the wave's pattern in columns, prime and long, so its loop does not show
491const STREAM_SPEED = 20 // columns a second; a bar at rest (waiting, failed, done) streams at half that
492const STREAM_LEVELS = [0.3, 0.37, 0.44, 0.51] // the grid's brightness at each step of the wave
493const FLICKER_TILE = 173 // columns the flicker classes are dealt over, every dot in exactly one
494const FLICKER_CLASSES = 24
495const FLICKER_LIFTS = [0, 0.35, 0.6, 0.9]
496// [share of the fill, opacity]: the grid fades in from nothing at the start to full at two thirds; the flicker fades in
497// later and steeper, so it sparkles at the head and thins out on its way to the start
498const STREAM_FADE: [number, number][] = [[0, 0], [0.67, 1], [1, 1]]
499const FLICKER_FADE: [number, number][] = [[0, 0], [0.15, 0], [0.5, 0.45], [0.8, 0.9], [1, 1]]
500// mixed better than hash for the few hundred values the stream takes: with it the wave comes out as it was measured
501// against the slider
502const streamHash = (a: number, b: number, k: number) => {
503  let x = (Math.imul(a, 374761393) + Math.imul(b, 668265263) + Math.imul(k, 1442695041)) | 0
504  x = Math.imul(x ^ (x >>> 13), 1274126177)
505  return ((x ^ (x >>> 16)) >>> 0) / 4294967296
506}
507// the wave: noise over STREAM_COLS columns (wrapping), smoothed to blobs a few columns wide and cut into steps. Drawn
508// as one stroke per step through its runs of columns, the full height of the track
509const STREAM_WAVE = (() => {
510  const raw = Array.from({ length: STREAM_COLS }, (_, i) => streamHash(i, 0, 5))
511  const smooth = raw.map((_, i) => {
512    let sum = 0
513    let weight = 0
514    for (let d = -5; d <= 5; d++) {
515      const k = Math.exp(-(d * d) / 12.5)
516      sum += (raw[(i + d + STREAM_COLS) % STREAM_COLS] ?? 0) * k
517      weight += k
518    }
519    return sum / weight
520  })
521  const lo = Math.min(...smooth)
522  const hi = Math.max(...smooth)
523  const steps = smooth.map(v => Math.min(STREAM_LEVELS.length - 1, Math.floor(((v - lo) / (hi - lo)) * STREAM_LEVELS.length)))
524  const runs = STREAM_LEVELS.map((level, l) => {
525    let d = ''
526    let end = -1
527    for (let i = 0; i < steps.length; ) {
528      let j = i
529      while (j < steps.length && steps[j] === steps[i]) j++
530      if (steps[i] === l) {
531        d += `${end < 0 ? `M${i * 3} ${TRACK_H / 2}` : `m${(i - end) * 3} 0`}h${(j - i) * 3}`
532        end = j
533      }
534      i = j
535    }
536    return d ? `<path stroke-opacity="${level}" d="${d}"/>` : ''
537  })
538  return `<g stroke="#fff" stroke-width="${TRACK_H}">${runs.join('')}</g>`
539})()
540// the flicker: each class a pattern of its dots over the tile, and a timeline of lifts (a random walk over
541// FLICKER_LIFTS, each held 50 to 300 ms, back at the grid now and then) of its own length and start. Every time in
542// it is a whole number of the wave's 50 ms steps: a change anywhere in the picture redraws all of it, and on one beat
543// the 24 classes and the wave redraw it 20 times a second instead of at nearly every frame (half the CPU)
544const FLICKER_TICK = 0.05
545const FLICKER = (() => {
546  const of = Array.from({ length: 7 }, (_, r) => Array.from({ length: FLICKER_TILE }, (_, c) => Math.floor(streamHash(c, r, 302) * FLICKER_CLASSES)))
547  return Array.from({ length: FLICKER_CLASSES }, (_, k) => {
548    let d = ''
549    let last: [number, number] | null = null
550    for (let r = 0; r < 7; r++) {
551      for (let c = 0; c < FLICKER_TILE; c++) {
552        if (of[r]?.[c] !== k) continue
553        d += `${last ? `m${c * 3 - last[0]} ${r * 3 - last[1]}` : `M${c * 3} ${r * 3}`}h2v2h-2z`
554        last = [c * 3, r * 3]
555      }
556    }
557    // in ticks; a frame that would hold the level it already has is left out
558    const length = Math.round((2.3 + 2.4 * streamHash(k, 1, 11)) / FLICKER_TICK)
559    const frames: string[] = []
560    let level = 0
561    let shown = -1
562    for (let t = 0, i = 0; t < length - 1; i++) {
563      if (level !== shown) frames.push(`${+((t / length) * 100).toFixed(3)}%{opacity:${FLICKER_LIFTS[level]}}`)
564      shown = level
565      t += Math.max(1, Math.round((0.07 + 0.23 * streamHash(k, i, 13)) / FLICKER_TICK))
566      const u = streamHash(k, i, 15)
567      level = u < 0.4 ? Math.max(0, level - 1) : u < 0.8 ? Math.min(3, level + 1) : 0
568    }
569    const css = `.q${k}{opacity:0;animation:q${k} ${(length * FLICKER_TICK).toFixed(2)}s step-end infinite;animation-delay:calc(var(--f) - ${(Math.round(streamHash(k, 2, 16) * length) * FLICKER_TICK).toFixed(2)}s)}@keyframes q${k}{${frames.join('')}}`
570    return { d, css }
571  })
572})()
573const FLICKER_CSS = FLICKER.map(f => f.css).join('')
574// the twinkle option in /config (#23). Off, the fill stands still as reduce motion draws it, the flicker left out and
575// the wave's bands kept where they start, and the strips' dots and the terminal fill hold their middle brightness; the
576// clocks, the glides and the agents' status dots still move
577let isTwinkling = true
578
579// the engine refuses the whole band, every bar in it, when one picture's source passes 131072 characters. A plan of
580// hundreds of steps would get there through its marks and their hover tips (a few pixels apart they only cover each
581// other anyway), so past a share of that each is thinned. Stage boundaries go first, as they give the track its
582// shape and name the stages; the step marks fill what is left, kept only so far apart along the track. Picking by
583// index would line up with regular stage sizes and drop every stage at once
584const MARKS_BUDGET = 40_000
585const TIPS_BUDGET = 100_000
586type Mark<T> = { x: number; isStage: boolean; item: T }
587function thin<T>(marks: Mark<T>[], size: (item: T) => number, budget: number): T[] {
588  const sizeOf = (m: Mark<T>) => size(m.item)
589  if (marks.reduce((n, m) => n + sizeOf(m), 0) <= budget) return marks.map(m => m.item)
590  const keep = new Set<Mark<T>>()
591  let used = 0
592  // every so many, spread evenly, of the marks that fit only in part
593  const spread = (list: Mark<T>[], room: number) => {
594    const every = Math.max(1, Math.ceil(list.reduce((n, m) => n + sizeOf(m), 0) / Math.max(1, room)))
595    list.forEach((m, i) => {
596      if (i % every !== 0 || used + sizeOf(m) > budget) return
597      used += sizeOf(m)
598      keep.add(m)
599    })
600  }
601  spread(marks.filter(m => m.isStage), budget)
602  const steps = marks.filter(m => !m.isStage)
603  const room = budget - used
604  const fits = steps.length === 0 ? 0 : Math.floor(room / (steps.reduce((n, m) => n + sizeOf(m), 0) / steps.length))
605  const span = (marks.at(-1)?.x ?? 0) - (marks[0]?.x ?? 0)
606  const gap = fits > 0 ? span / fits : Infinity
607  let last = -Infinity
608  for (const m of marks) {
609    if (keep.has(m)) last = m.x
610    else if (!m.isStage && m.x - last >= gap && used + sizeOf(m) <= budget) {
611      used += sizeOf(m)
612      keep.add(m)
613      last = m.x
614    }
615  }
616  return marks.filter(m => keep.has(m)).map(m => m.item)
617}
618
619// last drawn head position per plan, so a redraw glides from where the bar was; from and at are the glide that led
620// there (from === x when it stood), so a redraw before it has run keeps it going instead of drawing it arrived
621const lastHead = new Map<string, { W: number; x: number; from: number; at: number }>()
622// where each bar's wave got to (cols, in columns) when it last changed speed (at): a bar coming to rest, or set going
623// again, streams on from there at its new speed. Timed from the start at the new speed instead, the wave would jump to
624// wherever that speed had brought it
625const waveFrom = new Map<string, { start: number; speed: number; at: number; cols: number }>()
626
627// the track draws in a sandboxed frame (for hover); its page must stay see-through in either theme
628const SEE_THROUGH = '<style>:root,html,body{background:transparent!important;color-scheme:light dark;margin:0;overflow:hidden}svg{display:block}</style>'
629
630// a clock that counts in the frame by itself, so the drawing never has to be redrawn each second (a redraw
631// reloads the frame and everything in it blinks): each digit is a reel of its figures behind a one-line window,
632// stepped by a CSS animation whose negative delay is the time already run. Plain SVG, since the host's frame
633// drops foreignObject. {{T:start}} becomes those seconds on every draw (liveSource)
634const CLOCK_W = 48 // "59m 59s"
635const LINE = 16
636const CLOCK_CSS = `.ckt{font-variant-numeric:tabular-nums}
637.rs1{animation:r10 10s steps(10) var(--d) infinite}.rs10{animation:r6 60s steps(6) var(--d) infinite}
638.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(-4.25px)}100%{transform:translateX(-.75px)}}
639.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}
640.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}
641.ph1{animation:ho 3600s steps(1,end) var(--d) both}.ph2{animation:hm 3600s steps(1,end) var(--d) both}
642@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}}`
643
644// x is the clock's left edge, top the window's top. Under an hour it reads "12m 05s", the minutes part hidden for
645// the first minute; from an hour on "1h 05m", as elapsed() writes a finished time, up to 99h
646function liveClock(x: number, top: number, start: number, cls: string, textCls: string, isCentered = false): string {
647  const base = top + 12
648  const reel = (cx: number, figures: string[], reelCls: string) =>
649    `<g class="${reelCls}"><text class="${textCls} ckt" text-anchor="middle">${figures
650      .map((f, i) => `<tspan x="${cx.toFixed(1)}" y="${base + i * LINE}">${f}</tspan>`)
651      .join('')}</text></g>`
652  const unit = (ux: number, label: string) => `<text x="${ux.toFixed(1)}" y="${base}" class="${textCls}">${label}</text>`
653  const digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
654  const tens = ['', ...digits.slice(1)]
655  const id = `ck${start}x${Math.round(x)}y${Math.round(top)}`
656  const minutes =
657    `<g class="ph1"><g class="rmm">${reel(x + 3.5, tens, 'rm10')}${reel(x + 10.5, digits, 'rm1')}${unit(x + 14, 'm')}</g>` +
658    `${reel(x + 31, digits.slice(0, 6), 'rs10')}${reel(x + 38, digits, 'rs1')}${unit(x + 41.5, 's')}</g>`
659  // "h" is narrower than "m", so the minutes sit 3 px nearer to it than the seconds sit to "m": the same space between
660  // the parts, and the face's wide "m" ends about where the other face's "s" does
661  const hours =
662    `<g class="ph2">${reel(x + 3.5, tens, 'rh10')}${reel(x + 10.5, digits, 'rh1')}${unit(x + 14, 'h')}` +
663    `${reel(x + 28, digits.slice(0, 6), 'rm6')}${reel(x + 35, digits, 'rm1')}${unit(x + 38.5, 'm')}</g>`
664  // the window only has to hide the reels' other figures above and below; sideways it leaves room past the clock's
665  // right edge for a wider face than Segoe UI (SF Pro), whose last letter would otherwise be cut
666  return (
667    `<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 + 10}" height="${LINE}"/></clipPath>` +
668    `<g clip-path="url(#${id})"${isCentered ? ' class="cc"' : ''}>${minutes}${hours}</g></g>`
669  )
670}
671
672// the desktop rebuilds a strip's picture on every redraw of the band, another plugin's invalidate included, so a
673// source reused from an earlier draw would restart its clocks at that draw's offset (issue #6): the offset is
674// taken from now on every draw. To the millisecond: a glide is steepest at its start, where a tenth of a second
675// is up to 40% of the way, so a picture rebuilt there at a rounded offset set the pill back and sent it on again
676function liveSource(template: string, now: number): string {
677  return template.replace(/\{\{T:(\d+)\}\}/g, (_, t: string) => Math.max(0, (now - Number(t)) / 1000).toFixed(3))
678}
679
680// SMIL runs whatever CSS says, so prefers-reduced-motion alone cannot stop a glide or a colour flow: an element that
681// moves is drawn twice, the moving copy (class mv) hidden under reduced motion and a still one (sv), shown only then,
682// in its place. draw gets the animation to put in the element and the class to give it
683const withStill = (draw: (anim: string, cls: string) => string, anim: string) => (anim ? draw(anim, 'mv') + draw('', 'sv') : draw('', ''))
684const classAttr = (cls: string) => (cls ? ` class="${cls}"` : '')
685const STILL_CSS = '.sv{display:none}'
686const STILL_REDUCED = '.mv{display:none}.sv{display:inline}'
687
688// a bar is drawn three times: the track itself as a plain picture, cheap for the desktop to rebuild whenever anything
689// redraws; the pill's clock, a plain picture too, that the desktop shows while the pointer is over the track; and a
690// see-through layer on top for the checkpoint times. That layer needs an interactive frame, and the desktop rebuilds
691// such frames on every redraw of the band; empty until hovered, the rebuild is invisible. The clock is no part of it:
692// a frame built anew under a still pointer is not hovered until the pointer moves, so the clock went out on every
693// redraw (the footer's figure, once a second while a response streams), where the desktop's own hover holds. All
694// three at one width are reused until what they show of the plan changes
695type Track = { base: string; overlay: string; clock: string }
696// the desktop rebuilds the picture when anything near it redraws (the footer's figure, a strip), and a rebuilt glide
697// would play again from the start, the pill jumping back to where it was. So the glide begins where its time has got
698// to ({{T:moved}} becomes the seconds since the move on every draw, liveSource), and once it has run the bar is drawn
699// standing at its place. A rebuild from the very same source starts that source's glide over, whatever its offset:
700// the engine hands back its last answer when the desktop asks again with nothing the band read changed, which it does
701// as the model starts to answer after a tool call, some .5 s after the move. So the glide is short and the standing
702// picture is asked for before it ends: from PICTURE_STAND_MS on, with the pill all but there, a draw is standing,
703// and the gliding source is current for as short a time as the desktop takes to draw the band again. The desktop
704// shows a picture some .1 s after it is drawn and the standing one as late, so it lands about where the glide
705// stands then: a step of 1-2% of the way, where at .2 s it was 5%
706const PICTURE_GLIDE_MS = 300
707const PICTURE_STAND_MS = 250
708// a bar that glided is drawn once more as the glide ends, standing: with nothing else to redraw it (a finished bar, the
709// turn over) the desktop would keep the gliding picture, and play it again from the old place whenever it rebuilds it.
710// One timer at a time, when the first glide or morph still under way is over; a draw then queues the next. One due
711// sooner than the timer waiting takes its place, else a later end queued first would hold the earlier picture on
712let settleDue = 0
713function settleBy($: EngineInterface, at: number, now: number) {
714  if (at <= now || (settleDue > now && settleDue <= at)) return
715  settleDue = at
716  $.clock.after(at - now, () => {
717    if (settleDue === at) settleDue = 0
718    void update($, tick, n => n + 1).catch(() => {})
719  })
720}
721// kept per bar id with what the track shows of the plan: $.state hands back a fresh copy on every read, so a plan
722// object is never seen twice and could not key the drawings itself
723const drawn = new Map<string, { sig: string; W: number; color: string; track: Track; glideUntil: number }>()
724const trackSig = (p: Plan) => JSON.stringify([p.state, p.startedAt, p.endedAt, p.stages])
725
726function trackSvg(p: Plan, W: number, now: number): Track {
727  const cached = drawn.get(p.id)
728  const sig = trackSig(p)
729  const color = stateColor(p.state)
730  if (cached?.sig === sig && cached.W === W && cached.color === color && (cached.glideUntil === 0 || now < cached.glideUntil)) return cached.track
731  const track = drawTrack(p, W, now)
732  const glideUntil = track.base.includes('<animateTransform') ? (lastHead.get(p.id)?.at ?? now) + PICTURE_STAND_MS : 0
733  drawn.set(p.id, { sig, W, color, track, glideUntil })
734  return track
735}
736
737function drawTrack(p: Plan, W: number, now = 0): Track {
738  const H = TRACK_H
739  const w = atHead(p)
740  const done = p.state === 'done'
741  // the fill is exactly the finished share: a fresh plan starts empty
742  const frac = done ? 1 : Math.min(1, w.pos / Math.max(1, w.total))
743  const fx = frac * W
744  const key = p.id
745  // a resize redraws at once: a head drawn at another width would glide in from the wrong place
746  const last = lastHead.get(key)
747  // drawn again on its way to the same place (an agent's event, any redraw), the glide goes on from where it began,
748  // its begin offset putting the pill where its time has got to
749  const isGliding = last?.W === W && Math.abs(last.x - fx) <= 0.5 && now < last.at + PICTURE_STAND_MS
750  const from = isGliding ? last.from : last?.W === W ? last.x : fx
751  const at = isGliding ? last.at : now
752  lastHead.set(key, { W, x: fx, from, at })
753
754  const acc = hex(stateColor(p.state))
755  const light = mix(acc, [255, 255, 255], 0.32)
756  const ease = 'calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .2 1"'
757  const glide = Math.abs(from - fx) > 0.5
758
759  // the stream (STREAM_WAVE, FLICKER) over the fill, drawn as far as the fill reaches during a glide back. Its fades run
760  // along the fill; the wave's mask is a pattern longer than that, so its slide never uncovers the end
761  const span = Math.max(fx, from)
762  const speed = p.state === 'running' ? STREAM_SPEED : STREAM_SPEED / 2
763  const was = waveFrom.get(key)
764  const wave =
765    was?.start !== p.startedAt ? { start: p.startedAt, speed, at: p.startedAt, cols: 0 }
766    : was.speed === speed ? was
767    : // a whole column: the wave's delay (cols / speed) then stays on the flicker's 50 ms beat, one redraw rate for both
768      { start: p.startedAt, speed, at: now, cols: Math.round(was.cols + (Math.max(0, now - was.at) / 1000) * was.speed) % STREAM_COLS }
769  waveFrom.set(key, wave)
770  const fadeMask = (id: string, stops: [number, number][]) =>
771    `<linearGradient id="${id}g" x1="0" x2="${fx.toFixed(1)}" gradientUnits="userSpaceOnUse">${stops.map(([at, o]) => `<stop offset="${at}" stop-color="#fff" stop-opacity="${o}"/>`).join('')}</linearGradient>` +
772    `<mask id="${id}" maskUnits="userSpaceOnUse" x="0" y="0" width="${W}" height="${H}"><rect width="${W}" height="${H}" fill="url(#${id}g)"/></mask>`
773  // without the twinkle the flicker goes as a whole: its dots get their resting opacity from its stylesheet alone, so
774  // patterns left without it would draw every one of them bright
775  const streamDefs =
776    fadeMask('fade', STREAM_FADE) +
777    (isTwinkling ? fadeMask('kfade', FLICKER_FADE) : '') +
778    `<pattern id="dg" width="3" height="3" y="1" patternUnits="userSpaceOnUse"><rect width="2" height="2" fill="${rgb(light)}"/></pattern>` +
779    `<pattern id="wp" width="${STREAM_COLS * 3}" height="${H}" patternUnits="userSpaceOnUse">${STREAM_WAVE}</pattern>` +
780    `<mask id="wave" maskUnits="userSpaceOnUse" x="0" y="0" width="${W}" height="${H}"><rect class="wm" width="${(span + STREAM_COLS * 3 + 3).toFixed(1)}" height="${H}" fill="url(#wp)"/></mask>` +
781    (isTwinkling ? FLICKER.map((f, k) => `<pattern id="fp${k}" width="${FLICKER_TILE * 3}" height="21" y="1" patternUnits="userSpaceOnUse"><path class="q${k}" fill="${rgb(light)}" d="${f.d}"/></pattern>`).join('') : '')
782  const stream =
783    `<g mask="url(#fade)"><g mask="url(#wave)"><rect width="${span.toFixed(1)}" height="21" fill="url(#dg)"/></g></g>` +
784    (isTwinkling ? `<g mask="url(#kfade)">${FLICKER.map((_, k) => `<rect width="${span.toFixed(1)}" height="${H}" fill="url(#fp${k})"/>`).join('')}</g>` : '')
785
786  const took = stepTimes(p)
787  const markList: Mark<string>[] = []
788  const zoneList: Mark<{ hit: string; tip: string; rule: string }>[] = []
789  let k = 0
790  p.stages.forEach((s, i) => {
791    s.steps.forEach((_, j) => {
792      if (k > 0) {
793        const x = (k / w.total) * W
794        const isStage = j === 0
795        // a stage boundary is a short capsule, a step a dot; bright once passed. On a light page both would fade into
796        // the track, so there the stylesheet darkens them by class
797        const passed = x < fx - 1
798        const fill = passed ? rgb(mix(light, [255, 255, 255], 0.45)) : '#A8A69E'
799        const opacity = passed ? (isStage ? 0.95 : 0.8) : isStage ? 0.9 : 0.8
800        const cls = passed ? 'mp' : 'ma'
801        markList.push({
802          x,
803          isStage,
804          item: isStage
805            ? `<rect class="${cls}" x="${(x - 1.5).toFixed(1)}" y="${(H - 10) / 2}" width="3" height="10" rx="1.5" fill="${fill}" opacity="${opacity}"/>`
806            : `<circle class="${cls}" cx="${x.toFixed(1)}" cy="${H / 2}" r="1.4" fill="${fill}" opacity="${opacity}"/>`,
807        })
808        const before = p.stages[isStage ? i - 1 : i]
809        const ended = isStage ? before?.steps[before.steps.length - 1] : s.steps[j - 1]
810        // a mark the bar has reached names what ended there (and how long it took); one still ahead names what starts
811        // there, so a name far up the track does not read as the stage the bar is in
812        const label = k <= w.pos ? (isStage ? (before?.name ?? '') : (ended?.title ?? '')) : isStage ? s.name : (s.steps[j]?.title ?? '')
813        const ms = isStage ? took.stages[i - 1] : took.steps.get(ended as PlanStep)
814        const full = ms === undefined || k > w.pos ? label : `${label} · ${elapsed(ms)}`
815        // a tip never runs past the track: a long title is shortened to fit
816        const text = fitLabel(full, W - 16, 11, false)
817        const tw = Math.min(W, labelWidth(text, 11, false) + 16)
818        const tx = Math.max(0, Math.min(W - tw, x - tw / 2))
819        zoneList.push({
820          x,
821          isStage,
822          item: {
823            hit: `<rect class="h${k}" x="${(x - 5).toFixed(1)}" width="10" height="${H}" fill="#000" fill-opacity="0"/>`,
824            tip: `<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 + tw / 2).toFixed(1)}" y="${H / 2 + 3.8}" text-anchor="middle" class="tt">${esc(text)}</text></g>`,
825            rule: `.h${k}:hover~.p${k}`,
826          },
827        })
828      }
829      k++
830    })
831    void i
832  })
833  const marks = thin(markList, m => m.length, MARKS_BUDGET).join('')
834  const zones = thin(zoneList, z => z.hit.length + z.tip.length + z.rule.length + 1, TIPS_BUDGET)
835  const hits = zones.map(z => z.hit).join('')
836  const tips = zones.map(z => z.tip).join('')
837  const tipRules = zones.map(z => z.rule)
838
839  // knob: a pill with stage and count, or a round dot with the stage number when narrow
840  const isNarrow = W < NARROW
841  const color = stateColor(p.state)
842  const icon = ICON_PATH[p.state]
843  const single = p.stages.length === 1
844  const number = single ? w.step : w.stage + 1
845  let knob = ''
846  let timePill = ''
847  let kw = H
848  if (isNarrow) {
849    const label = done ? '' : String(number)
850    knob = `<circle cx="0" cy="${H / 2}" r="${H / 2}" fill="${color}"/>${
851      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>`
852    }`
853  } else {
854    const name = done ? (p.endedAt ? elapsed(p.endedAt - p.startedAt) : 'Done') : single ? (p.stages[0]?.name ?? 'Tasks') : (p.stages[w.stage]?.name ?? '')
855    // the pill carries the stage name and, past a thin line, the step at its place (the fill and the percent
856    // already say how far along it is); folded agents stay folded, the pill does not count them
857    const iconW = icon ? 16 : 0
858    // at most about half a short track, and never so wide on a long one that it hides the marks around it
859    const maxW = Math.max(80, Math.min(W * 0.55, 320))
860    const room = maxW - (20 + iconW)
861    // the step is set a size smaller and lighter than the stage, past a thin line
862    const stageWidth = (text: string) => labelWidth(text)
863    const stepWidth = (text: string) => labelWidth(text, 11, false)
864    // the step gives way first: shortened, then dropped, before the stage name is
865    const sepW = 15
866    const stepRoom = room - stageWidth(name) - sepW
867    const step = stepRoom >= stepWidth('Abc…') ? fitLabel(pillStep(p, w), stepRoom, 11, false) : ''
868    const shown = step ? name : fitLabel(name, room)
869    const shownW = stageWidth(shown) + (step ? sepW + stepWidth(step) : 0)
870    // a running pill is wide enough for its clock too, so the hover swap does not change its size
871    const textW = done ? shownW : Math.max(shownW, CLOCK_W)
872    const contentW = iconW + textW
873    kw = Math.round(20 + contentW)
874    const left = -contentW / 2
875    const mid = left + iconW + textW / 2
876    knob = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>`
877    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"/>`
878    // the separator is the mark the pill stands on: a stage's capsule at a stage's first step, a step's dot past it
879    const sepMark = (x: number) =>
880      w.step === 1
881        ? `<rect x="${(x - 1).toFixed(1)}" y="${(H - 10) / 2}" width="2" height="10" rx="1" fill="${INK}" fill-opacity=".7"/>`
882        : `<circle cx="${x.toFixed(1)}" cy="${H / 2}" r="1.7" fill="${INK}" fill-opacity=".8"/>`
883    if (step) {
884      // the line is the anchor: the stage ends at it and the step starts after it, so whatever the font's real
885      // widths, the two never run into each other
886      const line = left + iconW + (textW - shownW) / 2 + stageWidth(shown)
887      knob +=
888        `<text x="${line.toFixed(1)}" y="${H / 2 + 4.2}" text-anchor="end" class="kt">${esc(shown)}</text>` +
889        sepMark(line + 7.5) +
890        `<text x="${(line + sepW).toFixed(1)}" y="${(H / 2 + 3.9).toFixed(1)}" class="kt kp">${esc(step)}</text>`
891    } else knob += `<text x="${mid.toFixed(1)}" y="${H / 2 + 4.2}" text-anchor="middle" class="kt">${esc(shown)}</text>`
892    // hovering the track lays a copy of the pill over it, the stage name giving way to the time the plan has run so far
893    if (!done) {
894      const face = `<rect x="${-kw / 2}" y="0" width="${kw}" height="${H}" rx="${H / 2}" fill="${color}"/>${
895        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"/>` : ''
896      }`
897      timePill = `${face}${liveClock(mid - CLOCK_W / 2, 3, p.startedAt, 'kc0', 'kt', true)}`
898    }
899  }
900  const clampX = (x: number) => Math.max(kw / 2, Math.min(W - kw / 2, x))
901  const kx = clampX(fx)
902  const kFrom = clampX(from)
903
904  // the step name is full white: at .9 it reads under AA (4.5:1) on the amber pill
905  // the desktop rebuilds the picture whenever something near it redraws, which starts its animations over: every one
906  // is set back by the time since the plan started ({{T}}, liveSource), so a rebuild picks the stream up where it was
907  // instead of jumping back. The wave moves one column at a time (steps), as the slider's does, timed from its last
908  // change of speed (waveFrom) and set on by the columns it had gone by then
909  const motion = `svg{--f:-{{T:${Math.round(p.startedAt)}}}s;--w:-{{T:${Math.round(wave.at)}}}s}
910.wm{animation:wm ${(STREAM_COLS / speed).toFixed(2)}s steps(${STREAM_COLS}) infinite;animation-delay:calc(var(--w) - ${(wave.cols / speed).toFixed(2)}s)}
911@keyframes wm{to{transform:translateX(-${STREAM_COLS * 3}px)}}
912${FLICKER_CSS}
913`
914  const style = `<style>
915${isTwinkling ? motion : ''}.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}
916.kp{font-size:11px;font-weight:400}
917@media (prefers-color-scheme:light){.mp{fill:${rgb(mix(acc, [0, 0, 0], 0.3))};opacity:1}.ma{fill:${SCHEMES.light.gutter};opacity:1}}
918${STILL_CSS}@media (prefers-reduced-motion:reduce){.wm,[class^="q"]{animation:none}${STILL_REDUCED}}
919</style>`
920  const hoverStyle = `<style>
921.tp{opacity:0;transition:opacity .12s;pointer-events:none}${tipRules.length ? `${tipRules.join(',')}{opacity:1}` : ''}
922.tt{font:400 11px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:#F0EEFC}
923.kb,rect[class^="h"]{cursor:pointer}
924</style>`
925  // a glide drawn again later starts that much into its run, or past its end, standing where it went
926  const begin = `begin="-{{T:${Math.round(at)}}}s"`
927  const dur = `dur="${PICTURE_GLIDE_MS / 1000}s"`
928  const glideFill = glide ? `<animate attributeName="width" from="${from.toFixed(1)}" to="${fx.toFixed(1)}" ${dur} ${begin} ${ease} fill="freeze"/>` : ''
929  const glideKnob = glide ? `<animateTransform attributeName="transform" type="translate" from="${kFrom.toFixed(1)} 0" to="${kx.toFixed(1)} 0" ${dur} ${begin} ${ease} fill="freeze"/>` : ''
930
931  // a gliding pill is written once and shown by reference in both copies, so its words are not in the picture twice
932  const place = `transform="translate(${kx.toFixed(1)} 0)"`
933  const pill = glideKnob
934    ? `<defs><g id="kn">${knob}</g></defs><g class="mv" ${place}>${glideKnob}<use href="#kn"/></g><use class="sv" href="#kn" ${place}/>`
935    : `<g ${place}>${knob}</g>`
936
937  const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">`
938  const base = `${open}${style}
939<defs><clipPath id="pill"><rect width="${W}" height="${H}" rx="${H / 2}"/></clipPath><clipPath id="fill">${withStill((anim, cls) => `<rect${classAttr(cls)} width="${fx.toFixed(1)}" height="${H}">${anim}</rect>`, glideFill)}</clipPath>
940<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>
941${streamDefs}</defs>
942<g clip-path="url(#pill)"><rect width="${W}" height="${H}" fill="#808080" fill-opacity=".16"/>
943<g clip-path="url(#fill)"><rect width="${fx.toFixed(1)}" height="${H}" fill="url(#base)"/>${stream}</g>${marks}</g>
944${pill}</svg>`
945  // the hover layer: checkpoint areas under a running pill's place, so the pill wins where they meet; tips on top
946  const pillArea = timePill ? `<rect class="kb" x="${(kx - kw / 2).toFixed(1)}" y="0" width="${kw}" height="${H}" fill="#000" fill-opacity="0"/>` : ''
947  const overlay = `${open}${SEE_THROUGH}${hoverStyle}${hits}${pillArea}${tips}</svg>`
948  // the pill's copy with its clock, for the desktop to show over the track while the pointer is on it. Shown at any
949  // moment, so it glides with the pill (the same glide and offset, and the same still copy for reduced motion) rather
950  // than standing at the new place while the pill slides in under it
951  const clockStyle = `<style>.kt{font:500 12px 'Anthropic Sans',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;fill:${INK}}${CLOCK_CSS}
952${STILL_CSS}@media (prefers-reduced-motion:reduce){${STILL_REDUCED}}</style>`
953  const clockPill = glideKnob ? `<g class="mv" ${place}>${glideKnob}${timePill}</g><g class="sv" ${place}>${timePill}</g>` : `<g ${place}>${timePill}</g>`
954  const clock = timePill ? `${open}${clockStyle}${clockPill}</svg>` : ''
955
956  return { base, overlay, clock }
957}
958
959const AGENT_COLOR: Record<AgentRun['state'], string> = {
960  running: STATE_COLOR.running,
961  waiting: STATE_COLOR.needs_input,
962  done: STATE_COLOR.done,
963  error: STATE_COLOR.error,
964}
965const agentColor = (s: AgentRun['state']) => (s === 'running' ? stateColor('running') : AGENT_COLOR[s])
966
967// 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
968// a strip as a picture over the app's background, which no event tells the plugin: the picture carries both sets,
969// its media query picks one, and it lays its own opaque page under the tint, so a wrong guess still pairs the text
970// with its backing. The terminal picks by isLight
971type Scheme = { page: string; ink: string; dim: string; gutter: string; more: string; word: Record<AgentRun['state'], string> }
972const SCHEMES: Record<'dark' | 'light', Scheme> = {
973  dark: { page: '#1F1E1D', ink: '#F0EEFC', dim: '#A7A5AE', gutter: '#A8A69E', more: '#9A9993', word: { running: '#9C85D8', waiting: '#C0883B', done: '#4FA569', error: '#D67278' } },
974  light: { page: '#FFFFFF', ink: '#222226', dim: '#5B5B5E', gutter: '#5F5E59', more: '#6F6D66', word: { running: '#6A4DB2', waiting: '#905300', done: '#157632', error: '#B13038' } },
975}
976
977// the desktop drops an Svg whose alt is empty, so every drawing says what it shows
978function stripAlt(p: Plan, key: string): string {
979  const a = (p.agents ?? []).find(x => x.id === key)
980  return a ? `agent ${a.title}: ${a.state}, ${toolWord(a.tool)}` : 'more agents'
981}
982
983// the hover layer's words: what its tips show, the time the latest finished steps took, for a person who hears the
984// band instead of pointing at its marks
985function timesAlt(p: Plan): string {
986  const last = [...stepTimes(p).steps].sort(([a], [b]) => (a.doneAt ?? 0) - (b.doneAt ?? 0)).slice(-3)
987  if (last.length) return `${p.title}: ${last.map(([st, ms]) => `${st.title} took ${elapsed(ms)}`).join(', ')}`
988  // steps sent finished, a bar closed by its state, the Agents bar's agents: finished, with no time to read
989  const steps = p.stages.flatMap(s => s.steps)
990  const ended = p.state === 'done' ? steps.length : steps.filter(st => isFinished(st.status)).length
991  return `${p.title}: ${ended ? `${ended} of ${plural(steps.length, 'step')} finished, no times` : 'no step finished yet'}`
992}
993
994// an unfinished bar stops at 99%: 199 of 200 steps would otherwise round up to 100%
995function percent(p: Plan, w: { pos: number; total: number }): number {
996  if (p.state === 'done') return 100
997  return Math.min(99, Math.round((Math.min(w.pos, w.total) / Math.max(1, w.total)) * 100))
998}
999
1000const elapsed = (ms: number) => {
1001  const sec = Math.max(0, Math.round(ms / 1000))
1002  if (sec < 60) return `${sec}s`
1003  return sec < 3600 ? `${Math.floor(sec / 60)}m ${sec % 60}s` : `${Math.floor(sec / 3600)}h ${Math.floor((sec % 3600) / 60)}m`
1004}
1005
1006// which strips show: all of a small batch; in a big one the unfinished first, the rest folded into one line
1007function visibleAgents(p: Plan, now: number, max: number): { shown: AgentRun[]; hidden: AgentRun[] } | null {
1008  const list = p.agents ?? []
1009  if (list.length === 0) return null
1010  const hasError = list.some(a => a.state === 'error')
1011  if (p.agentsDoneAt && now - p.agentsDoneAt > FOLD_MS && !hasError) return null
1012  if (list.length <= max) return { shown: list, hidden: [] }
1013  const keep = new Set(list.filter(a => a.state !== 'done').slice(0, max - 1).map(a => a.id))
1014  for (const a of [...list].reverse()) {
1015    if (keep.size >= max - 1) break
1016    keep.add(a.id)
1017  }
1018  return { shown: list.filter(a => keep.has(a.id)), hidden: list.filter(a => !keep.has(a.id)) }
1019}
1020
1021// the strips drawn under a bar: none while the person has folded them away (the pill does not count them either)
1022const shownAgents = (p: Plan, now: number, max: number) => (p.isFolded ? null : visibleAgents(p, now, max))
1023// a bar gets a fold button while it has strips to show or fold; folded with none left (the batch over, or after a
1024// restart) it keeps the choice for its next agents but shows no button that would do nothing
1025const canFold = (p: Plan, now: number, max: number) => visibleAgents(p, now, max) !== null
1026
1027// what each strip showed last time it was drawn, so a change morphs from the old status instead of jumping
1028const lastStrip = new Map<string, { tool: string; color: string; state: AgentRun['state'] }>()
1029const MORPH = '.2s'
1030const MORPH_MS = 200
1031
1032// a strip's markup per agent, with what it showed: drawn once per change and reused while the agent stays the same.
1033// The desktop rebuilds a strip on every redraw of the band, so a morph begins where its time has got to ({{T:at}},
1034// as the glide does), and until says when it has run: the next draw after that is the strip standing, without it.
1035// Kept by the agent's id, as $.state hands back a fresh copy of every agent on each read
1036const drawnRows = new Map<string, { key: string; html: string; until: number }>()
1037
1038
1039// whether a drawing below the bars shows anything: an empty Box or blank text would only add the gap under them. A Box
1040// that draws by itself (a border, a background, a height it keeps) shows without children, as another mod's divider
1041// does, and stays under the bars (issue #15)
1042type Drawn = { type?: string; props?: Record<string, unknown>; children?: unknown[] } | string | null | undefined
1043const hasContent = (n: unknown): boolean => {
1044  if (n === null || n === undefined || n === false) return false
1045  if (typeof n === 'string') return n.trim() !== ''
1046  if (Array.isArray(n)) return n.some(hasContent)
1047  const el = n as Exclude<Drawn, string | null | undefined>
1048  const props = el.props ?? {}
1049  if (el.type === 'Box' && (props.borderStyle || props.backgroundColor || Number(props.height) > 0 || Number(props.minHeight) > 0)) return true
1050  if (el.type === 'Box' || el.type === 'Text' || el.type === undefined) return (el.children ?? []).some(hasContent)
1051  return true
1052}
1053
1054// tokens per second, the clean figure: the speed of one stream, the main conversation's. Agents stream on models of
1055// their own at the same time, and adding them up would count parallel work as speed.
1056// The figure is an average over time, not of speeds: all the tokens of the last minute of writing over that minute,
1057// so a long response weighs as long as it took and a burst of a short one cannot swing it. Each finished response adds
1058// its exact share: the API's output_tokens, and the time from its first piece of any kind to its stop (the wait before
1059// it starts is left out; thinking arrives as empty pieces but is written, so it is in), less the time a tool the API
1060// ran itself inside it (the advisor) kept it waiting. The response being written adds
1061// what its visible text and tool arguments come to so far, in tokens at the ratio finished responses showed, over the
1062// time they took; while it thinks out of sight it adds nothing until it stops. Another model starts the average over
1063const HISTORY_MS = 60_000
1064const SHOW_EVERY_MS = 1000
1065// a second with no visible piece while the response streams is a wait, on a tool the API runs itself (the advisor) or
1066// the network, not writing: its stretch ends at the last piece, and the figure dims until the response writes again
1067const WAIT_MS = 1000
1068type Timed = { tokens: number; ms: number }
1069type Meter = {
1070  first: number | null
1071  // since when the response has written visible pieces only: null while it thinks, or before it wrote any
1072  visibleFrom: number | null
1073  // the visible time and characters of its visible stretches before the current one
1074  visibleMs: number
1075  visibleChars: number
1076  // the characters of the current stretch after its first piece, which was written before the stretch's clock started
1077  stretchChars: number
1078  lastVisible: number
1079  chars: number
1080  hasThought: boolean
1081  shownAt: number
1082  shown: string
1083  // the latest piece of any kind, and where the response's clock starts over: a retry marker (a 529 or 429 retried
1084  // inside the step) comes before the backoff and the new request's wait, which are no writing
1085  last: number
1086  restart: number | null
1087}
1088// the footer's figure as last written, whichever response wrote it: each write redraws the footer, and the desktop
1089// builds the band anew with it, so the next response does not write the same figure again, and the live figure is
1090// written at most once a second across responses. A response's final figure goes at once
1091const lastSpeed = { label: '', at: -Infinity }
1092// the latest minute of finished responses on one model
1093let history: Timed[] = []
1094let historyModel = ''
1095function remember(model: string, done: Timed) {
1096  if (model !== historyModel) {
1097    history = []
1098    historyModel = model
1099  }
1100  history.push(done)
1101  let total = history.reduce((sum, h) => sum + h.ms, 0)
1102  while (history.length > 1 && total - (history[0]?.ms ?? 0) >= HISTORY_MS) total -= history.shift()?.ms ?? 0
1103}
1104// all the tokens over all the time, the response in progress included; none before a second of it
1105function average(model: string, now: Timed = { tokens: 0, ms: 0 }): number | null {
1106  const past = model === historyModel ? history : []
1107  const ms = past.reduce((sum, h) => sum + h.ms, now.ms)
1108  const tokens = past.reduce((sum, h) => sum + h.tokens, now.tokens)
1109  return ms >= 1000 ? tokens / (ms / 1000) : null
1110}
1111// what a visible character of the session's finished responses was worth, the latest few: each one the factor that
1112// made the live estimate read that response's exact rate. Taken by time, not as tokens over characters: a response
1113// that calls a tool pays ~120 tokens no character shows, which on a short one would count every character high. The
1114// lower median, as a long response is worth less per character than the short ones around it
1115const ratios: number[] = []
1116const tokensPerChar = () => {
1117  if (ratios.length === 0) return 1 / 3.6
1118  const sorted = [...ratios].sort((a, b) => a - b)
1119  return sorted[Math.floor((sorted.length - 1) / 2)] ?? 1 / 3.6
1120}
1121// what a visible piece adds to the response's output: its text, a tool call's arguments, the tool's name
1122const pieceSize = (c: TurnStepChunk) => (c.kind === 'text' ? c.text.length : c.kind === 'input' ? c.json.length : c.kind === 'tool' ? c.name.length : 0)
1123const newMeter = (): Meter => ({
1124  first: null,
1125  visibleFrom: null,
1126  visibleMs: 0,
1127  visibleChars: 0,
1128  stretchChars: 0,
1129  lastVisible: 0,
1130  chars: 0,
1131  hasThought: false,
1132  shownAt: 0,
1133  shown: '',
1134  last: 0,
1135  restart: null,
1136})
1137// a visible stretch ends at its last piece: its time and characters join those before it
1138function endStretch(m: Meter) {
1139  if (m.visibleFrom === null) return
1140  m.visibleMs += m.lastVisible - m.visibleFrom
1141  m.visibleChars += m.stretchChars
1142  m.visibleFrom = null
1143  m.stretchChars = 0
1144}
1145const isWaiting = (m: Meter, t: number) => m.visibleFrom !== null && t - m.lastVisible >= WAIT_MS
1146// a piece arrives: the first of any kind starts the response's clock; thinking, or a wait before it, closes a visible
1147// stretch
1148function see(m: Meter, c: TurnStepChunk, t: number) {
1149  if (m.first === null) m.first = t
1150  // an engine piece a second or more after the last one, before anything was written or thought: a retried request
1151  else if (c.kind === 'engine' && m.chars === 0 && !m.hasThought && t - m.last >= WAIT_MS) m.restart = t
1152  m.last = t
1153  if (isWaiting(m, t)) endStretch(m)
1154  if (c.kind === 'thinking') {
1155    m.hasThought = true
1156    endStretch(m)
1157    return
1158  }
1159  const n = pieceSize(c)
1160  if (n === 0) return
1161  m.chars += n
1162  m.lastVisible = t
1163  if (m.visibleFrom === null) m.visibleFrom = t
1164  else m.stretchChars += n
1165}
1166// the response so far, as far as it can be measured: its visible stretches, in estimated tokens over their time
1167const sofar = (m: Meter, t: number): Timed => ({
1168  tokens: (m.visibleChars + m.stretchChars) * tokensPerChar(),
1169  ms: m.visibleMs + (m.visibleFrom === null ? 0 : t - m.visibleFrom),
1170})
1171// the response is whole: its exact share of the average, and what its visible characters were worth for the live
1172// estimate. One of under a second is too short to time cleanly and is left out. A clock started over by a retry is not
1173// taken when the API ran tools itself: their wait is taken off already, and a first one shows as such a gap too
1174function finish(m: Meter, model: string, outputTokens: number, t: number, hasServerTools = false) {
1175  if (m.first === null) return
1176  const ms = t - (m.restart !== null && !hasServerTools ? m.restart : m.first)
1177  endStretch(m)
1178  const perChar = m.visibleMs >= 1000 && m.visibleChars >= 200 && ms >= 1000 ? outputTokens / ms / (m.visibleChars / m.visibleMs) : 0
1179  if (perChar >= 0.1 && perChar <= 1) {
1180    ratios.push(perChar)
1181    if (ratios.length > 12) ratios.shift()
1182  }
1183  if (ms >= 1000 && outputTokens >= 20) remember(model, { tokens: outputTokens, ms })
1184}
1185// the footer's settings control on the desktop: ⚙ asked for in its text form (U+FE0E), one colour with the chip the
1186// desktop draws a footer Button as, where a font might pick a coloured emoji. The footer draws no pictures, only text
1187// and Buttons, so an icon there is a character
1188const GEAR_TEXT = '⚙\uFE0E'
1189// a newer release out: a blue mark in the ⚙ Button. The desktop draws a footer Button's label alone, in the chip's grey,
1190// puts the Buttons before the text and squeezes the whole to 3ch when the footer is short of room, so only the chip is
1191// sure to show: there the mark is an emoji in the label, which keeps its own colour (a small blue diamond). The
1192// terminal draws a Button's children, so there it is a ● in the accent colour
1193const GEAR_NEWS = '⚙\uFE0E \u{1F539}'
1194const speedLabel = (s: Speed) => `⚡ ${(s.rate === null ? '–' : s.rate < 10 ? s.rate.toFixed(1) : String(Math.round(s.rate))).padStart(3, FIGURE_SPACE)} tok/s`
1195
1196// one tinted strip per agent: state colour, name, what it does now and for how long; not a progress bar
1197// Lucide "bot", drawn at 12 px in the gutter before each strip
1198const BOT = '<rect width="16" height="12" x="4" y="8" rx="2"/><path d="M12 8V4H8M2 14h2M20 14h2M15 13v2M9 13v2"/>'
1199
1200// the desktop's fold control: Lucide "chevron-up" (fold) or "chevron-down" (show); a Button's label is text only, so
types/index.d.ts 69 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  // the subagent that made the bar and moves it; the main loop's gate and reminders leave such a bar alone
36  byAgent?: string
37}
38// the footer's tokens per second: the last figure (null before the first response) and whether a response streams now
39export type Speed = { rate: number | null; isLive: boolean }
40
41// the settings window's choices kept in the store: auto-close, the sounds, the footer's figure; rev counts the changes
42export type Prefs = { autoclose: boolean; sounds: boolean; speedShown: boolean; updateCheck?: boolean; lang?: string; rev: number }
43// where the settings window's version check or update stands; kept across the reload an update ends with
44export type VersionState =
45  | { phase: 'idle' }
46  | { phase: 'checking' }
47  | { phase: 'latest' }
48  | { phase: 'available'; version: string; url: string }
49  | { phase: 'updating'; version: string }
50  | { phase: 'installed'; version: string }
51  | { phase: 'restart'; version: string }
52  | { phase: 'failed'; what: 'check' | 'update'; detail: string }
53  | { phase: 'folder' }
54
55declare module 'claude-code' {
56  interface PluginState {
57    'plan-progress': {
58      plans: Plan[]
59      isOpen: boolean
60      // bumped for a timed redraw: finished strips folding away, a glide drawn once more standing
61      tick: number
62      speed: Speed
63      // the settings window's choices as this session holds them, counted so each change redraws the footer and the window
64      prefs: Prefs | null
65      version: VersionState
66    }
67  }
68}
69