Progress bars with stage colors, ETA, subagent strips and automatic session titles

Private collection of reusable Claude Code skills, shared across projects.
Clone once, then symlink each skill into the personal skills directory:
git clone git@github.com:Chasonnnn/agentic-engineering-skills-personal.git ~/agentic-engineering-skills-personal
ln -s ~/agentic-engineering-skills-personal/agy ~/.claude/skills/agy
ln -s ~/agentic-engineering-skills-personal/ambitious ~/.claude/skills/ambitious
ln -s ~/agentic-engineering-skills-personal/audit-skill ~/.claude/skills/audit-skill
ln -s ~/agentic-engineering-skills-personal/board-sync ~/.claude/skills/board-sync
ln -s ~/agentic-engineering-skills-personal/authmux ~/.claude/skills/authmux
ln -s ~/agentic-engineering-skills-personal/codex ~/.claude/skills/codex
ln -s ~/agentic-engineering-skills-personal/github-pr-validation-loop ~/.claude/skills/github-pr-validation-loop
ln -s ~/agentic-engineering-skills-personal/no-use-effect ~/.claude/skills/no-use-effect
ln -s ~/agentic-engineering-skills-personal/opencode ~/.claude/skills/opencode
ln -s ~/agentic-engineering-skills-personal/orchestrate ~/.claude/skills/orchestrate
ln -s ~/agentic-engineering-skills-personal/review-and-remediate-server-logs ~/.claude/skills/review-and-remediate-server-logs
Mods (Claude Code function-hook plugins) load from CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json:
"CLAUDE_CODE_PLUGIN_DIRS": "~/agentic-engineering-skills-personal/mods/progress"
New machines: repeat both steps. Updating: git -C ~/agentic-engineering-skills-personal pull (symlinks pick up changes automatically).
| Skill | What it does |
|---|---|
| agy | User-invoked (/agy). Wraps the Antigravity CLI (agy) for a Gemini 4 Argon second opinion with the same review, challenge, and consult modes and verdict contract as codex. Pinned to gemini-4-argon-high; read-only by default. |
| ambitious | User-invoked (/ambitious). Raises the current task along altitude, depth, and range, sets a measurable target with an outside check, then does the raised version. Based on Felix Rieseberg's article. |
| audit-skill | Audit or improve skill instructions and helpers with source-specific evidence; includes optional comparison guidance and the Provencher article reference. |
| board-sync | Sync planning state (specs/ADRs/roadmap) to a GitHub Project board as epic issues with nested sub-issues — epics on the board, slices hidden under them — plus an optional stale-issue refresh. |
| authmux | Resolve repository-bound authentication intent, verify provider identity evidence, route supported CLI commands through process-scoped contexts, and fail closed before wrong-account or wrong-project work. |
| codex | Wraps the OpenAI Codex CLI for an independent second opinion: review (PASS/FAIL/INCOMPLETE on an explicit diff scope), challenge (adversarial break-it), consult (ask anything, with session continuity). Ported from gstack's /codex skill — see credit note below. |
| dependency-modernization | Upgrade dependencies with official release review, local feature adoption, compatibility checks, and measured validation. |
| github-pr-validation-loop | Audit open PRs against the current base branch, reimplement valid findings cleanly, close invalid or superseded noise with evidence, and monitor CI through completion. |
| no-use-effect | Prefer explicit React data flow, replace ad-hoc Effects with derived state, event handlers, query libraries, or keyed remounting, and contain legitimate external synchronization in named hooks. |
| opencode | User-invoked (/opencode). Wraps the OpenCode CLI for a second opinion from any model it serves, with the same review, challenge, and consult modes and verdict contract as codex. Pinned to cornell/nto.gemini-4-argon; read-only by default through inline permission rules. |
| orchestrate | Coordinates delegates, independent review, and integration; shares CLI execution with codex. (Folded in from orchestrate-skill with history; that repo is archived.) |
| review-and-remediate-server-logs | Review live server logs, prioritize actionable failures, reproduce and fix their causes, validate through CI, and verify the result after an authorized deployment. |
| Mod | What it does |
|---|---|
| progress | Progress bars above the prompt: the mcp__progress__track tool, a hairline bar with stage notches and a moving shine (heavy-rule text bar in the terminal), elapsed time, subagent strips, a done line that fades out, a status-line fallback while hidden, and session names taken from the open bar or a one-time Haiku call. Commands: /bars, /bars-clear, /bars-demo. |
SKILL.md inside, frontmatter per Claude Code skill format. Mods live under mods/, one plugin folder each.codex/ is a standalone port of the /codex skill from gstack (Garry Tan, MIT license) — the original wraps the OpenAI Codex CLI as one of ~30 skills in a much larger multi-agent toolkit. This port keeps the review/challenge/consult mechanics and drops everything wired into gstack's own infrastructure (telemetry, question-tuning auto-decide, checkpoint mode, gbrain sync, the D<N> AskUserQuestion format), so it runs standalone with no dependency on gstack being installed.
Use the approved project/host Python runtime. Helpers use the standard library.
claude plugin validate mods/progress && claude plugin test mods/progress
python -m unittest discover -s codex/tests -v
python -m unittest discover -s github-pr-validation-loop/tests -v
The PR snapshot JSON now contains coverage and pull_requests; exit 2 signals incomplete coverage. The CI watcher requires explicit workflow IDs and a full commit SHA. See its skill for event selection, authentication, and remaining readiness checks.
hooks/register.tsx 832 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, Plan, PlanStage, PlanState, PlanStep, StepStatus, TitleState } from '../types'
5
6const TOOL = 'mcp__progress__track'
7const plans = atom({ plugin: 'progress', key: 'plans' } as const, [])
8const isOpen = atom({ plugin: 'progress', key: 'isOpen' } as const, true)
9const tick = atom({ plugin: 'progress', key: 'tick' } as const, 0)
10const titleState = atom({ plugin: 'progress', key: 'title' } as const, { last: null, isUserOwned: false, hasAsked: false } as TitleState)
11
12const MAX_BARS = 3
13const FADE_MS = 1500 // a finished bar fades out over this long once the next prompt is sent
14const FADE_FRAMES = 10
15const STRIP_LINGER_MS = 5000
16const STALE_TURNS = 2 // an open bar no update touched for this many main turns was left behind, as after a pivot
17const MAX_STRIPS = 4
18const AGENTS = 'agents:auto' // slug() never yields ':', so no model id can take it
19const PX_PER_COL = 8 // desktop reports about 8 CSS px per column
20
21const ACCENT = '#7AA2F7'
22const UNLIT = '#3A3936'
23const DIM = '#8A8884'
24const STATE_COLOR: Record<PlanState, string> = { running: ACCENT, needs_input: '#E0A33A', paused: DIM, error: '#E5484D', done: '#3FB68B' }
25const STATE_GLYPH: Record<PlanState, string> = { running: '●', needs_input: '?', paused: '●', error: '!', done: '✓' }
26const AGENT_COLOR: Record<AgentRun['state'], string> = { running: ACCENT, waiting: '#E0A33A', done: '#3FB68B', error: '#E5484D' }
27const STATUSES: StepStatus[] = ['pending', 'active', 'done', 'error', 'skipped']
28
29const RULES = `# Progress bars
30Tasks needing more than ~3 edits or commands get a bar via ${TOOL}: create it once with {id, title, stages:[{name, steps:["Step title", ...]}]} (2-7 stages with short steps, or one stage for a flat list; titles of at most 4 words, in the user's language), then update it with short calls only: {id, next:true} when the active step is finished, or {id, done:[...], active:"..."}, {id, failed:"...", note}. done, active and failed take exact step titles; free text goes in note. Send state "needs_input" with a note before asking the user to decide. When the work is finished, close the bar with {id, state:"done"} before the final reply. The bar title also becomes the session name, so make it describe the task. Never describe the bars to the user.`
31
32type Raw = Record<string, unknown>
33const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '')
34const isStatus = (v: unknown): v is StepStatus => STATUSES.includes(v as StepStatus)
35// the model sometimes sends an array as JSON text
36const items = (v: unknown): unknown[] => {
37 if (typeof v === 'string' && /^\s*\[/.test(v)) {
38 try {
39 v = JSON.parse(v)
40 } catch {
41 return []
42 }
43 }
44 return Array.isArray(v) ? v : []
45}
46const isRaw = (v: unknown): v is Raw => Boolean(v) && typeof v === 'object' && !Array.isArray(v)
47const isFinished = (s: StepStatus) => s === 'done' || s === 'skipped'
48const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()
49const slug = (s: string) =>
50 s
51 .toLowerCase()
52 .replace(/[^\p{L}\p{N}]+/gu, '-')
53 .replace(/^-|-$/g, '')
54 .slice(0, 40) || 'plan'
55
56// ---------- plan model ----------
57
58// one title or a list of them
59const titles = (v: unknown): string[] => (typeof v === 'string' && !/^\s*\[/.test(v) ? [v] : items(v).filter(x => typeof x === 'string'))
60
61// a step from {title, status} or a bare title; a restructured plan keeps the status of steps it carries over
62function readStep(v: unknown, prevSteps: PlanStep[]): PlanStep | null {
63 const title = isRaw(v) ? str(v.title ?? v.name) : str(v)
64 if (!title) return null
65 const asked = isRaw(v) ? v.status : undefined
66 const kept = prevSteps.find(st => same(st.title, title))?.status
67 return { title, status: isStatus(asked) ? asked : (kept ?? 'pending') }
68}
69
70// stages as the model sends them: [{name, steps}], a flat list of titles, or top-level steps
71function readStages(input: Raw, prev: Plan | null): PlanStage[] {
72 const prevSteps = prev?.stages.flatMap(s => s.steps) ?? []
73 const steps = (v: unknown) => items(v).flatMap(x => readStep(x, prevSteps) ?? [])
74 const raw = items(input.stages)
75 const grouped = raw.filter(isRaw).map(s => ({ name: str(s.name ?? s.title, 60) || 'Stage', steps: steps(s.steps) }))
76 const flat = raw.some(isRaw) ? [] : steps(raw.length > 0 ? raw : input.steps)
77 return [...grouped, { name: 'Steps', steps: flat }].filter(s => s.steps.length > 0)
78}
79
80// short updates: {next:true}, {done:[titles]}, {active:title}, {failed:title}; titles that match no step come back
81function applyOps(stages: PlanStage[], input: Raw): { stages: PlanStage[]; unknown: string[] } {
82 const out = stages.map(s => ({ ...s, steps: s.steps.map(st => ({ ...st })) }))
83 const steps = out.flatMap(s => s.steps)
84 const unknown: string[] = []
85 const find = (title: string) => {
86 const st = steps.find(x => same(x.title, title))
87 if (!st && title.trim()) unknown.push(str(title, 60))
88 return st
89 }
90 if (input.next === true) {
91 const activeAt = steps.findIndex(st => st.status === 'active')
92 const at = activeAt >= 0 ? activeAt : steps.findIndex(st => !isFinished(st.status))
93 const cur = steps[at]
94 if (cur) cur.status = 'done'
95 const following = steps.slice(at + 1).find(st => st.status === 'pending')
96 if (following) following.status = 'active'
97 }
98 for (const t of titles(input.done)) {
99 const st = find(t)
100 if (st) st.status = 'done'
101 }
102 const active = typeof input.active === 'string' ? find(input.active) : undefined
103 if (active) {
104 const at = steps.indexOf(active)
105 steps.forEach((st, i) => {
106 if (st.status === 'active' && i !== at) st.status = i < at ? 'done' : 'pending'
107 })
108 active.status = 'active'
109 }
110 const failed = typeof input.failed === 'string' ? find(input.failed) : undefined
111 if (failed) failed.status = 'error'
112
113 return { stages: out, unknown }
114}
115
116function normalize(input: Raw, prev: Plan | null, now: number, id: string): { plan: Plan; unknown: string[] } {
117 const fresh = readStages(input, prev)
118 const isPartial = fresh.length === 0 && prev !== null
119 // ops apply to a new or restructured plan too, so one call can create and advance it
120 const { stages, unknown } = applyOps(isPartial ? prev.stages : fresh, input)
121 const steps = stages.flatMap(s => s.steps)
122 // a fresh plan with nothing active starts on its first open step
123 if (!isPartial && !steps.some(s => s.status === 'active')) {
124 const first = steps.find(s => !isFinished(s.status) && s.status !== 'error')
125 if (first) first.status = 'active'
126 }
127 const title = str(input.title, 60) || prev?.title || 'Plan'
128 const isAllDone = steps.length > 0 && steps.every(s => isFinished(s.status))
129 const asked = (input.state ?? input.status) as PlanState
130 const state: PlanState = STATE_GLYPH[asked] ? asked : isAllDone ? 'done' : typeof input.failed === 'string' ? 'error' : 'running'
131 // any update ends a pause; the paused time stays out of the clock
132 const pausedAt = prev?.state === 'paused' ? (prev.pausedAt ?? null) : null
133 const pausedMs = (prev?.pausedMs ?? 0) + (pausedAt !== null && state !== 'paused' ? now - pausedAt : 0)
134
135 const plan: Plan = {
136 id,
137 title,
138 stages,
139 state,
140 note: str(input.note, 160) || null,
141 startedAt: prev?.startedAt ?? now,
142 doneAt: state === 'done' ? (prev?.doneAt ?? now) : null,
143 pausedAt: state === 'paused' ? (pausedAt ?? now) : null,
144 pausedMs,
145 fadeAt: null,
146 idleTurns: 0,
147 agents: prev?.agents ?? [],
148 }
149 return { plan, unknown }
150}
151
152type Where = { finished: number; total: number; stage: number; step: number; stageSize: number; activeTitle: string | null }
153
154function where(p: Plan): Where {
155 const flat = p.stages.flatMap((s, i) => s.steps.map((step, j) => ({ i, j, step })))
156 const finished = flat.filter(x => isFinished(x.step.status)).length
157 const cur = flat.find(x => x.step.status === 'active') ?? flat.find(x => !isFinished(x.step.status))
158 const stage = cur?.i ?? Math.max(0, p.stages.length - 1)
159 const stageSize = p.stages[stage]?.steps.length ?? 0
160
161 return { finished, total: flat.length, stage, step: cur ? cur.j + 1 : stageSize, stageSize, activeTitle: cur?.step.title ?? null }
162}
163
164// lit share of the rule; a done bar is full even if the model closed it with steps open
165const fraction = (p: Plan) => {
166 const w = where(p)
167 return p.state === 'done' ? 1 : w.finished / Math.max(1, w.total)
168}
169
170const percent = (p: Plan) => Math.round(fraction(p) * 100)
171
172const duration = (ms: number) => {
173 const sec = Math.max(0, Math.round(ms / 1000))
174 if (sec < 60) return `${sec}s`
175 const min = Math.floor(sec / 60)
176 if (min < 60) return `${min}m${String(sec % 60).padStart(2, '0')}s`
177 return `${Math.floor(min / 60)}h${String(min % 60).padStart(2, '0')}m`
178}
179
180// 0 until the fade starts, 1 when the bar leaves
181const fadeOf = (p: Plan, now: number) => (p.fadeAt ? Math.min(1, Math.max(0, (now - p.fadeAt) / FADE_MS)) : 0)
182
183// terminal fade: characters drop out in a scattered order as f goes 0 -> 1
184const scatter = (i: number) => {
185 const x = Math.sin(i * 127.1 + 311.7) * 43758.5453
186 return x - Math.floor(x)
187}
188const dissolve = (text: string, f: number) => (f <= 0 ? text : [...text].map((c, i) => (scatter(i) < f ? ' ' : c)).join(''))
189
190// the clock stops while a bar is paused or done
191const elapsed = (p: Plan, now: number) => duration((p.doneAt ?? p.pausedAt ?? now) - p.startedAt - (p.pausedMs ?? 0))
192
193const stageLabel = (p: Plan) => {
194 const w = where(p)
195 return `${p.stages[w.stage]?.name ?? ''} ${w.step}/${w.stageSize}`
196}
197
198// the words beside the title: where the work is, or what it waits on
199function detail(p: Plan): string {
200 const note = p.note ? ` · ${p.note}` : ''
201 if (p.state === 'needs_input') return `Needs your input${note}`
202 if (p.state === 'error') return `Failed${note}`
203 if (p.state === 'done') {
204 const total = where(p).total
205 return `Completed · ${total} step${total === 1 ? '' : 's'}`
206 }
207 const active = where(p).activeTitle
208 return `${p.state === 'paused' ? 'Paused · ' : ''}${stageLabel(p)}${active ? ` · ${active}` : ''}`
209}
210
211const isOpenPlan = (p: Plan) => p.id !== AGENTS && p.state !== 'done' && !p.fadeAt
212
213// ---------- drawing ----------
214
215const LINE_H = 3
216const NOTCH = 2
217
218// where the lit part ended at the last draw, so a redraw glides from there; equal values keep the svg string stable
219const lastFill = new Map<string, number>()
220
221// desktop: one hairline, notched where stages meet; the lit part glides to its new edge and a shine runs over it;
222// a fading bar animates its own opacity, and the string stays the same each frame so the animation runs once
223function lineSvg(p: Plan, W: number, isFading: boolean): string {
224 const w = where(p)
225 const total = Math.max(1, w.total)
226 const fx = fraction(p) * W
227 const color = STATE_COLOR[p.state]
228 const from = lastFill.get(p.id) ?? fx
229 lastFill.set(p.id, fx)
230 const glide =
231 Math.abs(from - fx) > 0.5
232 ? `<animate attributeName="width" from="${from.toFixed(1)}" to="${fx.toFixed(1)}" dur=".5s" calcMode="spline" keyTimes="0;1" keySplines=".2 .8 .2 1" fill="freeze"/>`
233 : ''
234 let segs = ''
235 let at = 0
236 p.stages.forEach((s, i) => {
237 const x0 = (at / total) * W + (i > 0 ? NOTCH / 2 : 0)
238 at += s.steps.length
239 const x1 = (at / total) * W - (i < p.stages.length - 1 ? NOTCH / 2 : 0)
240 segs += `<rect x="${x0.toFixed(1)}" width="${Math.max(0, x1 - x0).toFixed(1)}" height="${LINE_H}" rx="1.5"/>`
241 })
242 const shine =
243 p.state === 'running' && fx > 0
244 ? `<rect width="${(W * 0.25).toFixed(1)}" height="${LINE_H}" fill="url(#shine)"><animate attributeName="x" from="${(-W * 0.25).toFixed(1)}" to="${W.toFixed(1)}" dur="2s" repeatCount="indefinite"/></rect>`
245 : ''
246 const fade = isFading
247 ? `<animate attributeName="opacity" from="1" to="0" dur="${FADE_MS / 1000}s" calcMode="spline" keyTimes="0;1" keySplines=".4 0 .6 1" fill="freeze"/>`
248 : ''
249 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${LINE_H}" viewBox="0 0 ${W} ${LINE_H}">
250<defs><linearGradient id="shine"><stop offset="0" stop-color="#fff" stop-opacity="0"/><stop offset=".5" stop-color="#fff" stop-opacity=".55"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
251<clipPath id="lit"><rect width="${fx.toFixed(1)}" height="${LINE_H}">${glide}</rect></clipPath></defs>
252<g>${fade}<g fill="${UNLIT}">${segs}</g><g clip-path="url(#lit)"><g fill="${color}">${segs}</g>${shine}</g></g></svg>`
253}
254
255// terminal: a heavy rule, lit up to a half-cell head
256function lineText(p: Plan, cols: number): { lit: string; rest: string } {
257 const filled = Math.round(fraction(p) * cols)
258 if (filled >= cols) return { lit: '━'.repeat(cols), rest: '' }
259 if (filled === 0) return { lit: '', rest: '━'.repeat(cols) }
260 return { lit: `${'━'.repeat(filled - 1)}╸`, rest: '━'.repeat(cols - filled) }
261}
262
263// strips that show: unfinished first, finished ones fold after a few seconds, failed ones stay
264function visibleAgents(p: Plan, now: number): { shown: AgentRun[]; hidden: number } {
265 const live = p.agents.filter(a => a.state !== 'done' || now - (a.endedAt ?? now) < STRIP_LINGER_MS)
266 const ranked = [...live].sort((a, b) => Number(a.state === 'done') - Number(b.state === 'done'))
267 return { shown: ranked.slice(0, MAX_STRIPS), hidden: Math.max(0, ranked.length - MAX_STRIPS) }
268}
269
270// ---------- engine glue ----------
271
272// adds or replaces one bar by id; past MAX_BARS the oldest finished bars make room, open ones never do;
273// computed inside update() from the latest list, so parallel writers do not drop each other
274function placeBar(all: readonly Plan[], next: Plan): Plan[] {
275 const rest = all.some(p => p.id === next.id) ? all.map(p => (p.id === next.id ? next : p)) : [...all, next]
276 while (rest.length > MAX_BARS) {
277 const doneAt = rest.findIndex(p => p.state === 'done' && p.id !== next.id)
278 if (doneAt < 0) break
279 rest.splice(doneAt, 1)
280 }
281 return rest
282}
283
284// drops what the module keeps per bar once the bar is gone
285function forget(id: string) {
286 lastFill.delete(id)
287 for (const [agentId, home] of agentHome) if (home === id) agentHome.delete(agentId)
288}
289
290async function syncStatus($: EngineInterface) {
291 const live = (await read($, plans)).filter(isOpenPlan).at(-1)
292 if (!live || (await read($, isOpen))) return $.ui.status(undefined)
293 const w = where(live)
294 $.ui.status(`${live.title} · ${stageLabel(live)}${w.activeTitle ? ` · ${w.activeTitle}` : ''}`)
295}
296
297async function dropPlan($: EngineInterface, id: string) {
298 forget(id)
299 await update($, plans, all => all.filter(p => p.id !== id))
300 await syncStatus($)
301}
302
303// fades out the bars `pick` chooses, then removes them: done bars on the next prompt, stale ones at a turn's end
304async function fadeBars($: EngineInterface, pick: (p: Plan) => boolean) {
305 const now = await $.clock.now()
306 let fading: string[] = []
307 await update($, plans, all => {
308 fading = []
309 return all.map(p => {
310 if (p.fadeAt || !pick(p)) return p
311 fading.push(p.id)
312 return { ...p, fadeAt: now }
313 })
314 })
315 if (fading.length === 0) return
316 // the terminal has no opacity: redraw a few frames while the fade runs
317 for (let k = 1; k < FADE_FRAMES; k++) {
318 $.clock.after((k * FADE_MS) / FADE_FRAMES, () => update($, tick, n => n + 1))
319 }
320 $.clock.after(FADE_MS, async () => {
321 // a bar updated during the fade has lost its fadeAt and stays
322 const gone = (await read($, plans)).filter(p => fading.includes(p.id) && p.fadeAt === now)
323 for (const p of gone) forget(p.id)
324 if (gone.length > 0) await update($, plans, all => all.filter(p => !gone.some(g => g.id === p.id)))
325 await syncStatus($)
326 })
327}
328
329async function putPlan($: EngineInterface, next: Plan) {
330 let prev: Plan | undefined
331 let evicted: string[] = []
332 await update($, plans, all => {
333 prev = all.find(p => p.id === next.id)
334 const placed = placeBar(all, next)
335 evicted = all.filter(p => !placed.some(x => x.id === p.id)).map(p => p.id)
336 return placed
337 })
338 evicted.forEach(forget)
339 if (!prev && next.id !== AGENTS) await update($, isOpen, () => true)
340 await syncStatus($)
341}
342
343// a tiny plan for /bars-demo
344const DEMO = (now: number): Plan => {
345 const s = (title: string, st: StepStatus) => ({ title, status: st })
346 return {
347 id: 'demo',
348 title: 'Orders module',
349 state: 'running',
350 note: null,
351 startedAt: now - 252_000,
352 doneAt: null,
353 agents: [
354 { id: 'demo-a', title: 'Explore schema', state: 'running', tool: 'Grep', startedAt: now - 41_000, endedAt: null },
355 { id: 'demo-b', title: 'Check migrations', state: 'done', tool: 'Done', startedAt: now - 80_000, endedAt: now - 1_000 },
356 ],
357 stages: [
358 { name: 'Analysis', steps: [s('Read modules', 'done'), s('Find dependencies', 'done'), s('List changes', 'done')] },
359 { name: 'Migration', steps: [s('Schema', 'done'), s('Migration', 'done'), s('Move data', 'active'), s('Indexes', 'pending')] },
360 { name: 'API', steps: [s('Endpoints', 'pending'), s('Validation', 'pending')] },
361 { name: 'Verify', steps: [s('Tests', 'pending'), s('Build', 'pending')] },
362 ],
363 }
364}
365
366// ---------- agents: drawn from engine events alone, no model calls ----------
367// module maps: a reload forgets running agents, whose strips then stay until the bar closes
368const agentHome = new Map<string, string>() // agentId -> bar id
369const toolUses = new Map<string, string>() // tool_use_id -> agentId, to find who waits on a permission
370
371async function editAgent($: EngineInterface, agentId: string, change: (a: AgentRun) => AgentRun) {
372 const home = agentHome.get(agentId)
373 if (!home) return
374 const before = (await read($, plans)).find(p => p.id === home)?.agents.find(a => a.id === agentId)
375 if (!before) return
376 const after = change(before)
377 if (after.state === before.state && after.tool === before.tool && after.endedAt === before.endedAt) return
378 const now = await $.clock.now()
379 await update($, plans, all =>
380 all.map(p => {
381 if (p.id !== home) return p
382 const agents = p.agents.map(a => (a.id === agentId ? change(a) : a))
383 if (p.id !== AGENTS) return { ...p, agents }
384 // the mod's own bar is done once every agent on it has ended
385 const isOver = agents.every(a => a.state === 'done' || a.state === 'error')
386 return { ...p, agents, state: isOver ? (agents.some(a => a.state === 'error') ? 'error' : 'done') : 'running', doneAt: isOver ? now : null }
387 }),
388 )
389}
390
391// a bare title is the usual form; {title, status} also works
392const STEP_SCHEMA = { anyOf: [{ type: 'string' }, { type: 'object', required: ['title'], properties: { title: { type: 'string' }, status: { enum: STATUSES } } }] }
393const WORK_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'])
394const WORK_BEFORE_NUDGE = 4
395const CALLS_BEFORE_STALE = 6
396const TITLE_PROMPT = 'Name this work session in 3 to 5 words, Title Case, no quotes or trailing punctuation. Reply with the name only.\n\n<request>\n'
397
398export const register: Register = on => {
399 // per-turn counts; a reload only restarts them
400 let workCalls = 0
401 let sinceUpdate = 0
402 let isNudged = false
403 // bars this main turn updated
404 const touched = new Set<string>()
405
406 on('session.start', async ($, e, next) => {
407 await $.tool.register({
408 name: 'track',
409 description: 'Live progress bar above the prompt, one per id. Create with title + stages; update with short ops (next, done, active, failed) or state.',
410 inputSchema: {
411 type: 'object',
412 required: ['id'],
413 properties: {
414 id: { type: 'string', description: 'Bar id; reuse it for updates' },
415 title: { type: 'string', description: 'At most 4 words; also used as the session name' },
416 stages: {
417 type: 'array',
418 description: 'Full breakdown, only when creating or restructuring: [{name: "Build", steps: ["Step title", ...]}]',
419 items: { type: 'object', required: ['name', 'steps'], properties: { name: { type: 'string' }, steps: { type: 'array', items: STEP_SCHEMA } } },
420 },
421 next: { type: 'boolean', description: 'Active step finished, start the next one' },
422 done: { type: 'array', items: { type: 'string' }, description: 'Exact step titles now finished' },
423 active: { type: 'string', description: 'Exact step title now in progress; free text goes in note' },
424 failed: { type: 'string', description: 'Exact step title that failed' },
425 state: { enum: ['running', 'needs_input', 'error', 'done'] },
426 note: { type: 'string', description: 'One line for needs_input or error' },
427 },
428 },
429 })
430 // one tick a second while anything moves: clocks, the pulsing glyph, strips folding
431 $.clock.every(1000, async () => {
432 const all = await read($, plans)
433 const isMoving = all.some(p => p.state === 'running' || p.state === 'needs_input' || p.agents.some(a => a.endedAt === null))
434 if (isMoving || agentHome.size > 0) await update($, tick, n => n + 1)
435 })
436 await $.command.register({ name: 'bars', description: 'Show or hide the progress bars' })
437 await $.command.register({ name: 'bars-clear', description: 'Remove all progress bars' })
438 await $.command.register({ name: 'bars-demo', description: 'Show a sample progress bar' })
439 await syncStatus($)
440
441 return next(e)
442 })
443
444 on('prompt.compose', async ($, e, next) => {
445 const result = await next(e)
446 return { sections: [...result.sections, { id: 'progress:rules', text: RULES, scope: 'session' as const }] }
447 })
448
449 on('turn.start', async ($, e, next) => {
450 workCalls = 0
451 sinceUpdate = 0
452 isNudged = false
453 touched.clear()
454 return next(e)
455 })
456
457 // the person answering, here or from a phone, clears "needs input"; open bars ride along as one short context line
458 on('prompt.submit', async ($, e, next) => {
459 if (e.origin.kind !== 'composer' && e.origin.kind !== 'bridge') return next(e)
460 const all = await read($, plans)
461 if (all.some(p => p.state === 'needs_input')) {
462 await update($, plans, xs => xs.map(p => (p.state === 'needs_input' ? { ...p, state: 'running' as const, note: null } : p)))
463 }
464 const open = all.filter(isOpenPlan)
465 if (open.length === 0) return next(e)
466 const line = `progress: open bars ${open.map(p => `${p.id} (${stageLabel(p)})`).join(', ')}`
467 return next({ ...e, context: [...(e.context ?? []), line] })
468 })
469
470 // session name: the newest open bar's title, else a short Haiku name for the first prompt;
471 // a name the person set themselves is never replaced
472 on('classic.UserPromptSubmit', async ($, e, next) => {
473 const isPerson = e.source === undefined || e.source === 'user'
474 // the person's next prompt fades the done bars
475 if (isPerson) await fadeBars($, p => p.state === 'done')
476 const result = await next(e)
477 if (result.sessionTitle || !isPerson) return result
478 const t = await read($, titleState)
479 if (t.isUserOwned) return result
480 const current = e.session_title?.trim()
481 if (current && current !== t.last) {
482 // someone else named it: the person (a rename) or a resumed session
483 await update($, titleState, s => ({ ...s, isUserOwned: true }))
484 return result
485 }
486 let title = (await read($, plans)).filter(isOpenPlan).at(-1)?.title ?? ''
487 if (!title && !t.hasAsked && t.last === null && e.prompt.trim().length > 0) {
488 await update($, titleState, s => ({ ...s, hasAsked: true }))
489 const named = await $.model.complete({ model: 'haiku', prompt: `${TITLE_PROMPT}${e.prompt.slice(0, 1500)}\n</request>`, maxTokens: 24, effort: 'low', timeoutMs: 4000 })
490 if (named.isAnswered) title = str(named.text.replace(/["'`*#.]/g, ''), 60)
491 }
492 if (!title || title === t.last) return result
493 await update($, titleState, s => ({ ...s, last: title }))
494 return { ...result, sessionTitle: title }
495 })
496
497 on('tool.call', { tool: TOOL }, async ($, e) => {
498 const raw = e as unknown as Raw
499 const now = await $.clock.now()
500 const id = slug(str(raw.id, 60) || str(raw.title, 60))
501 const all = await read($, plans)
502 const prev = all.find(p => p.id === id) ?? null
503 const { plan: next, unknown } = normalize(raw, prev, now, id)
504 if (next.stages.length === 0) {
505 // closing a bar that already left is not a mistake worth a retry
506 if (!prev && (raw.state ?? raw.status) === 'done') return { result: `${id}: no open bar, nothing to close` }
507 const why = raw.stages !== undefined || raw.steps !== undefined ? `the stages for "${id}" have no steps` : `no bar "${id}" yet`
508 const open = all.filter(isOpenPlan).map(p => p.id)
509 const hint = open.length > 0 ? ` Open bars: ${open.join(', ')}.` : ''
510 return { deny: `track: ${why}. Create it with {id, title, stages:[{name:"Build", steps:["First step","Second step"]}]}.${hint}` }
511 }
512 sinceUpdate = 0
513 touched.add(id)
514 await putPlan($, next)
515 const w = where(next)
516 const left = next.stages.flatMap(s => s.steps).filter(st => !isFinished(st.status)).map(st => st.title)
517 const miss = unknown.length > 0 ? `; no step titled ${unknown.map(t => `"${t}"`).join(', ')}, open steps: ${left.slice(0, 6).join(' | ') || 'none'}` : ''
518 return { result: `${id}: ${w.finished}/${w.total}, ${next.state}${w.activeTitle && next.state !== 'done' ? `, active "${w.activeTitle}"` : ''}${miss}` }
519 })
520
521 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
522 const live = (await read($, plans)).filter(p => (p.state === 'running' || p.state === 'needs_input') && p.id !== AGENTS).at(-1)
523 const mark = (from: PlanState, to: PlanState, note?: null) =>
524 update($, plans, all => all.map(p => (p.id === live?.id && p.state === from ? { ...p, state: to, ...(note === null ? { note } : {}) } : p)))
525 if (live?.state === 'running') await mark('running', 'needs_input')
526 try {
527 return await next(e)
528 } finally {
529 // answered, refused or interrupted: back to work, the question's note goes with it
530 if (live) await mark('needs_input', 'running', null)
531 }
532 })
533
534 // main loop: soft reminders only, never a refusal
535 on('tool.call', async ($, e, next) => {
536 if (e.agentId) {
537 const agentId = e.agentId
538 if (!agentHome.has(agentId)) return next(e)
539 await editAgent($, agentId, a => ({ ...a, state: 'running', tool: String(e.tool).replace(/^mcp__[^_]+__/, '') }))
540 if (e.tool_use_id) toolUses.set(e.tool_use_id, agentId)
541 const ran = await next(e)
542 if (e.tool_use_id) toolUses.delete(e.tool_use_id)
543 await editAgent($, agentId, a => (a.state === 'waiting' ? { ...a, state: 'running' } : a))
544 return ran
545 }
546 if (!WORK_TOOLS.has(String(e.tool))) return next(e)
547 const ran = await next(e)
548 if (ran.deny !== undefined || ran.isReadOnly) return ran
549 workCalls += 1
550 sinceUpdate += 1
551 const hasLive = (await read($, plans)).some(isOpenPlan)
552 const note = (text: string) => ({ ...ran, context: [...(ran.context ?? []), text] })
553 if (!hasLive && !isNudged && workCalls >= WORK_BEFORE_NUDGE) {
554 isNudged = true
555 return note(`progress: this task has several steps; create a bar with ${TOOL}.`)
556 }
557 if (hasLive && sinceUpdate >= CALLS_BEFORE_STALE) {
558 sinceUpdate = 0
559 return note('progress: the bar may be stale; send {id, next:true} if a step finished.')
560 }
561 return ran
562 })
563
564 on('agent.spawn', async ($, e, next) => {
565 const started = await next(e)
566 if (!('agentId' in started) || !started.agentId) return started
567 const id = started.agentId
568 const now = await $.clock.now()
569 const parentHome = e.parentAgentId ? agentHome.get(e.parentAgentId) : undefined
570 const run: AgentRun = { id, title: (e.description || e.subagentType || 'Agent').slice(0, 60), state: 'running', tool: 'Starting', startedAt: now, endedAt: null }
571 let home = AGENTS
572 let isNew = false
573 await update($, plans, all => {
574 // the parent's bar, else the newest open bar, else the mod's own; a bar closed meanwhile is skipped
575 const isLive = (h: string | undefined) => h !== undefined && all.some(p => p.id === h && isOpenPlan(p))
576 home = [parentHome, all.filter(isOpenPlan).at(-1)?.id].find(isLive) ?? AGENTS
577 isNew = false
578 const host = all.find(p => p.id === home)
579 if (host) {
580 // a finished agents bar starts a fresh batch
581 const agents = host.id === AGENTS && host.state !== 'running' ? [run] : [...host.agents, run]
582 return all.map(p => (p.id === home ? { ...p, agents, ...(p.id === AGENTS ? { state: 'running' as const, doneAt: null } : {}) } : p))
583 }
584 isNew = true
585 return placeBar(all, { id: AGENTS, title: 'Agents', stages: [], state: 'running', note: null, startedAt: now, doneAt: null, agents: [run] })
586 })
587 agentHome.set(id, home)
588 if (isNew) await update($, isOpen, () => true)
589 return started
590 })
591
592 // a subagent held on a permission prompt turns amber until the call goes on
593 on('tool.check', async ($, e, next) => {
594 const verdict = await next(e)
595 const useId = e.tool_use_id
596 const agentId = useId ? toolUses.get(useId) : undefined
597 if (agentId && useId && verdict.decision === 'ask') {
598 // the mode often settles an ask in a blink; only a call still held after a moment waits on the person
599 $.clock.after(600, async () => {
600 if (toolUses.get(useId) === agentId) await editAgent($, agentId, a => ({ ...a, state: 'waiting', tool: 'Needs approval' }))
601 })
602 }
603 return verdict
604 })
605
606 on('turn.complete', async ($, e, next) => {
607 const agentId = e.agentId
608 if (agentId && agentHome.has(agentId)) {
609 const now = await $.clock.now()
610 const isFailed = e.reason !== 'answer'
611 const tool = e.reason === 'aborted' ? 'Stopped' : isFailed ? 'Failed' : 'Done'
612 await editAgent($, agentId, a => ({ ...a, state: isFailed ? 'error' : 'done', tool, endedAt: now }))
613 agentHome.delete(agentId)
614 }
615 if (!agentId) {
616 // the main turn ended: a running plan whose steps are all finished closes itself, any other pauses;
617 // an open bar this turn left alone ages, and one left alone for STALE_TURNS fades out
618 const now = await $.clock.now()
619 let isChanged = false
620 await update($, plans, all => {
621 isChanged = false
622 return all.map(p => {
623 if (!isOpenPlan(p)) return p
624 isChanged = true
625 const idleTurns = touched.has(p.id) ? 0 : (p.idleTurns ?? 0) + 1
626 const steps = p.stages.flatMap(s => s.steps)
627 if (p.state !== 'running' || steps.length === 0) return { ...p, idleTurns }
628 return steps.every(s => isFinished(s.status))
629 ? { ...p, idleTurns, state: 'done' as const, doneAt: now }
630 : { ...p, idleTurns, state: 'paused' as const, pausedAt: now }
631 })
632 })
633 touched.clear()
634 await fadeBars($, p => isOpenPlan(p) && (p.idleTurns ?? 0) >= STALE_TURNS)
635 if (isChanged) await syncStatus($)
636 }
637 return next(e)
638 })
639
640 on('command.run', { command: 'bars' }, async $ => {
641 if ((await read($, plans)).length === 0) return { text: 'No bars yet. /bars-demo shows a sample.' }
642 const open = await read($, isOpen)
643 await update($, isOpen, () => !open)
644 await syncStatus($)
645 return { text: open ? 'Bars hidden; the status line shows the current step.' : 'Bars shown.' }
646 })
647
648 on('command.run', { command: 'bars-clear' }, async $ => {
649 for (const p of await read($, plans)) forget(p.id)
650 await update($, plans, () => [])
651 await syncStatus($)
652 return { text: 'Bars removed.' }
653 })
654
655 on('command.run', { command: 'bars-demo' }, async $ => {
656 await putPlan($, DEMO(await $.clock.now()))
657 await update($, isOpen, () => true)
658 return { text: 'Sample bar shown above the prompt.' }
659 })
660
661 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
662 const count = (await read($, plans)).length
663 const below = await next(e)
664 if (count === 0) return below
665 const open = await read($, isOpen)
666 const { Box, Button } = $.ui.resolve(e)
667 const press = async () => {
668 await update($, isOpen, () => !open)
669 await syncStatus($)
670 }
671 return (
672 <Box flexDirection="row" alignItems="center" gap={1}>
673 <Button key="bars-toggle" dimColor={!open} label={count > 1 ? `Bars ${count}` : 'Bars'} onPress={press} />
674 {below}
675 </Box>
676 )
677 })
678
679 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
680 const all = await read($, plans)
681 if (all.length === 0 || e.props.hasSurvey || !(await read($, isOpen))) return next(e)
682 const t = $.ui.resolve(e)
683 const { Box, Button, Text } = t
684 // the terminal's table answers Svg with an empty box, so its text drawing is chosen by surface
685 const Svg = e.surface !== 'terminal' && 'Svg' in t ? t.Svg : null
686 const n = await read($, tick)
687 const now = await $.clock.now()
688 const cols = Math.max(40, e.props.bodyColumns || 100)
689
690 const isTerminal = Svg === null
691 const dim = DIM
692
693 // terminal rows share column widths, so every rule starts and ends at the same place
694 const tracked = all.filter(p => p.id !== AGENTS)
695 const titleCols = Math.min(Math.round(cols * 0.25), Math.max(8, ...tracked.map(p => p.title.length)))
696 const detailCols = Math.min(Math.round(cols * 0.35), Math.max(8, ...tracked.map(p => detail(p).length)))
697 const timeCols = Math.max(4, ...tracked.map(p => elapsed(p, now).length))
698 const ruleCols = Math.max(8, cols - titleCols - detailCols - timeCols - 16)
699
700 const strips = (p: Plan) => {
701 const v = visibleAgents(p, now)
702 const count = v.shown.length + (v.hidden > 0 ? 1 : 0)
703 const branch = (i: number) => (isTerminal ? (i === count - 1 ? '└ ' : '├ ') : '')
704 const rows = v.shown.map((a, i) => {
705 const c = AGENT_COLOR[a.state]
706 const dot = a.state === 'running' ? (n % 2 === 0 ? '●' : '○') : a.state === 'done' ? '✓' : a.state === 'error' ? '✕' : '?'
707 const isEnded = a.state === 'done'
708 return (
709 <Box key={`agent-${a.id}`} flexDirection="row" gap={1} paddingLeft={2}>
710 <Text dimColor>{branch(i)}</Text>
711 <Text color={c}>{dot}</Text>
712 <Text dimColor={isEnded} wrap="truncate">
713 {a.title}
714 </Text>
715 <Text color={dim}>{isEnded ? 'done' : a.tool}</Text>
716 <Box flexGrow={1} />
717 <Text color={dim}>{duration((a.endedAt ?? now) - a.startedAt)}</Text>
718 </Box>
719 )
720 })
721 if (v.hidden > 0) {
722 rows.push(
723 <Box key={`agents-more-${p.id}`} flexDirection="row" gap={1} paddingLeft={2}>
724 <Text dimColor>{branch(count - 1)}</Text>
725 <Text color={dim}>{`+${v.hidden} more`}</Text>
726 </Box>,
727 )
728 }
729 return rows
730 }
731
732 const bar = (p: Plan) => {
733 const f = fadeOf(p, now)
734 const isFading = Boolean(p.fadeAt)
735 const fade = (s: string) => dissolve(s, f)
736 const close = !isFading ? <Button key={`close-${p.id}`} plain dimColor label="✕" onPress={() => dropPlan($, p.id)} /> : null
737 if (p.id === AGENTS) {
738 if (p.state === 'done') {
739 const count = p.agents.length
740 const label = `${p.title} · ${count} agent${count === 1 ? '' : 's'} · ${elapsed(p, now)}`
741 return [
742 <Box key={`bar-${p.id}`} flexDirection="row" gap={1}>
743 <Text wrap="truncate">
744 <Text color={STATE_COLOR.done}>{fade('✓')}</Text>
745 <Text color={dim}>{` ${fade(label)}`}</Text>
746 </Text>
747 <Box flexGrow={1} />
748 {close}
749 </Box>,
750 ]
751 }
752 const ended = p.agents.filter(a => a.endedAt !== null).length
753 return [
754 <Box key={`bar-${p.id}`} flexDirection="row" gap={1}>
755 <Text color={STATE_COLOR[p.state]}>{STATE_GLYPH[p.state]}</Text>
756 <Text bold>Agents</Text>
757 <Text color={dim}>{`${ended}/${p.agents.length} done`}</Text>
758 <Box flexGrow={1} />
759 {close}
760 </Box>,
761 ...strips(p),
762 ]
763 }
764 const pct = percent(p)
765 const color = STATE_COLOR[p.state]
766 // only a running bar blinks; paused, done and the rest hold still
767 const glyph = p.state === 'running' && n % 2 === 1 ? '○' : STATE_GLYPH[p.state]
768 const words = detail(p)
769 const wordsColor = p.state === 'running' ? dim : color
770 const pctText = `${String(pct).padStart(3, ' ')}%`
771 const below = isFading ? [] : strips(p)
772
773 if (isTerminal) {
774 const rule = lineText(p, ruleCols)
775 return [
776 <Box key={`bar-${p.id}`} flexDirection="row" gap={1}>
777 <Text color={color}>{fade(glyph)}</Text>
778 <Box width={titleCols} flexShrink={0}>
779 <Text bold wrap="truncate">
780 {fade(p.title)}
781 </Text>
782 </Box>
783 <Text>
784 <Text color={color}>{fade(rule.lit)}</Text>
785 <Text color={UNLIT}>{fade(rule.rest)}</Text>
786 </Text>
787 <Box width={detailCols} flexShrink={0}>
788 <Text color={wordsColor} wrap="truncate">
789 {fade(words)}
790 </Text>
791 </Box>
792 <Box width={timeCols} flexShrink={0}>
793 <Text color={dim}>{fade(elapsed(p, now))}</Text>
794 </Box>
795 <Text color={dim}>{fade(pctText)}</Text>
796 {close}
797 </Box>,
798 ...below,
799 ]
800 }
801
802 const W = (cols - 2) * PX_PER_COL
803 const alt = `${p.title}: ${words}, ${pct}%`
804 return [
805 <Box key={`bar-${p.id}`} flexDirection="column" gap={1}>
806 <Box flexDirection="row" alignItems="center" gap={1}>
807 <Text color={color}>{fade(glyph)}</Text>
808 <Text bold wrap="truncate">
809 {fade(p.title)}
810 </Text>
811 <Text color={wordsColor} wrap="truncate">
812 {fade(words)}
813 </Text>
814 <Box flexGrow={1} />
815 <Text color={dim}>{fade(elapsed(p, now))}</Text>
816 <Text>{fade(pctText)}</Text>
817 {close}
818 </Box>
819 <Svg source={lineSvg(p, W, isFading)} alt={alt} width={W} height={LINE_H} isInteractive />
820 </Box>,
821 ...below,
822 ]
823 }
824
825 return (
826 <Box flexDirection="column" gap={1}>
827 {all.flatMap(bar)}
828 </Box>
829 )
830 })
831}
832types/index.d.ts 38 lines1export type StepStatus = 'pending' | 'active' | 'done' | 'error' | 'skipped'
2export type PlanState = 'running' | 'needs_input' | 'paused' | 'error' | 'done'
3export type PlanStep = { title: string; status: StepStatus }
4export type PlanStage = { name: string; steps: PlanStep[] }
5export type AgentRun = {
6 id: string
7 title: string
8 state: 'running' | 'waiting' | 'done' | 'error'
9 tool: string
10 startedAt: number
11 endedAt: number | null
12}
13export type Plan = {
14 id: string
15 title: string
16 stages: PlanStage[]
17 state: PlanState
18 note: string | null
19 startedAt: number
20 doneAt: number | null
21 // set when the main turn ends with the bar unfinished; cleared on the next update
22 pausedAt?: number | null
23 // time spent paused, left out of the elapsed time
24 pausedMs?: number
25 // set on the next prompt after the bar is done; the bar fades out from here
26 fadeAt?: number | null
27 // main turns that ended without an update to this bar; at STALE_TURNS it fades out
28 idleTurns?: number
29 agents: AgentRun[]
30}
31export type TitleState = { last: string | null; isUserOwned: boolean; hasAsked: boolean }
32
33declare module 'claude-code' {
34 interface PluginState {
35 progress: { plans: Plan[]; isOpen: boolean; tick: number; title: TitleState }
36 }
37}
38