SLOPSHOPPER

progress-pulse

A live, colorful progress bar for whatever this session is working on: a band above the prompt, a full /progress pane, and a celebration every time a task lands

panebandguardcommandtoastprompt
v0.3.3no licenseupdated 2026-10-10jgilb17/claude-mods/progress-pulse
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · progress-pulse
│ ┃ Progress ✕ › fix the failing auth test and add an audit log call │ ┃ app progress-pulse 0.3.3 │ ┃ ⏺ Read(src/auth.ts) │ ┃ No task list yet. Progress appears as soon ⎿ Read 6 lines │ ┃ as the session breaks the work into tasks. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /progress │ ⎿ progress-pulse: app: no task list yet. Progress appears once the │ ⎿ progress-pulse: (progress-pulse 0.3.3) │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Progress
app progress-pulse 0.3.3 No task list yet. Progress appears as soon as the session breaks the work into tasks.
README

Joshua's Claude Code mods

Mods that load in every Claude Code session: the terminal, the desktop app's Code tab, and cloud sessions.

ModWhat it shows
repo-sentryBusiness, repo, branch, behind or ahead of origin, dirty count. Warns on work sitting on main, a stale repo, or a staged secret.
progress-pulseA live gradient progress band for the session's task list, a cheer on every finished task, /progress for the full view, /progress demo to see it run.
usage-meterThe 5-hour and weekly plan limits with reset times, context fill and session cost, right above the message box. /usage-meter hides or shows it.

How they load

  • Mac: setup-mac.js (run once) installs every mod as a Claude Code plugin read straight from this folder, and adds a session-start hook that runs sync-mods.js --quiet. A mod added to the marketplace installs itself at the next session start; an edit to a mod takes effect at the next session start or /reload-plugins.
  • Cloud: cloud-setup.sh goes into each cloud environment's setup script. Every new container clones this repo and runs sync-mods.js.

Adding a mod

Put it in its own folder with .claude-plugin/plugin.json, add it to .claude-plugin/marketplace.json, check it with claude plugin validate <folder> and claude plugin test <folder>, commit and push.

Other tools here

mcp-diagnose.js, mcp-where.js, move-mcp-to-repo.js, mcp-set-secret.js, mcp-env-from-dotenv.js: MCP server helpers that never print secret values. servicetrade-mcp/: the read-only ServiceTrade MCP server.

Source 4 files
hooks/register.tsx 581 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Agent, Celebration, Task } from '../types'
5import { bar, counts, duration, eta, fromTodos, gradient, milestonesCrossed, runs, textReport, today, upsert } from './logic'
6import { agentClock, agentsText, agentTasks, BAR_H, botSize, botSvg, pillWords, TRACK_H, compactTokens, currentBatch, expectedSteps, finished, miniBarSvg, PLAN_NOTE, progress, recordSteps, modelName, spawned, stepped, stepText, tier, trackSvg } from './agents'
7
8const tasksA = atom({ plugin: 'progress-pulse', key: 'tasks' } as const, [] as Task[])
9const startA = atom({ plugin: 'progress-pulse', key: 'sessionStart' } as const, 0)
10const cheerA = atom({ plugin: 'progress-pulse', key: 'celebration' } as const, null as Celebration | null)
11const projectA = atom({ plugin: 'progress-pulse', key: 'project' } as const, '')
12const hiddenA = atom({ plugin: 'progress-pulse', key: 'bandHidden' } as const, false)
13const agentsA = atom({ plugin: 'progress-pulse', key: 'agents' } as const, [] as Agent[])
14const paneOpenedA = atom({ plugin: 'progress-pulse', key: 'paneOpened' } as const, false)
15
16const usageTokens = (u: { input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number } | undefined) =>
17  // Cache reads are left out: every request of a subagent re-reads its whole cached prompt, so
18  // counting them made three 9-second Haiku agents read as 1.3M tokens in the 0.2.0 pane.
19  u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : 0
20
21const PANE = 'progress-pulse'
22// Shown in the pane header and the /progress reply, so which version is running is never a guess.
23// Bump together with .claude-plugin/plugin.json; the version test pins both.
24export const VERSION = '0.3.3'
25const CHEER_MS = 8000
26const QUIET_AFTER_DONE_MS = 15 * 60_000
27
28async function projectName($: EngineInterface): Promise<string> {
29  try {
30    const r = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 3000 })
31    if (r.exitCode === 0) return r.stdout.trim().split('/').filter(Boolean).pop() ?? ''
32  } catch { /* not a repo, or git missing */ }
33  const cwd = await $.session.cwd()
34  return cwd.split('/').filter(Boolean).pop() ?? 'this session'
35}
36
37// Everything that happens when the task list changes: store it, and cheer what just finished.
38async function apply($: EngineInterface, change: (prev: Task[], now: number) => Task[]): Promise<void> {
39  const now = await $.clock.now()
40  const stored = await read($, tasksA)
41  const isDemo = (t: Task) => t.id.startsWith('demo-')
42  const before = stored
43  let after = change(before, now)
44  if (after.some(t => !isDemo(t)) && after.some(isDemo)) after = after.filter(t => !isDemo(t))
45  await update($, tasksA, () => after)
46
47  const was = new Set(before.filter(t => t.status === 'completed').map(t => t.id))
48  const landed = after.filter(t => t.status === 'completed' && !was.has(t.id))
49  if (!landed.length) return
50
51  const b = counts(before), a = counts(after)
52  const all = a.total > 0 && a.done === a.total
53  const last = landed[landed.length - 1]!
54  const startedAt = await read($, startA)
55  const text = all
56    ? `ALL ${a.total} DONE in ${duration(now - (startedAt || now))}. Shipped.`
57    : `Done: ${last.subject}   ${a.done} of ${a.total}`
58  await update($, cheerA, () => ({ text, big: all, until: now + CHEER_MS }))
59  $.clock.after(CHEER_MS + 50, () => {
60    void (async () => {
61      const t = await $.clock.now()
62      await update($, cheerA, c => (c && c.until <= t ? null : c))
63    })().catch(() => {})
64  })
65
66  for (const m of milestonesCrossed(b.total ? b.pct : 0, a.pct)) {
67    if (m < 100) $.ui.toast(`${m}% of the way there: ${a.done} of ${a.total} done`)
68  }
69  if (all) $.ui.toast(`Every task done: ${a.total} of ${a.total}. Nice work.`, { timeoutMs: 8000 })
70  if (!landed.every(isDemo)) await postFeed($, all ? 'all tasks done' : `done: ${last.subject.slice(0, 50)}`)
71
72  // A running tally per project per day, kept across sessions, for the pane's Today section.
73  if (landed.every(isDemo)) return
74  try {
75    const project = (await read($, projectA)) || 'this session'
76    const key = `day:${today(now)}`
77    const tally = ((await $.store.get(key)) ?? {}) as Record<string, number>
78    tally[project] = (tally[project] ?? 0) + landed.filter(t => !isDemo(t)).length
79    await $.store.set(key, tally)
80  } catch { /* the tally is a nicety; never let it break a tool call */ }
81}
82
83// The feed: sessions running in a cloud container (CLAUDE_CODE_REMOTE=true) are shown in the app
84// without mod bands or panes, so there progress is posted as short notice lines in the transcript
85// instead, automatically, at each real milestone. The model never reads these lines.
86let isRemote = false
87let lastFeed = ''
88async function feedMode($: EngineInterface): Promise<'auto' | 'on' | 'off'> {
89  try { return ((await $.store.get('feed')) as 'auto' | 'on' | 'off' | undefined) ?? 'auto' } catch { return 'auto' }
90}
91export function feedText(tasks: Task[], crew: Agent[], history: Record<string, number[]>, project: string, event: string, now = 0): string {
92  const c = counts(tasks)
93  const crewDone = crew.filter(a => a.status !== 'running').length
94  const units = tasks.length + crew.length
95  const pct = Math.round(((c.done + crewDone) / Math.max(1, units)) * 100)
96  const cells = Math.round(pct / 10)
97  const parts = [`${'▓'.repeat(cells)}${'░'.repeat(10 - cells)} ${pct}%`]
98  if (tasks.length) parts.push(`tasks ${c.done}/${c.total}`)
99  if (crew.length) parts.push(`agents ${crewDone}/${crew.length} done`)
100  const lines = [`${project || 'session'}  ${parts.join('  ·  ')}  ·  ${event}`]
101  for (const a of crew.filter(x => x.status === 'running').slice(0, 4)) {
102    lines.push(`   ● ${a.name.slice(0, 40)}  ${progress(a, expectedSteps(history, a.type), now).label.split(' · ')[0]}`)
103  }
104  return lines.join('\n')
105}
106async function postFeed($: EngineInterface, event: string): Promise<void> {
107  try {
108    const mode = await feedMode($)
109    if (mode === 'off' || (mode === 'auto' && !isRemote)) return
110    const tasks = await read($, tasksA)
111    const crew = currentBatch(await read($, agentsA))
112    if (!tasks.length && !crew.length) return
113    let history: Record<string, number[]> = {}
114    try { history = ((await $.store.get('stepHistory')) ?? {}) as Record<string, number[]> } catch { /* none yet */ }
115    const text = feedText(tasks, crew, history, await read($, projectA), event, await $.clock.now())
116    if (text === lastFeed) return
117    lastFeed = text
118    await $.session.append({ message: { type: 'system', content: [{ type: 'text', text }] } })
119  } catch { /* the feed must never break the work it reports on */ }
120}
121
122// The Agents section: what the crew cost and how far each one has got.
123// eslint-disable-next-line @typescript-eslint/no-explicit-any
124type El = any
125async function crewSection($: EngineInterface, els: { Box: El; Text: El; Svg: El | null }, crew: Agent[], tasks: Task[], now: number) {
126  const { Box, Text, Svg } = els
127  let usd: number | null = null
128  try { const u = await $.session.usage(); usd = u.cost ? u.cost.usd : null } catch { /* no ledger on this host */ }
129  let history: Record<string, number[]> = {}
130  try { history = ((await $.store.get('stepHistory')) ?? {}) as Record<string, number[]> } catch { /* no history yet */ }
131  const tokens = crew.reduce((x, a) => x + a.tokens, 0)
132  const first = Math.min(...crew.map(a => a.startedAt))
133  const last = crew.some(a => a.status === 'running') ? now : Math.max(...crew.map(a => a.endedAt ?? now))
134  const running = crew.filter(a => a.status === 'running')
135  const ended = crew.filter(a => a.status !== 'running')
136  const planned = tasks.filter(t => t.status === 'pending')
137
138  const tile = (label: string, value: string, note: string) => (
139    <Box key={label} flexDirection="column" borderStyle="round" paddingX={1} flexGrow={1}>
140      <Text dimColor>{label}</Text>
141      <Text bold>{value}</Text>
142      <Text dimColor>{note}</Text>
143    </Box>
144  )
145  const row = (a: Agent) => {
146    const t = tier(a.model, a.type)
147    const live = a.status === 'running'
148    const p = progress(a, expectedSteps(history, a.type), now)
149    const pctColor = p.kind === 'est' ? undefined : t.color
150    const mark = a.status === 'done' ? <Text color="#2ec27e">{'✓'}</Text> : a.status === 'failed' ? <Text color="#e5484d">{'✕'}</Text> : <Text color={t.color}>{'●'}</Text>
151    return (
152      <Box key={a.id} flexDirection="row" columnGap={1} alignItems="center" marginBottom={1}>
153        {Svg ? <Svg source={botSvg(t.color, { cell: 3, bounce: live })} alt={`${t.label} agent`} {...botSize(3)} /> : null}
154        <Box flexDirection="column" flexGrow={1}>
155          <Text>
156            <Text bold>{a.name.slice(0, 40)}</Text>
157            <Text color={t.color}>{'  ' + t.label}</Text>
158            <Text dimColor>{`  ${modelName(a.model)} · ${a.type}`}</Text>
159          </Text>
160          <Text dimColor={!live}>{live ? a.stepLabel : a.status === 'done' ? 'Finished' : 'Stopped before finishing'}</Text>
161          {Svg
162            ? <Box flexDirection="row" columnGap={1} alignItems="center">
163                <Svg source={miniBarSvg(p.frac, a.status === 'failed' ? '#e5484d' : a.status === 'done' ? '#2ec27e' : t.color, 220, p.kind)} alt={p.label} width={220} height={BAR_H} />
164                <Text bold={p.kind !== 'est'} dimColor={p.kind === 'est'} color={pctColor}>{p.kind === 'done' ? '100%' : p.label.split(' · ')[0]}</Text>
165              </Box>
166            : <Text color={pctColor} dimColor={p.kind === 'est'}>{`${'█'.repeat(Math.round(p.frac * 20))}${'░'.repeat(20 - Math.round(p.frac * 20))} ${p.label}`}</Text>}
167          {live && p.label.includes(' · ') ? <Text dimColor>{p.label.split(' · ').slice(1).join(' · ')}</Text> : null}
168          <Text dimColor>{`${a.tokens ? compactTokens(a.tokens) + ' tokens · ' : ''}${agentClock((a.endedAt ?? now) - a.startedAt)}`}</Text>
169        </Box>
170        {mark}
171      </Box>
172    )
173  }
174  return (
175    <Box flexDirection="column">
176      <Text bold>{`Agents  ${ended.length} of ${crew.length} finished`}</Text>
177      <Box flexDirection="row" columnGap={1}>
178        {tile('Cost', usd !== null ? `$${usd.toFixed(2)}` : 'n/a', 'whole session, API rates')}
179        {tile('Tokens', compactTokens(tokens), 'agents, excl. cache reads')}
180        {tile('Time', agentClock(last - first), 'this crew')}
181      </Box>
182      <Text> </Text>
183      {running.length ? <Text bold color="#8b7cf6">{`Running · ${running.length}`}</Text> : null}
184      {running.map(row)}
185      {ended.length ? <Text bold color="#2ec27e">{`Finished · ${ended.length}`}</Text> : null}
186      {ended.map(row)}
187      {planned.length ? <Text bold dimColor>{`Planned · ${planned.length}`}</Text> : null}
188      {planned.slice(0, 6).map(t => <Text key={t.id} dimColor>{'◷ ' + t.subject}</Text>)}
189      <Text> </Text>
190    </Box>
191  )
192}
193
194export const register: Register = on => {
195  on('session.start', async ($, e, next) => {
196    const r = await next(e)
197    if (!(await read($, startA))) {
198      const now = await $.clock.now()
199      await update($, startA, () => now)
200    }
201    const name = await projectName($)
202    await update($, projectA, () => name)
203    await $.command.register({ name: 'progress', description: 'Show live progress on what this session is working on' })
204    try { isRemote = ((await $.process.run(['printenv', 'CLAUDE_CODE_REMOTE'], { timeoutMs: 2000 })).stdout || '').trim() === 'true' } catch { isRemote = false }
205    return r
206  })
207
208  on('command.run', { command: 'progress' }, async ($, e) => {
209    await update($, hiddenA, () => false)
210    const feedArg = e.args.trim().match(/^feed (on|off|auto)$/)
211    if (feedArg) {
212      await $.store.set('feed', feedArg[1])
213      return { text: `Progress lines in the transcript: ${feedArg[1]}${feedArg[1] === 'auto' ? ' (cloud sessions only)' : ''}.` }
214    }
215    const plansArg = e.args.trim().match(/^plans (on|off)$/)
216    if (plansArg) {
217      await $.store.set('agentPlans', plansArg[1] === 'on')
218      return { text: plansArg[1] === 'on' ? 'Subagents will be asked to keep a short checklist, so their bars show measured progress.' : 'Subagents will no longer be asked for a checklist; their bars fall back to estimates.' }
219    }
220    if (e.args.trim() === 'demo') {
221      // A 12-second show of what a session looks like as it works through a list. Demo tasks
222      // carry a demo- id, are never tallied, and vanish the moment a real task arrives.
223      const steps = ['Read the brief', 'Pull the live numbers', 'Build the change', 'Run the test suite', 'Check it on real data', 'Ship it']
224      await apply($, (_prev, now) => steps.reduce((ts, s, i) => upsert(ts, `demo-${i}`, { subject: s }, now), [] as Task[]))
225      let i = 0
226      const tick = $.clock.every(1000, () => {
227        const k = Math.floor(i / 2), starting = i % 2 === 0
228        i++
229        if (k >= steps.length) { tick.cancel(); return }
230        void apply($, (prev, now) => upsert(prev, `demo-${k}`, starting
231          ? { status: 'in_progress', activeForm: steps[k] + '...' }
232          : { status: 'completed' }, now)).catch(() => {})
233      })
234      return { text: 'Running a 12 second demo in the band above the prompt.' }
235    }
236    try { await $.ui.open({ id: PANE, title: 'Progress' }) } catch { /* a screen with no panes: the text below still answers */ }
237    // Also answer in text: sessions whose screen does not draw mod bands or panes (a cloud
238    // session viewed from the app) still get the picture as a transcript line.
239    const tasks = await read($, tasksA)
240    const now = await $.clock.now()
241    const started = await read($, startA)
242    const crewText = agentsText(currentBatch(await read($, agentsA)), now)
243    const report = textReport(tasks, (await read($, projectA)) || 'this session', now - (started || now))
244    return { text: (tasks.length || !crewText ? report + (crewText ? '\n' + crewText : '') : crewText) + `\n(progress-pulse ${VERSION})` }
245  })
246
247  // The session's own task list is the source of truth: every TaskCreate, TaskUpdate and
248  // TodoWrite the model makes passes through here, and only a call that succeeded is counted.
249  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
250    const r = await next(e)
251    const id = r.deny === undefined && !r.isError ? r.result?.task?.id : undefined
252    if (id && e.agentId) await update($, agentsA, l => agentTasks(l, String(e.agentId), { created: 1 }))
253    else if (id) await apply($, (prev, now) => upsert(prev, String(id), { subject: e.subject, activeForm: e.activeForm ?? null }, now))
254    return r
255  }).catch(($, e, next) => next(e))
256
257  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
258    const r = await next(e)
259    if (r.deny !== undefined || r.isError || r.result?.success === false) return r
260    if (e.agentId) {
261      if (e.status === 'completed') await update($, agentsA, l => agentTasks(l, String(e.agentId), { completed: 1 }))
262      return r
263    }
264    const id = String(e.taskId)
265    if (e.status === 'deleted') {
266      await apply($, prev => prev.filter(t => t.id !== id))
267    } else {
268      await apply($, (prev, now) => upsert(prev, id, {
269        ...(e.subject ? { subject: e.subject } : {}),
270        ...(e.activeForm ? { activeForm: e.activeForm } : {}),
271        ...(e.status && e.status !== 'deleted' ? { status: e.status } : {}),
272      }, now))
273    }
274    return r
275  }).catch(($, e, next) => next(e))
276
277  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
278    const r = await next(e)
279    if (r.deny === undefined && !r.isError && e.agentId) {
280      await update($, agentsA, l => agentTasks(l, String(e.agentId), { total: e.todos.length, done: e.todos.filter(t => t.status === 'completed').length }))
281    } else if (r.deny === undefined && !r.isError) await apply($, (prev, now) => fromTodos(prev, e.todos, now))
282    return r
283  }).catch(($, e, next) => next(e))
284
285  // The crew: every subagent the session starts (Agent tool, workflows, forks) gets a card.
286  on('agent.spawn', async ($, e, next) => {
287    let plans = true
288    try { plans = (await $.store.get('agentPlans')) !== false } catch { /* default on */ }
289    const r = await next(plans && e.subagentType !== 'fork' && !e.prompt.includes('Progress tracking:') ? { ...e, prompt: e.prompt + PLAN_NOTE } : e)
290    if (r.deny === undefined && r.agentId) {
291      const now = await $.clock.now()
292      await update($, agentsA, l => spawned(l, { id: r.agentId!, name: e.description || e.subagentType, type: e.subagentType, model: r.model || e.model || e.parentModel, background: e.background }, now))
293      if (!(await read($, paneOpenedA))) {
294        await update($, paneOpenedA, () => true)
295        try { await $.ui.open({ id: PANE, title: 'Progress' }) } catch { /* a screen with no panes */ }
296      }
297      await postFeed($, `agent started: ${(e.description || e.subagentType).slice(0, 50)}`)
298    }
299    return r
300  }).catch(($, e, next) => next(e))
301
302  // Each tool call an agent makes moves its card: a step counted and a few words on what it is doing.
303  on('tool.call', async ($, e, next) => {
304    const r = await next(e)
305    if (e.agentId) {
306      const label = stepText(e.tool, e as unknown as Record<string, unknown>)
307      await update($, agentsA, l => stepped(l, String(e.agentId), label))
308    } else if (e.tool === 'Bash' && r.deny === undefined) {
309      // A Codex worker started as a background command: it gets a card like any agent.
310      const bg = (r as { result?: { backgroundTaskId?: string } }).result?.backgroundTaskId
311      const cmd = String((e as { command?: string }).command ?? '')
312      if (bg && /\bcodex\b|codex-companion/i.test(cmd)) {
313        const now = await $.clock.now()
314        const name = String((e as { description?: string }).description || 'Codex worker')
315        await update($, agentsA, l => stepped(spawned(l, { id: `bg:${bg}`, name, type: 'codex', model: 'codex', background: true }, now), `bg:${bg}`, 'Working in its own worktree'))
316        if (!(await read($, paneOpenedA))) {
317          await update($, paneOpenedA, () => true)
318          try { await $.ui.open({ id: PANE, title: 'Progress' }) } catch { /* a screen with no panes */ }
319        }
320        await postFeed($, `codex worker started: ${name.slice(0, 50)}`)
321      }
322    }
323    return r
324  }).catch(($, e, next) => next(e))
325
326  // A background task finishing arrives as a notification prompt naming its task id.
327  on('prompt.submit', async ($, e, next) => {
328    try {
329      if ((e as { origin?: { kind?: string } }).origin?.kind === 'task-notification') {
330        const text = String(e.text ?? '')
331        const running = (await read($, agentsA)).filter(a => a.status === 'running' && a.id.startsWith('bg:') && text.includes(a.id.slice(3)))
332        if (running.length) {
333          const now = await $.clock.now()
334          const status = (text.match(/<status>\s*([a-z_]+)/i)?.[1] ?? (/\b(failed|killed|error)\b/i.test(text) ? 'failed' : 'completed')).toLowerCase()
335          const ok = status === 'completed' || status === 'success'
336          for (const a of running) {
337            await update($, agentsA, l => finished(l, a.id, ok, 0, now))
338            if (ok) {
339              try {
340                const h = ((await $.store.get('stepHistory')) ?? {}) as Record<string, number[]>
341                await $.store.set('stepHistory', recordSteps(h, 'codexMinutes', Math.max(1, Math.round((now - a.startedAt) / 60000))))
342              } catch { /* history is a nicety */ }
343            }
344            await postFeed($, `codex worker ${ok ? 'finished' : 'stopped'}: ${a.name.slice(0, 50)}`)
345          }
346        }
347      }
348    } catch { /* never block a prompt over a progress card */ }
349    return next(e)
350  }).catch(($, e, next) => next(e))
351
352  // An agent's turn ending is the agent finishing: its tokens are what the API reported for it.
353  on('turn.complete', async ($, e, next) => {
354    const r = await next(e)
355    if (e.agentId) {
356      const now = await $.clock.now()
357      const ok = e.reason === 'answer'
358      await update($, agentsA, l => finished(l, String(e.agentId), ok, usageTokens(e.usage), now))
359      if (ok) {
360        try {
361          const a = (await read($, agentsA)).find(x => x.id === String(e.agentId))
362          if (a && a.steps > 0) await $.store.set('stepHistory', recordSteps(((await $.store.get('stepHistory')) ?? {}) as Record<string, number[]>, a.type, a.steps))
363        } catch { /* history is a nicety */ }
364      }
365      const fin = (await read($, agentsA)).find(x => x.id === String(e.agentId))
366      await postFeed($, `agent ${ok ? 'finished' : 'stopped'}: ${(fin?.name ?? 'agent').slice(0, 50)}`)
367      const batch = currentBatch(await read($, agentsA))
368      if (batch.length > 1 && batch.every(a => a.status !== 'running')) {
369        $.ui.toast(`Crew finished: ${batch.filter(a => a.status === 'done').length} of ${batch.length} agents done.`, { timeoutMs: 6000 })
370      }
371    }
372    return r
373  }).catch(($, e, next) => next(e))
374
375  // The band above the prompt: one glance, always there while there is work on the list.
376  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
377    const below = await next(e)
378    const tasks = await read($, tasksA)
379    const crew = currentBatch(await read($, agentsA))
380    if (e.props.hasSurvey || (!tasks.length && !crew.length) || (await read($, hiddenA))) return below
381    const now = await $.clock.now()
382    const c = counts(tasks)
383    const crewDone = crew.filter(a => a.status !== 'running').length
384    const lastDone = Math.max(0, ...tasks.map(t => t.doneAt ?? 0), ...crew.map(a => a.endedAt ?? 0))
385    const cheer = await read($, cheerA)
386    const cheering = cheer && cheer.until > now
387    const allDone = (tasks.length ? c.done === c.total : true) && crewDone === crew.length
388    if (allDone && now - lastDone > QUIET_AFTER_DONE_MS && !cheering) return below
389
390    const { Box, Text, Button } = $.ui.resolve(e)
391    const project = await read($, projectA)
392    const started = await read($, startA)
393
394    // Screens that draw vectors (the desktop app, VS Code, mobile): the animated pixel track,
395    // a pill riding its leading edge, and the crew count beside a bobbing bot.
396    if (e.surface !== 'terminal') {
397      const { Svg } = $.ui.resolve(e) as unknown as { Svg: El }
398      // Tasks and agents count together, so a crew still running never shows as 100%.
399      const crewRunning = crew.some(a => a.status === 'running')
400      const units = tasks.length + crew.length, unitsDone = c.done + crewDone
401      const pct = Math.round((unitsDone / Math.max(1, units)) * 100)
402      const done = pct >= 100 && allDone
403      const active = tasks.find(t => t.status === 'in_progress')
404      const word = active ? pillWords(active.activeForm || active.subject) : crewRunning ? 'Agents' : 'Next up'
405      const count = active || !crewRunning ? `${c.done}/${c.total}` : `${crewDone}/${crew.length}`
406      const label = done ? 'Done' : `${word} ${count}`
407      const title = (project || 'This session').slice(0, 28)
408      const dot = done ? '#2ec27e' : '#8b7cf6'
409      const running = crewRunning
410      const crewHat = (crew.find(a => a.status === 'running') ?? crew[crew.length - 1])
411      return (
412        <Box flexDirection="column">
413          <Box flexDirection="row" alignItems="center" columnGap={1}>
414            <Text color={dot}>{'●'}</Text>
415            <Text bold>{title}</Text>
416            <Svg source={trackSvg(pct, label, done ? 'done' : 'running', 300)} alt={`${title}: ${pct}% (${label})`} width={300} height={TRACK_H} />
417            <Text bold>{`${pct}%`}</Text>
418            {crew.length
419              ? <Box flexDirection="row" alignItems="center" columnGap={1}>
420                  <Svg source={botSvg(done || !crewHat ? '#2ec27e' : tier(crewHat.model, crewHat.type).color, { cell: 2.4, bounce: running })} alt="crew" {...botSize(2.4)} />
421                  <Text>{`×${crew.length}`}</Text>
422                </Box>
423              : null}
424            <Button key="hide" plain label="✕" onPress={() => update($, hiddenA, () => true)} />
425          </Box>
426          {cheering
427            ? <Text bold color={cheer!.big ? '#2ec27e' : 'success'}>{(cheer!.big ? '★ ' : '✦ ') + cheer!.text}</Text>
428            : active
429              ? <Text wrap="truncate-end">
430                  <Text color={dot}>{'▶ '}</Text>
431                  <Text>{active.activeForm || active.subject}</Text>
432                  <Text dimColor>{(tasks.find(t => t.status === 'pending') ? '   next: ' + tasks.find(t => t.status === 'pending')!.subject : '') + (tasks.length ? `   ${c.done} of ${c.total}` : '')}</Text>
433                </Text>
434              : null}
435          {below}
436        </Box>
437      )
438    }
439
440    if (!tasks.length) {
441      return (
442        <Box flexDirection="column">
443          <Text>
444            <Text bold color="#8b7cf6">{'◆ '}</Text>
445            <Text bold>{(project || 'session') + ' '}</Text>
446            <Text>{`agents ${crewDone}/${crew.length} done`}</Text>
447            <Text dimColor>{'  ·  ' + crew.filter(a => a.status === 'running').map(a => a.name).slice(0, 2).join(', ')}</Text>
448          </Text>
449          {below}
450        </Box>
451      )
452    }
453    // Size the bar to what is left of the line after the fixed text, so the band never wraps,
454    // including when the /progress pane is docked beside the transcript and narrows it.
455    const name = (project || 'session').slice(0, 24)
456    const tail = ` ${c.pct}%  ${c.done} of ${c.total} · ${duration(now - (started || now))}`
457    const width = Math.max(6, Math.min(40, e.props.bodyColumns - (2 + name.length + 1) - tail.length - 7))
458    const active = tasks.find(t => t.status === 'in_progress')
459    const upNext = tasks.find(t => t.status === 'pending')
460
461    return (
462      <Box flexDirection="column">
463        <Box flexDirection="row" flexWrap="nowrap">
464          <Text wrap="truncate-end">
465            <Text bold color={gradient(c.pct / 100)}>{'◆ '}</Text>
466            <Text bold>{name + ' '}</Text>
467            {runs(bar(c, width)).map(r => (r.color ? <Text color={r.color}>{r.text}</Text> : <Text dimColor>{r.text}</Text>))}
468            <Text bold color={gradient(c.pct / 100)}>{` ${c.pct}%`}</Text>
469            <Text dimColor>{`  ${c.done} of ${c.total} · ${duration(now - (started || now))}`}</Text>
470          </Text>
471          <Box marginLeft={2}>
472            <Button key="hide" plain label="hide" onPress={() => update($, hiddenA, () => true)} />
473          </Box>
474        </Box>
475        {cheering
476          ? <Text bold color={cheer!.big ? '#2ed573' : 'success'}>{(cheer!.big ? '★ ★ ★  ' : '✦  ') + cheer!.text + (cheer!.big ? '  ★ ★ ★' : '  ✦')}</Text>
477          : active
478            ? <Text>
479                <Text color={gradient(c.pct / 100)}>{'▶ '}</Text>
480                <Text>{active.activeForm || active.subject}</Text>
481                {upNext ? <Text dimColor>{'   next: ' + upNext.subject}</Text> : null}
482              </Text>
483            : upNext ? <Text dimColor>{'○ up next: ' + upNext.subject}</Text> : null}
484        {below}
485      </Box>
486    )
487  })
488
489  // The full view: /progress opens it.
490  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
491    const { Box, Text } = $.ui.resolve(e)
492    const tasks = await read($, tasksA)
493    const project = await read($, projectA)
494    const started = await read($, startA)
495    const now = await $.clock.now()
496    const c = counts(tasks)
497    const cols = e.props.bodyColumns
498    const width = Math.max(10, Math.min(60, cols - 4))
499    const big = runs(bar(c, width))
500    const left = eta(tasks)
501    const doneTimes = tasks.filter(t => t.status === 'completed' && t.doneAt).map(t => (t.doneAt as number) - (t.startedAt ?? t.createdAt))
502    const avg = doneTimes.length ? doneTimes.reduce((x, y) => x + y, 0) / doneTimes.length : null
503
504    let tally: Record<string, number> = {}
505    try { tally = ((await $.store.get(`day:${today(now)}`)) ?? {}) as Record<string, number> } catch { /* empty */ }
506    const most = Math.max(1, ...Object.values(tally))
507    const barRow = (key: string) => (
508      <Box key={key} flexDirection="row">
509        {big.map(r => (r.color ? <Text color={r.color}>{r.text}</Text> : <Text dimColor>{r.text}</Text>))}
510      </Box>
511    )
512
513    const crew = currentBatch(await read($, agentsA))
514    const PaneSvg = e.surface !== 'terminal' ? ($.ui.resolve(e) as unknown as { Svg: El }).Svg : null
515    const crewView = crew.length ? await crewSection($, { Box, Text, Svg: PaneSvg }, crew, tasks, now) : null
516    // The task list's own bar: the band's dotted track where vectors draw. The block-character bar
517    // is for the terminal; on the desktop it wrapped into four green stripes nobody could read.
518    const taskBar = PaneSvg
519      ? <PaneSvg source={trackSvg(c.pct, c.done === c.total ? 'Done' : `${c.done}/${c.total}`, c.done === c.total ? 'done' : 'running', 300)} alt={`Tasks ${c.pct}%`} width={300} height={TRACK_H} />
520      : <Box flexDirection="column">{barRow('b1')}{barRow('b2')}</Box>
521
522    return (
523      <Box flexDirection="column">
524        <Text>
525          <Text bold>{`${project || 'This session'}`}</Text>
526          <Text dimColor>{`   progress-pulse ${VERSION}`}</Text>
527        </Text>
528        <Text> </Text>
529        {crewView}
530        {crewView ? <Text bold>Session tasks</Text> : null}
531        {tasks.length === 0 && crew.length ? <Text dimColor>No task list in the main session yet.</Text> : tasks.length === 0
532          ? <Text dimColor>No task list yet. Progress appears as soon as the session breaks the work into tasks.</Text>
533          : <Box flexDirection="column">
534              {taskBar}
535              <Text> </Text>
536              <Text>
537                <Text bold color={gradient(c.pct / 100)}>{`${c.pct}%`}</Text>
538                <Text>{`  ${c.done} of ${c.total} done`}</Text>
539                <Text dimColor>{c.active ? `  ·  ${c.active} in progress` : ''}</Text>
540              </Text>
541              <Text> </Text>
542              {tasks.map(t => {
543                const took = t.status === 'completed' && t.doneAt ? duration(t.doneAt - (t.startedAt ?? t.createdAt))
544                  : t.status === 'in_progress' && t.startedAt ? `${duration(now - t.startedAt)} so far` : ''
545                return t.status === 'completed'
546                  ? <Text><Text color="#2ed573">{'✓ '}</Text><Text dimColor>{t.subject}</Text><Text dimColor>{took ? `  ${took}` : ''}</Text></Text>
547                  : t.status === 'in_progress'
548                    ? <Text><Text bold color={gradient(c.pct / 100)}>{'▶ '}</Text><Text bold>{t.activeForm || t.subject}</Text><Text dimColor>{took ? `  ${took}` : ''}</Text></Text>
549                    : <Text dimColor>{'○ ' + t.subject}</Text>
550              })}
551              <Text> </Text>
552              <Text dimColor>
553                {`Elapsed ${duration(now - (started || now))}`}
554                {avg !== null ? `  ·  ${duration(avg)} per task (measured)` : ''}
555                {left !== null && left > 0 ? `  ·  about ${duration(left)} left (estimate from that average)` : ''}
556              </Text>
557            </Box>}
558        {Object.keys(tally).length
559          ? <Box flexDirection="column">
560              <Text> </Text>
561              <Text bold>Today across projects</Text>
562              {Object.entries(tally).sort((x, y) => y[1] - x[1]).map(([name, n], i) => (
563                PaneSvg
564                  ? <Box key={name} flexDirection="row" columnGap={1} alignItems="center">
565                      <Text>{name.slice(0, 22)}</Text>
566                      <PaneSvg source={miniBarSvg(n / most, gradient(n / most), 160)} alt={`${name}: ${n} done`} width={160} height={BAR_H} />
567                      <Text bold>{`${n}`}</Text>
568                    </Box>
569                  : <Text>
570                      <Text>{name.padEnd(22).slice(0, 22)}</Text>
571                      <Text color={gradient(n / most)}>{'█'.repeat(Math.max(1, Math.round((n / most) * 24)))}</Text>
572                      <Text bold>{`  ${n}`}</Text>
573                    </Text>
574              ))}
575            </Box>
576          : null}
577      </Box>
578    )
579  })
580}
581
hooks/logic.ts 122 lines
1import type { Task, TaskStatus } from '../types'
2
3// Orange to gold to green as the bar fills. At 100% the whole bar turns green.
4const STOPS: [number, number, number][] = [[0xff, 0x6b, 0x35], [0xff, 0xc1, 0x4d], [0x2e, 0xd5, 0x73]]
5const hex = (r: number, g: number, b: number) =>
6  '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('')
7
8export function gradient(t: number): string {
9  const x = Math.min(1, Math.max(0, t)) * (STOPS.length - 1)
10  const i = Math.min(STOPS.length - 2, Math.floor(x))
11  const f = x - i
12  const a = STOPS[i]!, b = STOPS[i + 1]!
13  return hex(a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f)
14}
15
16export type Counts = { total: number; done: number; active: number; pending: number; pct: number }
17
18export function counts(tasks: Task[]): Counts {
19  const total = tasks.length
20  const done = tasks.filter(t => t.status === 'completed').length
21  const active = tasks.filter(t => t.status === 'in_progress').length
22  return { total, done, active, pending: total - done - active, pct: total ? Math.round((done / total) * 100) : 0 }
23}
24
25// One cell per entry: filled cells carry their gradient color; an in-progress task shows as a
26// half-lit cell after the filled run so the bar visibly moves as work starts, not only as it ends.
27export type Cell = { ch: string; color: string | null }
28
29export function bar(c: Counts, width: number): Cell[] {
30  const w = Math.max(4, width)
31  const filled = c.total ? Math.round((c.done / c.total) * w) : 0
32  const activeCells = c.total && c.active ? Math.max(1, Math.round((c.active / c.total) * w)) : 0
33  const cells: Cell[] = []
34  for (let i = 0; i < w; i++) {
35    if (i < filled) cells.push({ ch: '█', color: c.done === c.total ? '#2ed573' : gradient(i / Math.max(1, w - 1)) })
36    else if (i < filled + activeCells) cells.push({ ch: '▓', color: gradient(i / Math.max(1, w - 1)) })
37    else cells.push({ ch: '░', color: null })
38  }
39  return cells
40}
41
42// Collapse runs of the same color so a 40-cell bar is a handful of Text elements, not 40.
43export function runs(cells: Cell[]): { text: string; color: string | null }[] {
44  const out: { text: string; color: string | null }[] = []
45  for (const cell of cells) {
46    const last = out[out.length - 1]
47    if (last && last.color === cell.color) last.text += cell.ch
48    else out.push({ text: cell.ch, color: cell.color })
49  }
50  return out
51}
52
53export function duration(ms: number): string {
54  const s = Math.max(0, Math.round(ms / 1000))
55  if (s < 60) return `${s}s`
56  const m = Math.round(s / 60)
57  if (m < 60) return `${m}m`
58  return `${Math.floor(m / 60)}h ${m % 60}m`
59}
60
61// Estimate of time left: the average of the measured durations of tasks finished this session,
62// times what is left. Labelled an estimate wherever it is shown; null until two tasks have
63// finished with a measured duration, because one sample is not an average.
64export function eta(tasks: Task[]): number | null {
65  const measured = tasks
66    .filter(t => t.status === 'completed' && t.doneAt !== null && (t.startedAt ?? t.createdAt) !== null)
67    .map(t => (t.doneAt as number) - (t.startedAt ?? t.createdAt))
68    .filter(ms => ms > 0)
69  if (measured.length < 2) return null
70  const avg = measured.reduce((a, b) => a + b, 0) / measured.length
71  const left = tasks.filter(t => t.status !== 'completed').length
72  return left ? avg * left : 0
73}
74
75// The quarter marks a run of completions crossed, so each gets one cheer and only one.
76export function milestonesCrossed(before: number, after: number): number[] {
77  return [25, 50, 75, 100].filter(m => before < m && after >= m)
78}
79
80export function upsert(tasks: Task[], id: string, patch: Partial<Task> & { subject?: string }, now: number): Task[] {
81  const i = tasks.findIndex(t => t.id === id)
82  if (i === -1) {
83    return [...tasks, {
84      id, subject: patch.subject ?? `Task ${id}`, activeForm: patch.activeForm ?? null,
85      status: (patch.status as TaskStatus) ?? 'pending', createdAt: now,
86      startedAt: patch.status === 'in_progress' ? now : null, doneAt: patch.status === 'completed' ? now : null,
87    }]
88  }
89  const prev = tasks[i]!
90  const next: Task = { ...prev, ...patch }
91  if (patch.status === 'in_progress' && prev.status !== 'in_progress') next.startedAt = now
92  if (patch.status === 'completed' && prev.status !== 'completed') next.doneAt = now
93  if (patch.status && patch.status !== 'completed') next.doneAt = null
94  return tasks.map((t, j) => (j === i ? next : t))
95}
96
97// TodoWrite hands over the whole list every time. Match by content so a task keeps its timings
98// across rewrites; anything not in the new list is gone.
99export function fromTodos(prev: Task[], todos: { content: string; status: TaskStatus; activeForm?: string }[], now: number): Task[] {
100  return todos.map((todo, i) => {
101    const old = prev.find(t => t.subject === todo.content)
102    const base: Task = old ?? { id: `todo-${i}-${todo.content.slice(0, 24)}`, subject: todo.content, activeForm: todo.activeForm ?? null, status: 'pending', createdAt: now, startedAt: null, doneAt: null }
103    return upsert([base], base.id, { status: todo.status, activeForm: todo.activeForm ?? base.activeForm }, now)[0]!
104  })
105}
106
107export const today = (now: number) => new Date(now).toISOString().slice(0, 10)
108
109// The whole picture as plain text, for a screen that draws no bands or panes.
110export function textReport(tasks: Task[], project: string, elapsedMs: number): string {
111  if (!tasks.length) return `${project}: no task list yet. Progress appears once the session breaks the work into tasks.`
112  const c = counts(tasks)
113  const cells = bar(c, 20).map(x => x.ch).join('')
114  const lines = [`${project}  ${cells}  ${c.pct}%  ${c.done} of ${c.total} done  ·  ${duration(elapsedMs)}`]
115  for (const t of tasks) {
116    lines.push(t.status === 'completed' ? `  ✓ ${t.subject}` : t.status === 'in_progress' ? `  ▶ ${t.activeForm || t.subject}` : `  ○ ${t.subject}`)
117  }
118  const left = eta(tasks)
119  if (left) lines.push(`  about ${duration(left)} left (estimate from the measured average)`)
120  return lines.join('\n')
121}
122
hooks/agents.ts 222 lines
1import type { Agent } from '../types'
2
3// What a model id reads as: claude-opus-5-5 -> Opus 5.5. Anything else is shown as given.
4export function modelName(id: string): string {
5  if (id === 'codex') return 'Codex'
6  const m = /(opus|sonnet|haiku)-(\d+)(?:-(\d+))?/i.exec(id || '')
7  if (!m) return id || 'inherit'
8  return `${m[1]![0]!.toUpperCase()}${m[1]!.slice(1).toLowerCase()} ${m[2]}${m[3] ? '.' + m[3] : ''}`
9}
10
11// The crew tier, read from the model the agent runs on: the bigger the model, the heavier the hat.
12export type Tier = { label: string; color: string }
13export function tier(model: string, type: string): Tier {
14  const m = (model || '').toLowerCase()
15  if (type === 'codex') return { label: 'codex', color: '#10a37f' }
16  if (/explore|plan|review/i.test(type)) return { label: 'careful', color: '#e0a526' }
17  if (m.includes('opus')) return { label: 'heavy', color: '#ff6b35' }
18  if (m.includes('haiku')) return { label: 'light', color: '#2ec27e' }
19  return { label: 'medium', color: '#5b8def' }
20}
21
22export function spawned(list: Agent[], a: { id: string; name: string; type: string; model: string; background: boolean }, now: number): Agent[] {
23  if (list.some(x => x.id === a.id)) return list
24  return [...list, { ...a, status: 'running' as const, startedAt: now, endedAt: null, steps: 0, stepLabel: 'Starting', tokens: 0, tasksDone: 0, tasksTotal: 0 }].slice(-40)
25}
26
27export function stepped(list: Agent[], id: string, label: string): Agent[] {
28  return list.map(a => (a.id === id && a.status === 'running' ? { ...a, steps: a.steps + 1, stepLabel: label } : a))
29}
30
31export function agentTasks(list: Agent[], id: string, change: { created?: number; completed?: number; total?: number; done?: number }): Agent[] {
32  return list.map(a => {
33    if (a.id !== id) return a
34    const tasksTotal = change.total ?? a.tasksTotal + (change.created ?? 0)
35    const tasksDone = Math.min(tasksTotal, change.done ?? a.tasksDone + (change.completed ?? 0))
36    return { ...a, tasksTotal, tasksDone }
37  })
38}
39
40export function finished(list: Agent[], id: string, ok: boolean, tokens: number, now: number): Agent[] {
41  return list.map(a => (a.id === id
42    ? { ...a, status: (ok ? 'done' : 'failed') as Agent['status'], endedAt: now, tokens: a.tokens + tokens, tasksDone: ok ? a.tasksTotal : a.tasksDone, stepLabel: ok ? 'Done' : 'Stopped' }
43    : a))
44}
45
46// A tool call as a few words on the agent's card.
47export function stepText(tool: string, input: Record<string, unknown>): string {
48  if (tool === 'TaskUpdate' && typeof input.activeForm === 'string') return input.activeForm
49  if (tool === 'Bash' && typeof input.description === 'string') return input.description
50  if ((tool === 'Read' || tool === 'Edit' || tool === 'Write') && typeof input.file_path === 'string') {
51    return `${tool} ${String(input.file_path).split('/').pop()}`
52  }
53  if (tool === 'Grep' || tool === 'Glob') return 'Searching'
54  if (tool.startsWith('mcp__')) return tool.split('__').slice(1).join(' ').replace(/_/g, ' ')
55  return tool
56}
57
58// The batch: agents started within ten minutes of the newest, so yesterday's crew does not crowd today's.
59export function currentBatch(list: Agent[]): Agent[] {
60  if (!list.length) return []
61  const newest = Math.max(...list.map(a => a.startedAt))
62  return list.filter(a => newest - a.startedAt < 10 * 60_000 || a.status === 'running')
63}
64
65export function fraction(a: Agent): number | null {
66  if (a.status !== 'running') return 1
67  if (a.tasksTotal > 0) return a.tasksDone / a.tasksTotal
68  return null
69}
70
71// How far an agent has got, and how we know. "tasks" is measured: the agent's own checklist,
72// done over total. "est" is an estimate: steps taken over the typical step count for that agent
73// type, from agents that finished earlier, held at 90% until the agent actually finishes.
74export type Progress = { frac: number; kind: 'tasks' | 'est' | 'done' | 'failed'; label: string }
75export function progress(a: Agent, expected: number, now?: number): Progress {
76  if (a.status === 'done') return { frac: 1, kind: 'done', label: '100%' }
77  if (a.status === 'failed') return { frac: a.tasksTotal ? a.tasksDone / a.tasksTotal : 0, kind: 'failed', label: 'stopped' }
78  if (a.type === 'codex') {
79    // A Codex worker runs outside Claude, so its steps are invisible: time is the only signal.
80    // expected is then the typical run time in minutes.
81    const mins = Math.max(0, ((now ?? a.startedAt) - a.startedAt) / 60000)
82    const f = Math.min(0.9, mins / Math.max(1, expected))
83    return { frac: f, kind: 'est', label: `~${Math.round(f * 100)}% est. · ${Math.round(mins)}m of ~${Math.round(expected)}m` }
84  }
85  if (a.tasksTotal > 0) {
86    const f = a.tasksDone / a.tasksTotal
87    return { frac: f, kind: 'tasks', label: `${Math.round(f * 100)}% · ${a.tasksDone}/${a.tasksTotal} tasks` }
88  }
89  const f = Math.min(0.9, a.steps / Math.max(1, expected))
90  return { frac: f, kind: 'est', label: `~${Math.round(f * 100)}% est. · step ${a.steps} of ~${Math.round(expected)}` }
91}
92
93// The typical number of steps an agent of this type takes, from the last 20 that finished:
94// the median for its type, else across all types, else 12 until there is history.
95export function expectedSteps(history: Record<string, number[]>, type: string): number {
96  if (type === 'codex') { const d = (history.codexMinutes ?? []).filter(n => n > 0).sort((x, y) => x - y); return d.length >= 3 ? Math.max(2, d[Math.floor(d.length / 2)]!) : 15 }
97  const med = (xs: number[]) => { const s = [...xs].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]! }
98  const own = (history[type] ?? []).filter(n => n > 0)
99  if (own.length >= 3) return Math.max(3, med(own))
100  const all = Object.entries(history).filter(([k]) => k !== 'codexMinutes').flatMap(([, v]) => v).filter(n => n > 0)
101  return all.length >= 3 ? Math.max(3, med(all)) : 12
102}
103export function recordSteps(history: Record<string, number[]>, type: string, steps: number): Record<string, number[]> {
104  return { ...history, [type]: [...(history[type] ?? []), steps].slice(-20) }
105}
106
107// Appended to every subagent's task so most agents carry a real checklist, which makes their bar
108// a measured percentage instead of an estimate. Off with /progress plans off.
109export const PLAN_NOTE = '\n\nProgress tracking: if you have a task list tool (TaskCreate/TaskUpdate or TodoWrite), start by breaking this job into 3 to 6 short tasks, and mark each one completed the moment it is done. Keep the list to this job only.'
110
111export const compactTokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`)
112
113// ---------- Pixel art (original sprite: a small worker bot whose hat color says its tier) ----------
114
115const SPRITE = [
116  '...hhhh...',
117  '..hhhhhh..',
118  '.hhhhhhhh.',
119  '.bbbbbbbb.',
120  '.bebbbbeb.',
121  '.bbbbbbbb.',
122  '.bbmmmmbb.',
123  '..bbbbbb..',
124  '..b.bb.b..',
125]
126
127// Drawn sizes, so the Svg element gets an exact box: without width and height the desktop app
128// sizes the frame itself, which is how the 0.2.0 band ended up with large white boxes.
129export const botSize = (cell = 4) => ({ width: 10 * cell, height: 10 * cell })
130export const TRACK_H = 22
131export const BAR_H = 6
132
133// The pill's words: the start of what is happening, cut at a word so it reads as a phrase.
134export function pillWords(text: string, max = 18): string {
135  const t = text.replace(/\.\.\.$|…$/, '').trim()
136  if (t.length <= max) return t
137  const cut = t.slice(0, max)
138  const sp = cut.lastIndexOf(' ')
139  return (sp > 6 ? cut.slice(0, sp) : cut).replace(/[\s,;:]+$/, '') + '…'
140}
141
142export function botSvg(hat: string, opts: { cell?: number; bounce?: boolean } = {}): string {
143  const c = opts.cell ?? 4
144  const w = SPRITE[0]!.length * c, hgt = SPRITE.length * c
145  const fill: Record<string, string> = { h: hat, b: '#9fb3c8', e: '#1b2430', m: '#5c6f82' }
146  let rects = ''
147  SPRITE.forEach((row, y) => [...row].forEach((ch, x) => {
148    if (ch !== '.') rects += `<rect x="${x * c}" y="${y * c}" width="${c}" height="${c}" fill="${fill[ch]}"/>`
149  }))
150  const bob = opts.bounce
151    ? `<animateTransform attributeName="transform" type="translate" values="0 0;0 -${c / 2};0 0" dur="0.9s" repeatCount="indefinite"/>`
152    : ''
153  return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${hgt + c}" viewBox="0 -${c} ${w} ${hgt + c}" shape-rendering="crispEdges"><g>${rects}${bob}</g></svg>`
154}
155
156const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
157
158// The band's track: a field of pixel dots that fills left to right, a shimmer running through the
159// filled part while work is in flight, and a pill riding the leading edge with what is happening.
160export function trackSvg(pct: number, label: string, state: 'running' | 'done', width = 300): string {
161  const h = 22, dot = 3, gap = 2, rows = 3
162  const cols = Math.floor((width - 8) / (dot + gap))
163  const filledCols = Math.round((Math.max(0, Math.min(100, pct)) / 100) * cols)
164  const color = state === 'done' ? '#2ec27e' : '#8b7cf6'
165  let dots = ''
166  for (let x = 0; x < cols; x++) {
167    for (let y = 0; y < rows; y++) {
168      const on = x < filledCols
169      const op = on ? 0.95 : ((x * 7 + y * 3) % 5 === 0 ? 0.35 : 0.15)
170      dots += `<rect x="${4 + x * (dot + gap)}" y="${5 + y * (dot + gap)}" width="${dot}" height="${dot}" fill="${on ? color : '#8a8f98'}" opacity="${op}"/>`
171    }
172  }
173  const pillText = esc(label).slice(0, 24)
174  const pillW = Math.max(46, pillText.length * 6.6 + 18)
175  const edge = 4 + filledCols * (dot + gap)
176  const pillX = state === 'done' ? width - pillW - 2 : Math.max(2, Math.min(width - pillW - 2, edge - pillW / 2))
177  const shimmer = state === 'running' && filledCols > 2
178    ? `<rect x="0" y="0" width="28" height="${h}" fill="url(#sh)"><animate attributeName="x" from="-28" to="${edge}" dur="1.6s" repeatCount="indefinite"/></rect>`
179    : ''
180  const pulse = state === 'running'
181    ? `<animate attributeName="opacity" values="1;0.75;1" dur="1.4s" repeatCount="indefinite"/>`
182    : ''
183  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${h}" viewBox="0 0 ${width} ${h}">` +
184    `<defs><linearGradient id="sh" x1="0" x2="1"><stop offset="0" stop-color="#fff" stop-opacity="0"/><stop offset="0.5" stop-color="#fff" stop-opacity="0.55"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>` +
185    `<clipPath id="fill"><rect x="0" y="0" width="${edge}" height="${h}"/></clipPath></defs>` +
186    `<rect x="0" y="0" width="${width}" height="${h}" rx="${h / 2}" fill="#8a8f98" opacity="0.12"/>` +
187    dots + `<g clip-path="url(#fill)">${shimmer}</g>` +
188    `<g><rect x="${pillX}" y="1" width="${pillW}" height="${h - 2}" rx="${(h - 2) / 2}" fill="${color}"/>` +
189    `<text x="${pillX + pillW / 2}" y="${h / 2 + 4}" text-anchor="middle" font-family="-apple-system,Segoe UI,Helvetica,Arial,sans-serif" font-size="11.5" font-weight="600" fill="#fff">${pillText}</text>${pulse}</g></svg>`
190}
191
192// A thin per-agent bar filled to its real fraction. No motion: the fill is the information.
193// Measured progress is solid; an estimate is drawn lighter so the two never look the same.
194export function miniBarSvg(frac: number | null, color: string, width = 260, kind: 'tasks' | 'est' | 'done' | 'failed' = 'tasks'): string {
195  const h = 6, f = Math.max(0, Math.min(1, frac ?? 0)), w = Math.round(width * f)
196  const fill = kind === 'est'
197    ? `<rect x="0" y="0" width="${w}" height="${h}" rx="3" fill="${color}" opacity="0.45"/>`
198    : `<rect x="0" y="0" width="${w}" height="${h}" rx="3" fill="${color}"/>`
199  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${h}" viewBox="0 0 ${width} ${h}"><rect x="0" y="0" width="${width}" height="${h}" rx="3" fill="#8a8f98" opacity="0.2"/>${fill}</svg>`
200}
201
202const clock = (ms: number) => {
203  const s = Math.max(0, Math.round(ms / 1000))
204  return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
205}
206export const agentClock = clock
207
208// One line per agent of the current crew, for sessions whose screen draws no panes.
209export function agentsText(crew: Agent[], now: number): string {
210  if (!crew.length) return ''
211  const done = crew.filter(a => a.status !== 'running').length
212  const lines = [`Agents  ${done} of ${crew.length} finished`]
213  for (const a of crew) {
214    const mark = a.status === 'running' ? '●' : a.status === 'done' ? '✓' : '✕'
215    const t = tier(a.model, a.type)
216    const step = `${progress(a, a.type === 'codex' ? 15 : 12, now).label.split(' · ')[0]} · ${a.stepLabel}`
217    const took = clock((a.endedAt ?? now) - a.startedAt)
218    lines.push(`  ${mark} ${a.name}  (${t.label}, ${modelName(a.model)})  ${a.status === 'running' ? step : a.status === 'done' ? 'finished' : 'failed'}  ·  ${a.tokens ? compactTokens(a.tokens) + ' tokens · ' : ''}${took}`)
219  }
220  return lines.join('\n')
221}
222
types/index.d.ts 46 lines
1export type TaskStatus = 'pending' | 'in_progress' | 'completed'
2
3export type Task = {
4  id: string
5  subject: string
6  activeForm: string | null
7  status: TaskStatus
8  createdAt: number
9  startedAt: number | null
10  doneAt: number | null
11}
12
13export type Celebration = { text: string; big: boolean; until: number }
14
15export type AgentStatus = 'running' | 'done' | 'failed'
16
17export type Agent = {
18  id: string
19  name: string
20  type: string
21  model: string
22  background: boolean
23  status: AgentStatus
24  startedAt: number
25  endedAt: number | null
26  steps: number
27  stepLabel: string
28  tokens: number
29  tasksDone: number
30  tasksTotal: number
31}
32
33declare module 'claude-code' {
34  interface PluginState {
35    'progress-pulse': {
36      tasks: Task[]
37      sessionStart: number
38      celebration: Celebration | null
39      project: string
40      bandHidden: boolean
41      agents: Agent[]
42      paneOpened: boolean
43    }
44  }
45}
46