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
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

cc-mods

Claude Code mods (function-hook plugins), forked from other authors or written here, kept in one repo. Each mod lives under mods/<name>/. A forked one is a squashed git subtree of its upstream: the upstream's license stays with it, and each squash commit names the upstream commit it came from. One written here has no upstream and carries its own license.

The repo is also a plugin marketplace, so a forked mod can be installed from here once it carries local changes.

Mods

ModUpstreamLocal changesLicense
md-promptnogu66/md-prompt0.2.0: none. The dunder-path fix carried here as 0.1.1-cc.1 was taken upstream in 0.1.2 (nogu66/md-prompt#4), so the mod is upstream as isMIT
plan-progresszycck/claude-mods1.0.0-cc.7, on upstream 1.0.0 and its fix #26 (b77335e); the earlier local changes that upstream now ships (the duplicate-title carry, light-theme strips, the strip clock taken from now, the demo reel gone, a folding chevron) are upstream's code again, and the usage rules are back in prompt.compose, which the desktop engine has by 2.1.308 (2.1.284 refused it) and which keeps them in front of the model while the desktop defers the tool. Kept on top: an agent's strip names the agent definition it runs as before its model and effort (worker · sonnet 5.5 · high; none for general-purpose) and, before its time, the context its last request carried (ctx 42k), with its share of the window only where the model id names that window ([1m]: ctx 251k · 25%); a bar's strips fold into one summary row by default (3 more agents · 2 running · 1 done, a waiting or failed agent keeping its own), the foldAgents option, on in the manifest and off for a host that passes no options, so upstream's folding and its tests stand as they are; agents the main thread starts in a turn before it opens a bar for that work move onto that bar as it opens (a new id, or a finished bar's id taken for the next task); the bars draw in the desktop app's own colours (the desktopColors option, on in the manifest: running in its clay #D97757, waiting in its blue, error and done in its danger and success; a pill a shade deeper where white reads at 4.5:1, each strip's tool word lifted until it reads at 4.6:1 on the desktop's tint and on the terminal's 4-bit one); a permission dialog put to you and left unanswered sounds decision, on the engine's permission_prompt notification; finished bars stay doneBarSeconds 60 s by default once /plan-progress-autoclose is on; the engine's own mark under the band (an element of type engine, which draws nothing while bars show) adds no gap under them, so the band sits centred in the desktop's card; the footer shows, before tok/s, how long the main conversation's prompt cache stays warm (the cacheTimer option, auto in the manifest, as cache-timer 0.3.2 counted it: Cache 42m, the seconds in the last minute, Cache cold; auto starts at 1h and follows a model switch's cache_ttl and a 5-to-60-minute idle request's cache read or re-write), the words changing once a minute and read by the band too, so a footer change never hands back an old band; a -cc.N build counts as a folder install, so it never asks GitHub for releases or runs claude plugin update from its settings window, and updates through this repo; the test engine shims Uint8Array#toBase64 for Node before 25, its stream returns its result as the engine's does, compile.cjs uses the TypeScript 7 CLI, and the one case that reads TypeScript's JavaScript API falls back to upstream's pattern under TypeScript 7MIT

Install a mod from this repo

Function hooks are early access, so turn them on first in ~/.claude/settings.json:

{ "env": { "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" } }
claude plugin marketplace add mtmtian/cc-mods
claude plugin install md-prompt@cc-mods

To install from a local checkout instead, so your own edits are what gets installed, pass its path: claude plugin marketplace add <path to this checkout>.

Install a mod from one marketplace only. With both md-prompt@nogu66 and md-prompt@cc-mods enabled, the prompt box is painted twice.

Change a mod

A local change bumps the mod's version in its .claude-plugin/plugin.json with a -cc.N suffix (0.1.1-cc.1, 0.1.1-cc.2, ...), since installed copies only update when the version changes. Then:

claude plugin marketplace update cc-mods
claude plugin update md-prompt@cc-mods

While working on a mod, --plugin-dir loads the checkout directly and reloads on save (for md-prompt: claude --plugin-dir mods/md-prompt/plugins/md-prompt); each mod's own README has its test commands.

Run the checks

Use the Node.js version in .node-version, then run from the repo root:

npm ci
npm run ci

The root CI workflow runs on every pull request, pushes to main, and manual dispatch. Test and plugin checks run on standard Ubuntu and macOS runners; workflow and shell checks run in a separate Ubuntu job:

CheckWhat it covers
npm testmd-prompt's Bun tests, plan-progress's asserted stub-engine regressions, and the upstream-status script's local Git fixtures
npm run check:pluginsMarketplace/source/name/license consistency, strict Claude manifest validation, native hook tests for md-prompt, and TypeScript checks for both plugins
Workflow and shell checksactionlint for the active root workflow and ShellCheck for the repository's shell scripts

The plugin checks copy the plugins into a temporary directory, use a fresh Claude config, and generate SDK declarations for the locked CLI version there. /cost is a local command: no login or model API key is needed. The API endpoint is set to a closed local port, so an accidental model request fails. The temporary copies are removed even when a check fails. These checks do not replace testing real prompt editing, desktop rendering or audio in Claude Desktop.

Development tools are version-pinned in package.json and package-lock.json; Actions use full commit SHAs. Dependabot proposes weekly npm-tool and Action updates; update actionlint's version and checksum together in the workflow. Claude and Bun require their native-binary install scripts, approved by exact version in allowScripts. When updating either package, review its install script, update the approval with npm install-scripts approve <package>, and rerun the checks. CI has read-only repository permissions, cancels superseded PR runs, and uses neither uploaded artifacts nor dependency caches.

Check and pull upstream changes

upstreams.tsv lists each mod's upstream URL and branch. scripts/upstream-status.sh reads it and, per mod, prints the upstream commit last synced, the upstream commits since, the paths changed here, and the paths changed on both sides (overlap_path=, where a pull may conflict). It only fetches; it never pulls or edits a mod. scripts/test-upstream-status.sh checks it against a throwaway upstream.

bash scripts/upstream-status.sh

To take the upstream changes, with the URL and branch from upstreams.tsv (on a branch, merged with a merge commit so the squash commit's git-subtree-split trailer stays on main):

git subtree pull --prefix=mods/<name> <url> <branch> --squash

Resolve conflicts by keeping each local change on top of upstream's version, never by taking one side whole. Then check that every local change still holds: the mod's tests (each local change has a regress case where it can), and a strict type check against the engine's types, which catches call sites the two sides changed differently.

Add another mod

git subtree add --prefix=mods/<name> https://github.com/<owner>/<repo>.git <branch> --squash

Then add the mod to upstreams.tsv, a row to the table above, and an entry to .claude-plugin/marketplace.json whose source points at the directory holding that mod's .claude-plugin/plugin.json.

A mod written here goes in mods/<name>/plugins/<name>/ with its own LICENSE beside it; it gets a row in the table and a marketplace entry, but no upstreams.tsv line.

Notes

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