SLOPSHOPPER

live-status

A live monitor for Claude Code: model, effort, context, 5h/7d usage limits, task progress and a subagents panel, in one responsive card.

panebandguardcommandtoastprocess
v0.5.1MITupdated 2026-10-18fanoisme/claude-mods/plugins/live-status
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · live-status
│ ┃ Agents ✕ › fix the failing auth test and add an audit log call │ ┃ 0/0 running · 0 tokens │ ┃ Collapse ⏺ Read(src/auth.ts) │ ┃ No subagents yet. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /monitor │ ⎿ live-status: Monitor off. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Agents
0/0 running · 0 tokens Collapse No subagents yet.
README

live-status

Part of claude-mods, a collection of Claude Code mods.

A live monitor for Claude Code, drawn above the prompt. One responsive card shows what the session is doing right now: model and effort, context, 5-hour and 7-day usage limits, cost, the task in progress, and your subagents. A matching panel lists every subagent with its own context bar.

The monitor through a whole turn

Idle, light and dark follow your system theme:

Monitor, idle

A narrow window stacks the card and lists subagents inline, so nothing is lost when there is no room for the panel:

Monitor in a narrow window

The agents panel (/monitor, or /agents-live):

Agents panel summary A working subagent A finished subagent

Install

In a Claude Code terminal session:

/plugin install live-status --marketplace fanoisme/claude-mods

Answer y to add the marketplace, then pick the user scope. The mod is active at once and in every session you start afterwards. If you use the Claude desktop app, install it once from a terminal at the user scope: the Code tab loads it too (the /plugin command itself is a terminal command).

Prefer to try it first without installing? Clone the repo and run:

git clone https://github.com/fanoisme/claude-mods
claude --plugin-dir ./claude-mods/plugins/live-status

To remove it: /plugin uninstall live-status.

What you get

PartShowsUpdates
Model chipModel name and effort (Opus 5.5 · high)Every model request
ContextFill, tokens used of the window, HIGH from 60%, CRITICAL from 85%As the engine reports it, and every 5 s mid-turn
5H / 7D limitsUsage of each window and when it resetsAs the engine reports it; countdowns refresh every 15 s when idle
CostSession cost so farAs the engine reports it
StatusWORKING / IDLE, elapsed time, steps, tool calls, running agentsEvery second while a turn runs
Task barProgress of the task being worked on, 3/5 · 60%, segmented per stepWhen the task is reported (see below)
AgentsOne row per subagent, inline when there is no room for the panelLive
RTKToken savings from RTK, only when it is installed: a green RTK PROJECT gauge (this project's average saving, tokens saved, commands) and two sections in the panel (this project, all projects)Re-read every 60 s from rtk gain
Agents panelSummary tiles plus a card per subagent: status, type, model, effort, time, tokens, steps, context barLive
SessionsEvery Claude Code session on the machine, with name, folder, where it runs (desktop / cli), WORKING or IDLE and when it last changed; this one is marked THIS. The band shows 3 sessions · 2 workingRe-read every 3 s, redrawn only when something changed

Level is never shown by color alone: the words HIGH and CRITICAL sit next to the bar. A toast appears once when context or a limit crosses 85%, and again at 95%.

The 5H and 7D limits are reported only for accounts whose plan has them; without a reading the card says so instead of guessing. Subagents show tokens, time and context, not dollars: the engine reports tokens, not money.

Commands

CommandDoes
/monitorShows or hides everything: the band above the prompt and the agents panel together
/monitor on · /monitor offForces it on or off
/agents-liveToggles only the agents panel

The agents panel opens by itself at session start, and the band is on from the first moment.

Watching other sessions

The side panel lists every live session on your machine, so you can keep an eye on a long run in another window:

Sessions panel

Each card shows the task that session is working on, as 3/6 · 50% with a segmented bar. Progress comes from the todo list Claude keeps (see Task progress): every session that has live-status installed publishes its own task to ~/.claude/live-status/progress/<session>.json, and the others read it. A session that reports nothing shows an empty bar and the note "no task progress reported", never a made-up percentage.

It also reads the small registry entries Claude Code keeps in ~/.claude/sessions/<pid>.json (name, folder, status, last update). The only thing it writes is its own progress file (task title, step counts, current step). No transcripts, no keys, no network. Entries untouched for 24 hours are treated as dead and hidden. Per-session model and context are not in that registry, so other sessions show status and activity only; your own session shows the full card.

Task progress

Nothing can know in advance how big a task is, so the task bar reads the todo list Claude already keeps (the built-in TodoWrite tool): 3/5 · 60% is "3 of the 5 todos are completed", and the step in progress is shown next to it. There is nothing to set up and no CLAUDE.md snippet to add. If Claude keeps no todo list, the bar falls back to subagents finished out of subagents started, and with neither the row stays hidden and the card stays compact.

RTK

If RTK is on your PATH, the monitor shows what it has saved you: a green RTK PROJECT gauge in the band for this project (65% average saving, 572 saved · 8 commands), falling back to the global figure (RTK SAVED) until RTK has recorded commands in the folder you are working in. The side panel shows two sections, RTK · THIS PROJECT and RTK · ALL PROJECTS. It runs rtk gain -f json and rtk gain --project -f json once at start and then every 60 seconds. That is a local read of RTK's own history: no network, no tokens. If RTK is not installed, nothing is drawn and nothing polls again.

No tokens

The mod never talks to the model. It adds no tool, no system-prompt text and no instructions, and it makes no model calls: it only watches events the engine already raises and draws what it sees. Concretely:

  • The todo list is observed: the TodoWrite call passes through unchanged, so nothing extra is sent or returned.
  • There is no task-style tool whose definition would ride along on every request.
  • Slash commands (/monitor, /agents-live) answer with a few words, shown once in your transcript.
  • Everything else (the band, the panel, toasts, the status line, the progress files) is drawn locally and costs no tokens.

Responsive by design

WindowWhat changes
WideOne row of model, three gauges and the task bar; the agents panel docks beside the transcript
Under 520 pxThe card stacks into two rows of gauges
No room for the panel (under 144 columns, or the panel is closed)Up to three subagents are listed inline in the band, two when very narrow
TerminalThe same figures as colored text rows, no images

Motion is limited to a slow sheen on the context and task bars and a travelling highlight on the bottom rail, only while a turn is running. It stops under prefers-reduced-motion, and light and dark follow the system theme.

Light on your machine

The mod is built to stay out of the way:

  • Event-driven first. Context, limits and cost arrive from the engine when they change; nothing polls for them while idle beyond one read every 15 s.
  • Adaptive polling. Other sessions are checked every 5 s while something is moving (a turn here, or a working session elsewhere) and every 15 s otherwise, and only files whose modification time changed are read again.
  • A slow clock for the panel. The side panel redraws every 5 to 15 s, not every second; only the band above the prompt ticks each second, and only while a turn runs.
  • Small and bounded. At most 40 subagent runs are kept, sessions idle for a day are dropped, and the panel has no animation.
  • Motion budget. While a turn runs the band draws a single light sweep along its bottom edge; it stops under prefers-reduced-motion.

Customize

All colors and sizes are plain constants at the top of hooks/register.tsx: the CSS string for the card and lozenges, the <linearGradient> stops for the bars, and tone() for the terminal palette. Edit, then reinstall or reload.

Develop

git clone https://github.com/fanoisme/claude-mods
cd claude-mods
claude --plugin-dir ./plugins/live-status       # loads the mod from the folder
claude plugin validate ./plugins/live-status    # manifest + hooks check
npx -p typescript tsc -p ./plugins/live-status --noEmit   # after the mod has loaded once

While a mod loads, Claude Code writes its API types into .claude-plugin/types/, which is what tsc reads (and why that folder is git-ignored). The mod keeps its values in $.state, declared in types/index.d.ts.

Compatibility

Written against the Claude Code mod API of build 2.1.293 (session.measure, turn.step, agent.spawn, ui.render). The desktop app draws the card as SVG; the terminal draws text. If a later build renames an event, claude plugin validate will say which one.

License

MIT, see the repository LICENSE.

Source 2 files
hooks/register.tsx 1308 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Crew, Limit, Panel, Rtk, RtkScope, Run, SessionRow, Task, Turn, Usage } from '../types'
5
6const NO_USAGE: Usage = { ctxPercent: null, ctxTokens: null, ctxWindow: 0, limits: [], costUsd: null }
7const NO_TURN: Turn = { isRunning: false, startedAt: 0, steps: 0, tools: 0, lastSeconds: 0, agents: 0 }
8
9const usage = atom({ plugin: 'live-status', key: 'usage' } as const, NO_USAGE)
10const model = atom({ plugin: 'live-status', key: 'model' } as const, '')
11const effort = atom({ plugin: 'live-status', key: 'effort' } as const, '')
12const turn = atom({ plugin: 'live-status', key: 'turn' } as const, NO_TURN)
13const task = atom({ plugin: 'live-status', key: 'task' } as const, null)
14const crew = atom({ plugin: 'live-status', key: 'crew' } as const, { spawned: 0, done: 0 })
15const runs = atom({ plugin: 'live-status', key: 'runs' } as const, [])
16const rtk = atom({ plugin: 'live-status', key: 'rtk' } as const, null)
17const sessions = atom({ plugin: 'live-status', key: 'sessions' } as const, [])
18const panel = atom({ plugin: 'live-status', key: 'panel' } as const, { isCompact: false, isDoneCollapsed: true })
19const now = atom({ plugin: 'live-status', key: 'now' } as const, 0)
20const slow = atom({ plugin: 'live-status', key: 'slow' } as const, 0)
21
22const PANE = 'live-agents'
23
24// What the card shows for the work in hand: the reported task, else the crew.
25type TaskView = { title: string; done: number; total: number; current: string; isFinished: boolean }
26
27const taskView = (t: Task | null, c: Crew): TaskView | null => {
28  if (t && t.total > 0) return { title: t.title, done: t.done, total: t.total, current: t.current, isFinished: t.isFinished }
29  if (c.spawned > 0) return { title: 'Subagents', done: c.done, total: c.spawned, current: '', isFinished: c.done >= c.spawned }
30  return null
31}
32const isHidden = atom({ plugin: 'live-status', key: 'isHidden' } as const, false)
33const warned = atom({ plugin: 'live-status', key: 'warned' } as const, '')
34
35// Terminal palette (raw colors, the terminal has no CSS).
36const GREEN = '#5fbf8f'
37const AMBER = '#FFBC25'
38const RED = '#E5484D'
39const BLUE = '#8f8cf4'
40
41const tone = (pct: number): string => (pct >= 85 ? RED : pct >= 60 ? AMBER : GREEN)
42
43const bar = (pct: number, width: number): string => {
44  const filled = Math.max(0, Math.min(width, Math.round((width * pct) / 100)))
45  return '█'.repeat(filled) + '░'.repeat(width - filled)
46}
47
48const modelName = (id: string): string => {
49  const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
50  const [, family = '', major = '', minor] = m ?? []
51  if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '...'
52  return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
53}
54
55const fmtTokens = (n: number): string =>
56  n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
57
58const fmtTime = (ms: number): string => {
59  const s = Math.max(0, Math.round(ms / 1000))
60  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
61}
62
63const fmtCost = (usd: number): string => `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
64
65const fmtReset = (iso: string | undefined, at: number): string => {
66  if (!iso) return ''
67  const ms = Date.parse(iso) - at
68  if (!Number.isFinite(ms) || ms <= 0) return ''
69  const m = Math.round(ms / 60000)
70  if (m < 60) return `${m}m`
71  const h = Math.floor(m / 60)
72  return h < 24 ? `${h}h${String(m % 60).padStart(2, '0')}m` : `${Math.floor(h / 24)}d${h % 24}h`
73}
74
75const LIMIT_LABEL: Record<string, string> = { five_hour: '5H', seven_day: '7D', spend_limit: 'SPEND' }
76
77type RawUsage = {
78  context: { tokens?: number; window: number; percent?: number }
79  rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
80  cost?: { usd: number }
81}
82
83const fromUsage = (u: RawUsage): Usage => ({
84  ctxPercent: u.context.percent ?? null,
85  ctxTokens: u.context.tokens ?? null,
86  ctxWindow: u.context.window,
87  limits: u.rateLimits.map((r): Limit => ({ kind: r.kind, pct: r.percentUsed, resetsAt: r.resetsAt })),
88  costUsd: u.cost?.usd ?? null,
89})
90
91async function refresh($: EngineInterface): Promise<void> {
92  try {
93    const u = await $.session.usage()
94    await update($, usage, () => fromUsage(u))
95  } catch {
96    // Usage is not available yet; the next measure fills it in.
97  }
98}
99
100// Before the first model step, the effort is whatever the person configured.
101async function configuredEffort($: EngineInterface): Promise<string> {
102  try {
103    const fromEnv = await $.env.get('CLAUDE_EFFORT')
104    if (fromEnv) return fromEnv
105    const s = (await $.settings.read()) as Record<string, unknown>
106    const level = s.effortLevel ?? s.effort
107    return typeof level === 'string' ? level : ''
108  } catch {
109    return ''
110  }
111}
112
113// ---------------------------------------------------------------------------
114// Desktop drawing: one SVG card. Only looping CSS motion, phase-locked to the
115// wall clock through a negative animation-delay, so the once-a-second redraw
116// of a running turn continues the motion instead of restarting it.
117
118// Design tokens: Inter, soft grey surface, charcoal text, a yellow→orange rail,
119// info / discovery / neutral lozenges, 12px card radius. Change colors in CSS below.
120const FONT = "Inter,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif"
121const EASE = 'cubic-bezier(.65,0,.35,1)' // ease-in-out, for on-screen motion
122
123const xml = (s: string): string =>
124  s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
125
126const charEm = (ch: string): number =>
127  /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-Z@%MW]/.test(ch) ? 0.7 : 0.55
128
129const textWidth = (s: string, size: number): number => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
130
131const fitText = (s: string, size: number, maxW: number): string => {
132  if (textWidth(s, size) <= maxW) return s
133  let out = ''
134  for (const ch of s) {
135    if (textWidth(out + ch + '…', size) > maxW) break
136    out += ch
137  }
138  return out + '…'
139}
140
141// Motion budget: the band keeps one light sweep (the bottom rail) while a turn runs;
142// the shimmer on the bars costs more for little, so it is off.
143const BAND_SHEEN = false
144
145type AgentRow = { name: string; status: 'running' | 'done' | 'failed'; ctx: number }
146
147type Gauge = { label: string; pct: number | null; caption: string; sheen: boolean; good?: boolean }
148
149const gradFor = (pct: number | null): string => (pct === null ? 'gNone' : pct >= 85 ? 'gBad' : pct >= 60 ? 'gWarn' : 'gOk')
150
151const CSS = `
152.card{fill:#F8F9FB;stroke:#D0D6DD}.nm{fill:#333333}.mu{fill:#626B79}.pc{fill:#232933}
153.trk{fill:#FFF4D6}.tick{fill:#626B79}.chip{fill:#F1EBFD}.chipt{fill:#5B3BB0}.chipx{fill:none;stroke:#7D8695}.rail{fill:#EDF0F2}
154.dot-ok{fill:#1F7A4D}.dot-run{fill:#1D5FBF}
155.lz-run{fill:#E8F0FC}.lz-runt{fill:#1D5FBF}.lz-idle{fill:#EDF0F2}.lz-idlet{fill:#333333}
156.lv-hi{fill:#B54708}.lv-bad{fill:#C62F2F}.seg{fill:#F8F9FB}
157@media (prefers-color-scheme: dark){
158.card{fill:#282828;stroke:#3F3F3F}.nm{fill:#FFFFFF}.mu{fill:#C4C9D0}.pc{fill:#FFFFFF}
159.trk{fill:#3A3A38}.tick{fill:#9AA3AF}.chip{fill:#3A2F63}.chipt{fill:#D9CCFA}.chipx{stroke:#626B79}.rail{fill:#3A3A3A}
160.dot-ok{fill:#4FD08F}.dot-run{fill:#6DA7EC}
161.lz-run{fill:#1F3558}.lz-runt{fill:#B7D3F6}.lz-idle{fill:#3A3A3A}.lz-idlet{fill:#FFFFFF}
162.lv-hi{fill:#EB6834}.lv-bad{fill:#FF7A78}.seg{fill:#282828}}
163`
164
165function cardSvg(args: {
166  W: number
167  stack: boolean
168  name: string
169  fx: string
170  cost: string
171  state: string
172  detail: string
173  isRunning: boolean
174  gauges: Gauge[]
175  task: TaskView | null
176  agents: { rows: AgentRow[]; working: number; more: number }
177  sessions?: { total: number; working: number; attention?: number }
178  nowMs: number
179}): { svg: string; H: number } {
180  const { W, stack, name, fx, cost, state, detail, isRunning, gauges, task: tv, agents: ag, sessions: ss, nowMs } = args
181  const PAD = 14
182  const baseH = stack ? 118 : 76
183  const taskH = tv ? 32 : 0
184  const agentH = ag.rows.length ? 24 + ag.rows.length * 22 : 0
185  const H = baseH + taskH + agentH
186  // With a fourth gauge (RTK) the left block gives up some room.
187  const leftW = stack ? W - PAD * 2 : gauges.length > 3 ? Math.max(200, Math.min(290, Math.round(W * 0.3))) : Math.max(232, Math.min(330, Math.round(W * 0.38)))
188  const gx0 = stack ? PAD : PAD + leftW + 22
189  const gy0 = stack ? 58 : 17
190  const gAreaW = stack ? W - PAD * 2 : W - gx0 - PAD
191  const gGap = 18
192  const gw = Math.floor((gAreaW - gGap * (gauges.length - 1)) / Math.max(1, gauges.length))
193
194  const phase = (period: number): string => `-${((nowMs % (period * 1000)) / 1000).toFixed(2)}s`
195
196  // Left block: orb, model, effort chip, cost, status line.
197  const nameFit = fitText(name, 13, leftW - 120)
198  const nameW = textWidth(nameFit, 13) * 1.04
199  const chipText = (fx || 'effort ?').toUpperCase()
200  const chipW = Math.round(textWidth(chipText, 9.5) + 16 + chipText.length * 0.6)
201  const chipX = PAD + 20 + Math.round(nameW) + 8
202  const known = fx !== ''
203  const costX = PAD + leftW
204  const sessText = ss && ss.total > 1 ? `${ss.total} sessions · ${ss.working} working${ss.attention ? ` · ${ss.attention} need you` : ''}` : ''
205  const stateText = state.toUpperCase()
206  const lzW = Math.round(textWidth(stateText, 9.5) + 16 + stateText.length * 0.6)
207  const left = `
208<g>
209  <circle class="${isRunning ? 'dot-run' : 'dot-ok'}" cx="${PAD + 5}" cy="${PAD + 11}" r="4"/>
210  <text class="nm" x="${PAD + 20}" y="${PAD + 15}" font-family="${FONT}" font-size="13" font-weight="650">${xml(nameFit)}</text>
211  <rect class="${known ? 'chip' : 'chipx'}" x="${chipX}" y="${PAD + 3}" width="${chipW}" height="17" rx="8.5"${known ? '' : ' stroke-dasharray="2.5 2.5"'}/>
212  <text class="${known ? 'chipt' : 'mu'}" x="${chipX + chipW / 2}" y="${PAD + 15}" text-anchor="middle" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".6">${xml(chipText)}</text>
213  ${cost ? `<text class="mu" x="${costX}" y="${PAD + 15}" text-anchor="end" font-family="${FONT}" font-size="11" font-weight="600" font-variant-numeric="tabular-nums">${xml(cost)}</text>` : ''}
214  <rect class="${isRunning ? 'lz-run' : 'lz-idle'}" x="${PAD + 20}" y="${PAD + 26}" width="${lzW}" height="17" rx="8.5"/>
215  <text class="${isRunning ? 'lz-runt' : 'lz-idlet'}" x="${PAD + 20 + lzW / 2}" y="${PAD + 38}" text-anchor="middle" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".6">${xml(stateText)}</text>
216  ${sessText ? `<text class="mu" x="${costX}" y="${PAD + 39}" text-anchor="end" font-family="${FONT}" font-size="10" font-weight="600">${xml(sessText)}</text>` : ''}
217  <text class="mu" x="${PAD + 20 + lzW + 8}" y="${PAD + 39}" font-family="${FONT}" font-size="11">${xml(fitText(detail, 11, leftW - 22 - lzW - 8 - (sessText ? Math.round(textWidth(sessText, 10)) + 12 : 0)))}</text>
218</g>`
219
220  // Gauges.
221  const keyframes: string[] = []
222  const draw = gauges.map((g, i) => {
223    const x = gx0 + i * (gw + gGap)
224    const y = gy0
225    const pct = g.pct === null ? 0 : Math.max(0, Math.min(100, g.pct))
226    // Level is never colour alone: the word comes with it.
227    const lvl = g.pct === null || g.good ? '' : pct >= 85 ? (gw < 112 ? 'CRIT' : 'CRITICAL') : pct >= 60 ? 'HIGH' : ''
228    const fillW = g.pct === null ? 0 : Math.max(pct > 0 ? 6 : 0, Math.round((gw * pct) / 100))
229    const ticks = [60, 85]
230      .map(t => ({ t, tx: x + Math.round((gw * t) / 100) }))
231      .filter(({ tx }) => !g.good && tx > x + fillW + 3)
232      .map(({ tx }) => `<rect class="tick" x="${tx}" y="${y + 15}" width="1" height="8" rx=".5" opacity=".55"/>`)
233      .join('')
234    let sheen = ''
235    if (BAND_SHEEN && isRunning && g.sheen && fillW > 12) {
236      keyframes.push(`@keyframes sh${i}{0%{transform:translateX(-30px)}100%{transform:translateX(${fillW}px)}}`)
237      sheen = `<clipPath id="cl${i}"><rect x="${x}" y="${y + 16}" width="${fillW}" height="6" rx="3"/></clipPath>
238<g clip-path="url(#cl${i})"><rect x="${x}" y="${y + 16}" width="30" height="6" fill="url(#gSheen)" style="animation:sh${i} 1.6s ${EASE} infinite;animation-delay:${phase(1.6)}"/></g>`
239    }
240    return `
241<g>
242  <text class="mu" x="${x}" y="${y + 10}" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".9">${xml(g.label)}${lvl ? `<tspan class="${pct >= 85 ? 'lv-bad' : 'lv-hi'}" dx="5">${lvl}</tspan>` : ''}</text>
243  <text class="pc" x="${x + gw}" y="${y + 10}" text-anchor="end" font-family="${FONT}" font-size="12" font-weight="700" font-variant-numeric="tabular-nums">${g.pct === null ? '—' : Math.round(g.pct) + '%'}</text>
244  <rect class="trk" x="${x}" y="${y + 16}" width="${gw}" height="6" rx="3"/>
245  ${fillW ? `<rect x="${x}" y="${y + 16}" width="${fillW}" height="6" rx="3" fill="url(#${g.good ? 'gDone' : gradFor(g.pct)})"/>` : ''}
246  ${sheen}${ticks}
247  <text class="mu" x="${x}" y="${y + 38}" font-family="${FONT}" font-size="10" font-variant-numeric="tabular-nums">${xml(fitText(g.caption, 10, gw))}</text>
248</g>`
249  })
250
251  // The task being worked on: full width, thicker than a gauge, segmented per step.
252  let taskRow = ''
253  if (tv) {
254    const tx = PAD
255    const ty = baseH - 10
256    const tw = W - PAD * 2
257    const pct = Math.max(0, Math.min(100, Math.round((tv.done / Math.max(1, tv.total)) * 100)))
258    const fillW = pct > 0 ? Math.max(8, Math.round((tw * pct) / 100)) : 0
259    const grad = tv.isFinished ? 'gDone' : 'gOk'
260    const stepsText = `${tv.done}/${tv.total}`
261    const right = `${stepsText}  ·  ${pct}%`
262    const labelW = tw - textWidth(right, 12) - 24
263    const head = `TASK${tv.title ? '  ' + tv.title : ''}${tv.current && !tv.isFinished ? '  ›  ' + tv.current : ''}`
264    const segs: string[] = []
265    if (tv.total <= 16) {
266      for (let i = 1; i < tv.total; i++) {
267        segs.push(`<rect class="seg" x="${tx + Math.round((tw * i) / tv.total) - 1}" y="${ty + 16}" width="2" height="8"/>`)
268      }
269    }
270    let sheen = ''
271    if (BAND_SHEEN && isRunning && !tv.isFinished && fillW > 16) {
272      keyframes.push(`@keyframes sht{0%{transform:translateX(-36px)}100%{transform:translateX(${fillW}px)}}`)
273      sheen = `<clipPath id="clt"><rect x="${tx}" y="${ty + 16}" width="${fillW}" height="8" rx="4"/></clipPath>
274<g clip-path="url(#clt)"><rect x="${tx}" y="${ty + 16}" width="36" height="8" fill="url(#gSheen)" style="animation:sht 1.6s ${EASE} infinite;animation-delay:${phase(1.6)}"/></g>`
275    }
276    taskRow = `
277<g>
278  <text class="mu" x="${tx}" y="${ty + 10}" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".9">${xml(fitText(head, 9.5, labelW))}</text>
279  <text class="pc" x="${tx + tw}" y="${ty + 10}" text-anchor="end" font-family="${FONT}" font-size="12" font-weight="700" font-variant-numeric="tabular-nums">${xml(right)}</text>
280  <rect class="trk" x="${tx}" y="${ty + 16}" width="${tw}" height="8" rx="4"/>
281  ${fillW ? `<rect x="${tx}" y="${ty + 16}" width="${fillW}" height="8" rx="4" fill="url(#${grad})"/>` : ''}
282  ${sheen}${segs.join('')}
283</g>`
284  }
285
286  // Subagents inline, for when the agents panel has no room (narrow window): one
287  // compact row each, newest working first.
288  let agentBlock = ''
289  if (ag.rows.length) {
290    const ay = baseH - 10 + taskH
291    const barW = Math.max(48, Math.min(120, Math.round(W * 0.16)))
292    const head = `AGENTS  ·  ${ag.working} working${ag.more ? `  ·  +${ag.more} more` : ''}`
293    const rows = ag.rows.map((r, i) => {
294      const y = ay + 22 + i * 22
295      const fill = Math.round((barW * r.ctx) / 100)
296      const dot = r.status === 'running' ? 'dot-run' : r.status === 'done' ? 'dot-ok' : 'lv-bad'
297      const word = r.status === 'running' ? '' : r.status === 'done' ? 'done' : 'failed'
298      const barX = W - PAD - 40 - barW
299      const wordW = word ? Math.round(textWidth(word, 10) + 10) : 0
300      const nameW = barX - wordW - (PAD + 16) - 10
301      const grad = r.ctx >= 85 ? 'gBad' : r.ctx >= 60 ? 'gWarn' : 'gOk'
302      return `
303<circle class="${dot}" cx="${PAD + 5}" cy="${y + 7}" r="3"/>
304<text class="nm" x="${PAD + 16}" y="${y + 11}" font-family="${FONT}" font-size="11" font-weight="600">${xml(fitText(r.name, 11, Math.max(40, nameW)))}</text>
305${word ? `<text class="${r.status === 'failed' ? 'lv-bad' : 'mu'}" x="${barX - 10}" y="${y + 11}" text-anchor="end" font-family="${FONT}" font-size="10" font-weight="600">${word}</text>` : ''}
306<rect class="trk" x="${barX}" y="${y + 4}" width="${barW}" height="6" rx="3"/>
307${fill > 0 ? `<rect x="${barX}" y="${y + 4}" width="${Math.max(5, fill)}" height="6" rx="3" fill="url(#${r.status === 'done' ? 'gDone' : grad})"/>` : ''}
308<text class="pc" x="${W - PAD}" y="${y + 11}" text-anchor="end" font-family="${FONT}" font-size="11" font-weight="700" font-variant-numeric="tabular-nums">${r.ctx}%</text>`
309    })
310    agentBlock = `<g>
311<text class="mu" x="${PAD}" y="${ay + 10}" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".9">${xml(head)}</text>
312${rows.join('')}
313</g>`
314  }
315
316  // Turn rail along the bottom: a travelling highlight while working.
317  const railW = W - PAD * 2
318  const seg = Math.round(railW * 0.28)
319  keyframes.push(`@keyframes rl{0%{transform:translateX(${-seg}px)}100%{transform:translateX(${railW}px)}}`)
320  const rail = `
321<clipPath id="rc"><rect x="${PAD}" y="${H - 6}" width="${railW}" height="2" rx="1"/></clipPath>
322<rect class="rail" x="${PAD}" y="${H - 6}" width="${railW}" height="2" rx="1"/>
323${isRunning ? `<g clip-path="url(#rc)"><rect x="${PAD}" y="${H - 6}" width="${seg}" height="2" rx="1" fill="url(#gRail)" style="animation:rl 1.8s ${EASE} infinite;animation-delay:${phase(1.8)}"/></g>` : ''}`
324
325  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
326<style>${CSS}
327${keyframes.join('\n')}
328@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style>
329<defs>
330<linearGradient id="gOk" x1="0" x2="1"><stop offset="0" stop-color="#FFBC25"/><stop offset="1" stop-color="#FFA500"/></linearGradient>
331<linearGradient id="gWarn" x1="0" x2="1"><stop offset="0" stop-color="#EB6834"/><stop offset="1" stop-color="#F58A5B"/></linearGradient>
332<linearGradient id="gBad" x1="0" x2="1"><stop offset="0" stop-color="#C62F2F"/><stop offset="1" stop-color="#E34948"/></linearGradient>
333<linearGradient id="gDone" x1="0" x2="1"><stop offset="0" stop-color="#1F7A4D"/><stop offset="1" stop-color="#138A5E"/></linearGradient>
334<linearGradient id="gNone" x1="0" x2="1"><stop offset="0" stop-color="#999"/><stop offset="1" stop-color="#bbb"/></linearGradient>
335<linearGradient id="gSheen" x1="0" x2="1"><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>
336<linearGradient id="gRail" x1="0" x2="1"><stop offset="0" stop-color="#FFA500" stop-opacity="0"/><stop offset=".5" stop-color="#FFA500"/><stop offset="1" stop-color="#FFBC25" stop-opacity="0"/></linearGradient>
337</defs>
338<rect class="card" x=".5" y=".5" width="${W - 1}" height="${H - 1}" rx="12"/>
339${left}
340${draw.join('')}
341${taskRow}
342${agentBlock}
343${rail}
344</svg>`
345  return { svg, H }
346}
347
348// ---------------------------------------------------------------------------
349// Agents pane: one card per subagent, in the monitor's design language.
350
351const PANE_CSS = `${CSS}
352.lz-ok{fill:#E3F5EB}.lz-okt{fill:#1F7A4D}.lz-bad{fill:#FDECEC}.lz-badt{fill:#C62F2F}.tile{fill:#EDF0F2}
353.lz-att{fill:#FFF4D6}.lz-attt{fill:#8A5A00}
354@media (prefers-color-scheme: dark){
355.lz-ok{fill:#1E3A2C}.lz-okt{fill:#7BE0B0}.lz-bad{fill:#4A2323}.lz-badt{fill:#FF9C9A}.tile{fill:#333333}
356.lz-att{fill:#4A3A12}.lz-attt{fill:#FFD36B}}`
357
358const DEFS = `<defs>
359<linearGradient id="gOk" x1="0" x2="1"><stop offset="0" stop-color="#FFBC25"/><stop offset="1" stop-color="#FFA500"/></linearGradient>
360<linearGradient id="gWarn" x1="0" x2="1"><stop offset="0" stop-color="#EB6834"/><stop offset="1" stop-color="#F58A5B"/></linearGradient>
361<linearGradient id="gBad" x1="0" x2="1"><stop offset="0" stop-color="#C62F2F"/><stop offset="1" stop-color="#E34948"/></linearGradient>
362<linearGradient id="gDone" x1="0" x2="1"><stop offset="0" stop-color="#1F7A4D"/><stop offset="1" stop-color="#138A5E"/></linearGradient>
363<linearGradient id="gSheen" x1="0" x2="1"><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>
364</defs>`
365
366const paneSvg = (W: number, H: number, extra: string, body: string): string =>
367  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}"><style>${PANE_CSS}${extra}
368@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style>${DEFS}${body}</svg>`
369
370const runElapsed = (a: Run, at: number): number => (a.endedAt ?? Math.max(at, a.startedAt)) - a.startedAt
371const runContext = (a: Run): number => (a.contextMax ? Math.min(100, Math.round((a.contextTokens / a.contextMax) * 100)) : 0)
372
373const LOZENGE: Record<Run['status'], { text: string; bg: string; fg: string }> = {
374  running: { text: 'WORKING', bg: 'lz-run', fg: 'lz-runt' },
375  done: { text: 'DONE', bg: 'lz-ok', fg: 'lz-okt' },
376  failed: { text: 'FAILED', bg: 'lz-bad', fg: 'lz-badt' },
377}
378
379const statsSvg = (W: number, list: Run[], at: number): string => {
380  const running = list.filter(a => a.status === 'running').length
381  const tokens = list.reduce((s, a) => s + a.tokens, 0)
382  const start = list.length ? Math.min(...list.map(a => a.startedAt)) : 0
383  const end = list.length ? Math.max(...list.map(a => a.endedAt ?? Math.max(at, a.startedAt))) : 0
384  const gap = 8
385  const tw = Math.floor((W - gap * 2) / 3)
386  const tile = (i: number, k: string, v: string): string => {
387    const x = i * (tw + gap)
388    return `<rect class="tile" x="${x}" y="0" width="${tw}" height="46" rx="8"/>
389<text class="mu" x="${x + 12}" y="18" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".9">${k}</text>
390<text class="pc" x="${x + 12}" y="37" font-family="${FONT}" font-size="16" font-weight="700" font-variant-numeric="tabular-nums">${xml(v)}</text>`
391  }
392  return paneSvg(
393    W,
394    46,
395    '',
396    tile(0, 'RUNNING', `${running} / ${list.length}`) + tile(1, 'TOKENS', fmtTokens(tokens)) + tile(2, 'TIME', fmtTime(end - start)),
397  )
398}
399
400const agentSvg = (W: number, a: Run, at: number, nowMs: number): string => {
401  const H = 100
402  const PAD = 14
403  const lz = LOZENGE[a.status]
404  const lzW = Math.round(textWidth(lz.text, 9.5) + 16 + lz.text.length * 0.6)
405  const ctx = runContext(a)
406  const typeText = a.type.replace(/^[^:]*:/, '')
407  const chipW = Math.round(textWidth(typeText, 10) + 18)
408  const meta = [
409    modelName(a.model),
410    a.effort ? a.effort : '',
411    fmtTime(runElapsed(a, at)),
412    `${fmtTokens(a.tokens)} tok`,
413    `${a.steps} ${a.steps === 1 ? 'step' : 'steps'}`,
414  ]
415    .filter(Boolean)
416    .join('  ·  ')
417  const barW = W - PAD * 2
418  const fillW = ctx > 0 ? Math.max(6, Math.round((barW * ctx) / 100)) : 0
419  const lvl = ctx >= 85 ? 'CRITICAL' : ctx >= 60 ? 'HIGH' : ''
420  const grad = ctx >= 85 ? 'gBad' : ctx >= 60 ? 'gWarn' : 'gOk'
421  const dot = a.status === 'running' ? 'dot-run' : a.status === 'done' ? 'dot-ok' : 'lv-bad'
422  const sheen = ''
423  const kf = ''
424  const body = `
425<rect class="card" x=".5" y=".5" width="${W - 1}" height="${H - 1}" rx="12"/>
426<circle class="${dot}" cx="${PAD + 5}" cy="${PAD + 11}" r="4"/>
427<text class="nm" x="${PAD + 20}" y="${PAD + 15}" font-family="${FONT}" font-size="13" font-weight="650">${xml(fitText(a.description || a.type, 13, W - PAD * 2 - 20 - lzW - 12))}</text>
428<rect class="${lz.bg}" x="${W - PAD - lzW}" y="${PAD + 3}" width="${lzW}" height="17" rx="8.5"/>
429<text class="${lz.fg}" x="${W - PAD - lzW / 2}" y="${PAD + 15}" text-anchor="middle" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".6">${lz.text}</text>
430<rect class="chip" x="${PAD + 20}" y="${PAD + 27}" width="${chipW}" height="16" rx="8"/>
431<text class="chipt" x="${PAD + 20 + chipW / 2}" y="${PAD + 38.5}" text-anchor="middle" font-family="${FONT}" font-size="10" font-weight="600">${xml(typeText)}</text>
432<text class="mu" x="${PAD + 20 + chipW + 8}" y="${PAD + 39}" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${xml(fitText(meta, 11, W - PAD * 2 - 20 - chipW - 8))}</text>
433<text class="mu" x="${PAD}" y="${H - 30}" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".9">CONTEXT${lvl ? `<tspan class="${ctx >= 85 ? 'lv-bad' : 'lv-hi'}" dx="5">${lvl}</tspan>` : ''}</text>
434<text class="pc" x="${W - PAD}" y="${H - 30}" text-anchor="end" font-family="${FONT}" font-size="11" font-weight="700" font-variant-numeric="tabular-nums">${ctx}%  <tspan class="mu" font-weight="500">${fmtTokens(a.contextTokens)} of ${fmtTokens(a.contextMax)}</tspan></text>
435<rect class="trk" x="${PAD}" y="${H - 24}" width="${barW}" height="6" rx="3"/>
436${fillW ? `<rect x="${PAD}" y="${H - 24}" width="${fillW}" height="6" rx="3" fill="url(#${a.status === 'done' ? 'gDone' : grad})"/>` : ''}
437${sheen}`
438  return paneSvg(W, H, kf, body)
439}
440
441// ---------------------------------------------------------------------------
442// Every session on this machine. Claude Code keeps a small registry entry per
443// live session in ~/.claude/sessions/<pid>.json (name, folder, status, last
444// update). Only that metadata is read: never transcripts, never the .key files.
445
446const DEAD_AFTER_MS = 24 * 3600 * 1000
447
448// Parsed registry and progress files, keyed by name and file time: a poll only reads
449// the files that changed since the last one.
450const regCache = new Map<string, { m: number; raw: Record<string, unknown> }>()
451const progCache = new Map<string, { m: number; raw: Record<string, unknown> }>()
452
453// An idle session that stopped recently is most likely waiting for you (a turn just
454// finished); one that has been quiet for longer is background noise and is hidden.
455// The registry only says busy or idle, so "needs you" is that recency, not a flag.
456const ATTENTION_MS = 30 * 60 * 1000
457
458const needsYou = (s: SessionRow, at: number): boolean => s.status === 'idle' && !s.isSelf && at - s.updatedAt <= ATTENTION_MS
459const isShown = (s: SessionRow, at: number): boolean => s.isSelf || s.status === 'busy' || at - s.updatedAt <= ATTENTION_MS
460
461const lastSegment = (p: string): string => p.split(/[\\/]/).filter(Boolean).pop() || p
462
463// RTK (a CLI that condenses command output to save tokens), when it is installed.
464// `rtk gain -f json` is a local read of its own history: no network, no tokens.
465const fmtSaved = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : `${Math.round(n)}`)
466
467const parseRtk = (stdout: string): RtkScope | null => {
468  try {
469    const sum = (JSON.parse(stdout) as { summary?: Record<string, unknown> }).summary
470    if (!sum) return null
471    const saved = Number(sum.total_saved ?? 0)
472    const input = Number(sum.total_input ?? 0)
473    const pct = Number(sum.avg_savings_pct ?? (input > 0 ? (saved / input) * 100 : 0))
474    return {
475      saved,
476      input,
477      output: Number(sum.total_output ?? 0),
478      commands: Number(sum.total_commands ?? 0),
479      pct: Math.max(0, Math.min(100, pct)),
480    }
481  } catch {
482    return null
483  }
484}
485
486// Global savings, plus the savings of the session's own folder (`rtk gain --project`,
487// run in the session's working directory) when RTK has recorded commands there.
488async function readRtk($: EngineInterface): Promise<Rtk | null> {
489  try {
490    const all = await $.process.run(['rtk', 'gain', '-f', 'json'], { timeoutMs: 8000 })
491    if (all.exitCode !== 0) return null
492    const global = parseRtk(all.stdout)
493    if (!global) return null
494    let project: RtkScope | null = null
495    try {
496      const mine = await $.process.run(['rtk', 'gain', '--project', '-f', 'json'], { timeoutMs: 8000 })
497      const parsed = mine.exitCode === 0 ? parseRtk(mine.stdout) : null
498      project = parsed && parsed.commands > 0 ? parsed : null
499    } catch {
500      // No per-project reading: the global one still shows.
501    }
502    return { ...global, project }
503  } catch {
504    return null
505  }
506}
507
508async function homeDir($: EngineInterface): Promise<string> {
509  return ((await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || '').replace(/\\/g, '/')
510}
511
512// Each session publishes the progress of its own task to
513// ~/.claude/live-status/progress/<sessionId>.json, so the others can draw it.
514// Only the task's title, step counts and current step are written.
515async function publishProgress($: EngineInterface): Promise<void> {
516  try {
517    const home = await homeDir($)
518    if (!home) return
519    const id = await $.session.id()
520    const tv = taskView(await read($, task), await read($, crew))
521    const at = await $.clock.now()
522    const body = tv ? { title: tv.title, done: tv.done, total: tv.total, current: tv.current, isFinished: tv.isFinished, updatedAt: at } : { total: 0, updatedAt: at }
523    await $.fs.write(`${home}/.claude/live-status/progress/${id}.json`, JSON.stringify(body))
524  } catch {
525    // Not writable: other sessions simply see no progress from this one.
526  }
527}
528
529async function readProgress($: EngineInterface, home: string, id: string, at: number): Promise<SessionRow['task']> {
530  try {
531    const path = `${home}/.claude/live-status/progress/${id}.json`
532    const st = await $.fs.stat(path)
533    const hit = progCache.get(id)
534    let raw: Record<string, unknown>
535    if (hit && hit.m === st.mtimeMs) {
536      raw = hit.raw
537    } else {
538      raw = JSON.parse((await $.fs.read(path)) as string) as Record<string, unknown>
539      progCache.set(id, { m: st.mtimeMs, raw })
540    }
541    const total = Number(raw.total ?? 0)
542    if (!(total > 0) || at - Number(raw.updatedAt ?? 0) > DEAD_AFTER_MS) return undefined
543    return {
544      title: typeof raw.title === 'string' ? raw.title : '',
545      done: Math.max(0, Math.min(total, Number(raw.done ?? 0))),
546      total,
547      current: typeof raw.current === 'string' ? raw.current : '',
548      isFinished: raw.isFinished === true,
549    }
550  } catch {
551    return undefined
552  }
553}
554
555const sessionSig = (rows: SessionRow[]): string =>
556  JSON.stringify(rows.map(r => [r.id, r.status, r.updatedAt, r.name, r.task ? [r.task.done, r.task.total, r.task.current, r.task.isFinished] : 0]))
557
558async function readSessions($: EngineInterface): Promise<SessionRow[]> {
559  try {
560    const home = await homeDir($)
561    if (!home) return []
562    const dir = `${home}/.claude/sessions`
563    const entries = await $.fs.list(dir)
564    const self = await $.session.id()
565    const at = await $.clock.now()
566    const rows: SessionRow[] = []
567    for (const en of entries) {
568      if (!/^\d+\.json$/.test(en.name)) continue
569      try {
570        const hit = regCache.get(en.name)
571        let raw: Record<string, unknown>
572        if (hit && hit.m === en.mtimeMs) {
573          raw = hit.raw
574        } else {
575          raw = JSON.parse((await $.fs.read(`${dir}/${en.name}`)) as string) as Record<string, unknown>
576          regCache.set(en.name, { m: en.mtimeMs, raw })
577        }
578        const id = typeof raw.sessionId === 'string' ? raw.sessionId : ''
579        if (!id) continue
580        const updatedAt = Number(raw.updatedAt ?? raw.statusUpdatedAt ?? raw.startedAt ?? 0)
581        if (at - updatedAt > DEAD_AFTER_MS) continue
582        const cwd = typeof raw.cwd === 'string' ? raw.cwd : ''
583        rows.push({
584          id,
585          pid: Number(raw.pid ?? 0),
586          name: typeof raw.name === 'string' && raw.name ? raw.name : lastSegment(cwd) || 'session',
587          project: lastSegment(cwd),
588          entry: typeof raw.entrypoint === 'string' ? raw.entrypoint.replace(/^claude-/, '') : 'cli',
589          status: raw.status === 'busy' ? 'busy' : 'idle',
590          updatedAt,
591          startedAt: Number(raw.startedAt ?? 0),
592          isSelf: id === self,
593        })
594      } catch {
595        // A half-written or unreadable entry: skip it, the next poll gets it.
596      }
597    }
598    for (const k of [...regCache.keys()]) if (!entries.some(en => en.name === k)) regCache.delete(k)
599    for (const r of rows) {
600      if (r.isSelf) continue
601      const progress = await readProgress($, home, r.id, at)
602      if (progress) r.task = progress
603    }
604    // This session first, then working ones, then the most recently active.
605    return rows.sort(
606      (a, b) =>
607        Number(b.isSelf) - Number(a.isSelf) ||
608        (a.status === b.status ? b.updatedAt - a.updatedAt : a.status === 'busy' ? -1 : 1),
609    )
610  } catch {
611    return []
612  }
613}
614
615const ago = (ms: number): string => {
616  const s = Math.max(0, Math.round(ms / 1000))
617  if (s < 60) return `${s}s ago`
618  const m = Math.floor(s / 60)
619  return m < 60 ? `${m}m ago` : `${Math.floor(m / 60)}h ago`
620}
621
622const sessionSvg = (W: number, s: SessionRow, at: number, nowMs: number): string => {
623  void nowMs
624  const H = 96
625  const PAD = 14
626  const busy = s.status === 'busy'
627  const attention = needsYou(s, at)
628  const lz = busy
629    ? { text: 'WORKING', bg: 'lz-run', fg: 'lz-runt' }
630    : attention
631      ? { text: 'NEEDS YOU', bg: 'lz-att', fg: 'lz-attt' }
632      : { text: 'IDLE', bg: 'lz-idle', fg: 'lz-idlet' }
633  const lzW = Math.round(textWidth(lz.text, 9.5) + 16 + lz.text.length * 0.6)
634  const thisW = s.isSelf ? Math.round(textWidth('THIS', 9) + 14) : 0
635  const meta = `${s.entry} · ${s.project} · ${ago(at - s.updatedAt)}`
636  const thisChip = s.isSelf
637    ? `<rect class="chip" x="${W - PAD - lzW - thisW - 8}" y="${PAD + 4}" width="${thisW}" height="15" rx="7.5"/><text class="chipt" x="${W - PAD - lzW - thisW / 2 - 8}" y="${PAD + 15}" text-anchor="middle" font-family="${FONT}" font-size="9" font-weight="700" letter-spacing=".6">THIS</text>`
638    : ''
639
640  // Progress is the todo list that session keeps. A session that
641  // reports none gets an empty bar and a plain note, never an invented percentage.
642  const tk = s.task && s.task.total > 0 ? s.task : null
643  const pct = tk ? Math.round((tk.done / tk.total) * 100) : 0
644  const barW = W - PAD * 2
645  const barY = H - 20
646  const fillW = tk && pct > 0 ? Math.max(6, Math.round((barW * pct) / 100)) : 0
647  const right = tk ? `${tk.done}/${tk.total}  ·  ${pct}%` : ''
648  const head = tk
649    ? `${tk.title}${tk.current && !tk.isFinished ? '  ›  ' + tk.current : ''}`
650    : busy
651      ? 'working · no task progress reported'
652      : 'no task reported'
653  const segs: string[] = []
654  if (tk && tk.total <= 16) {
655    for (let i = 1; i < tk.total; i++) {
656      segs.push(`<rect class="seg" x="${PAD + Math.round((barW * i) / tk.total) - 1}" y="${barY}" width="2" height="6"/>`)
657    }
658  }
659  const body = `
660<rect class="card" x=".5" y=".5" width="${W - 1}" height="${H - 1}" rx="12"${s.isSelf ? ' style="stroke:#FFBC25"' : ''}/>
661<circle class="${busy ? 'dot-run' : 'dot-ok'}" cx="${PAD + 5}" cy="${PAD + 11}" r="4"/>
662<text class="nm" x="${PAD + 20}" y="${PAD + 15}" font-family="${FONT}" font-size="13" font-weight="650">${xml(fitText(s.name, 13, W - PAD * 2 - 20 - lzW - thisW - 20))}</text>
663${thisChip}
664<rect class="${lz.bg}" x="${W - PAD - lzW}" y="${PAD + 3}" width="${lzW}" height="17" rx="8.5"/>
665<text class="${lz.fg}" x="${W - PAD - lzW / 2}" y="${PAD + 15}" text-anchor="middle" font-family="${FONT}" font-size="9.5" font-weight="700" letter-spacing=".6">${lz.text}</text>
666<text class="mu" x="${PAD + 20}" y="${PAD + 38}" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${xml(fitText(meta, 11, W - PAD * 2 - 20))}</text>
667<text class="${tk ? 'nm' : 'mu'}" x="${PAD}" y="${H - 27}" font-family="${FONT}" font-size="10" font-weight="${tk ? 600 : 500}">${xml(fitText(head, 10, barW - (right ? textWidth(right, 11) + 16 : 0)))}</text>
668${right ? `<text class="pc" x="${W - PAD}" y="${H - 27}" text-anchor="end" font-family="${FONT}" font-size="11" font-weight="700" font-variant-numeric="tabular-nums">${xml(right)}</text>` : ''}
669<rect class="trk" x="${PAD}" y="${barY}" width="${barW}" height="6" rx="3"/>
670${fillW ? `<rect x="${PAD}" y="${barY}" width="${fillW}" height="6" rx="3" fill="url(#${tk && tk.isFinished ? 'gDone' : 'gOk'})"/>` : ''}
671${segs.join('')}`
672  return paneSvg(W, H, '', body)
673}
674
675// A section header: caption left, summary right, and an overview progress bar.
676const sectionSvg = (W: number, title: string, summary: string, pct: number | null, isDone = false): string => {
677  const H = 38
678  const fillW = pct === null ? 0 : Math.max(pct > 0 ? 6 : 0, Math.round((W * Math.min(100, pct)) / 100))
679  const body = `
680<text class="nm" x="0" y="14" font-family="${FONT}" font-size="10.5" font-weight="800" letter-spacing="1.2">${xml(title)}</text>
681<text class="mu" x="${W}" y="14" text-anchor="end" font-family="${FONT}" font-size="11" font-weight="600" font-variant-numeric="tabular-nums">${xml(fitText(summary, 11, W - textWidth(title, 10.5) - 24))}</text>
682<rect class="trk" x="0" y="22" width="${W}" height="7" rx="3.5"/>
683${fillW ? `<rect x="0" y="22" width="${fillW}" height="7" rx="3.5" fill="url(#${isDone ? 'gDone' : 'gOk'})"/>` : ''}`
684  return paneSvg(W, H, '', body)
685}
686
687async function togglePane($: EngineInterface): Promise<boolean> {
688  const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
689  if (isOpen) {
690    await $.ui.close({ id: PANE })
691    return false
692  }
693  const at = await $.clock.now()
694  await update($, now, () => at)
695  await $.ui.open({ id: PANE, title: 'Agents' })
696  return true
697}
698
699export const register: Register = on => {
700  on('session.start', async ($, e, next) => {
701    const started = await next(e)
702    await update($, now, () => 0)
703    try {
704      const m = await $.session.model()
705      await update($, model, () => m)
706    } catch {
707      // The model shows up with the first step.
708    }
709    await $.command.register({
710      name: 'monitor',
711      description: 'Show or hide the whole monitor: the band above the prompt and the agents panel (on / off to force)',
712    })
713    await $.command.register({
714      name: 'agents-live',
715      description: 'Show or hide the panel of subagents: status, model, context, tokens and time',
716    })
717    await refresh($)
718    const configured = await configuredEffort($)
719    await update($, effort, cur => cur || configured)
720
721    // On from the first moment: the band draws by itself; open the agents panel too.
722    void $.ui.open({ id: PANE, title: 'Agents' })
723
724    // Realtime: every second while a turn runs (clock, steps), every 5th second
725    // re-reading usage mid-step; idle, every 15 seconds so reset countdowns and
726    // limit windows stay true. Changes the engine reports arrive at once through
727    // session.measure.
728    let ticks = 0
729    let lastSessionSig = ''
730    let othersBusy = false
731    // RTK: detected once; if it is not there nothing is drawn and nothing polls again.
732    let rtkOn = false
733    let rtkAt = 0
734    const first = await readRtk($)
735    rtkOn = first !== null
736    await update($, rtk, () => first)
737    // First read right away, so the panel is not empty for the first seconds.
738    const firstRows = await readSessions($)
739    lastSessionSig = sessionSig(firstRows)
740    othersBusy = firstRows.some(r => !r.isSelf && r.status === 'busy')
741    void publishProgress($)
742    await update($, sessions, () => firstRows)
743    $.clock.every(1000, () => {
744      void (async () => {
745        ticks += 1
746        const t = await read($, turn)
747        if (rtkOn && ticks - rtkAt >= 60) {
748          rtkAt = ticks
749          const fresh = await readRtk($)
750          if (fresh) await update($, rtk, () => fresh)
751        }
752        // Cheap by design. Other sessions: polled every 5 s while something moves (a turn
753        // here, or a working session elsewhere), every 15 s otherwise, and only files
754        // that changed are read. The panel redraws on that slow clock. Usage is
755        // re-read every 15 s, since the engine also reports changes by itself.
756        const every = t.isRunning || othersBusy ? 5 : 15
757        if (ticks % every === 0) {
758          const rows = await readSessions($)
759          othersBusy = rows.some(r => !r.isSelf && r.status === 'busy')
760          const sig = sessionSig(rows)
761          if (sig !== lastSessionSig) {
762            lastSessionSig = sig
763            await update($, sessions, () => rows)
764          }
765          const at = await $.clock.now()
766          await update($, slow, () => at)
767        }
768        if (t.isRunning || ticks % 15 === 0) {
769          if (ticks % 15 === 0) await refresh($)
770          const at = await $.clock.now()
771          await update($, now, () => at)
772        }
773      })()
774    })
775
776    return started
777  })
778
779  // Context, limits and cost move on their own: the engine reports each change.
780  on('session.measure', async ($, e, next) => {
781    await update($, usage, () => fromUsage(e))
782
783    const worst = Math.max(e.context.percent ?? 0, ...e.rateLimits.map(r => r.percentUsed))
784    const level = worst >= 95 ? '95' : worst >= 85 ? '85' : ''
785    if (level && (await read($, warned)) !== level) {
786      await update($, warned, () => level)
787      $.ui.toast(`Usage at ${Math.round(worst)}%: see the monitor above the prompt`)
788    } else if (!level) {
789      await update($, warned, () => '')
790    }
791
792    return next(e)
793  })
794
795  // One command for both: the band above the prompt and the agents panel.
796  on('command.run', { command: 'monitor' }, async ($, e) => {
797    const arg = e.args.trim().toLowerCase()
798    const hidden = await read($, isHidden)
799    const paneOpen = (await $.ui.panes()).some(p => p.id === PANE)
800    const wantOn = arg === 'on' ? true : arg === 'off' ? false : hidden || !paneOpen
801
802    if (wantOn) {
803      await update($, isHidden, () => false)
804      if (!paneOpen) await togglePane($)
805      return { text: 'Monitor on: band and agents panel.' }
806    }
807    await update($, isHidden, () => true)
808    if (paneOpen) await togglePane($)
809    return { text: 'Monitor off.' }
810  })
811
812  on('command.run', { command: 'agents-live' }, async $ => {
813    const isOpen = await togglePane($)
814    return { text: isOpen ? 'Agents panel opened.' : 'Agents panel closed.' }
815  })
816
817  // Task progress comes from the todo list Claude already keeps (TodoWrite). The call is
818  // only observed and passes through untouched, so this adds no tokens: no tool of our
819  // own in the model's tool list, no extra calls, nothing written to its context.
820  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
821    const ran = await next(e)
822    if (e.agentId) return ran
823    const todos = (e as unknown as { todos?: { content?: string; status?: string; activeForm?: string }[] }).todos ?? []
824    const total = todos.length
825    const done = todos.filter(t => t.status === 'completed').length
826    const active = todos.find(t => t.status === 'in_progress') ?? todos.find(t => t.status === 'pending')
827    await update($, task, () =>
828      total > 0
829        ? {
830            title: 'Tasks',
831            total,
832            done,
833            current: (active?.activeForm || active?.content || '').trim(),
834            isFinished: done === total,
835          }
836        : null,
837    )
838    const at = await $.clock.now()
839    await update($, now, () => at)
840    await publishProgress($)
841    return ran
842  })
843
844  on('turn.start', async ($, e, next) => {
845    await update($, crew, () => ({ spawned: 0, done: 0 }))
846    await publishProgress($)
847    await update($, task, prev => (prev?.isFinished ? null : prev))
848    const at = await $.clock.now()
849    await update($, turn, t => ({ ...NO_TURN, isRunning: true, startedAt: at, agents: t.agents }))
850    await update($, now, () => at)
851    return next(e)
852  })
853
854  on('turn.step', async function* ($, e, next) {
855    if (!e.agentId) {
856      await update($, model, () => e.model)
857      await update($, effort, () => (e.effort === undefined ? '' : String(e.effort)))
858      await update($, turn, t => ({ ...t, steps: t.steps + 1 }))
859    }
860    const result = yield* next(e)
861    const u = result.usage
862    const agentId = e.agentId
863    if (agentId && u) {
864      // A subagent's own request: its live context, tokens and step count.
865      const used =
866        (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.output_tokens || 0)
867      await update($, runs, list =>
868        list.map(r =>
869          r.agentId !== agentId
870            ? r
871            : {
872                ...r,
873                model: u.model || e.model,
874                effort: typeof e.effort === 'string' ? e.effort : r.effort,
875                status: 'running' as const,
876                endedAt: undefined,
877                contextTokens: used,
878                contextMax: /haiku/i.test(u.model || e.model) ? 200_000 : 1_000_000,
879                tokens: r.tokens + used,
880                steps: r.steps + 1,
881              },
882        ),
883      )
884    }
885    await refresh($)
886    return result
887  })
888
889  on('tool.call', async ($, e, next) => {
890    if (!e.agentId) await update($, turn, t => ({ ...t, tools: t.tools + 1 }))
891    return next(e)
892  })
893
894  on('agent.spawn', async ($, e, next) => {
895    const started = await next(e)
896    if (started.deny === undefined) {
897      await update($, turn, t => ({ ...t, agents: t.agents + 1 }))
898      await update($, crew, c => ({ ...c, spawned: c.spawned + 1 }))
899      await publishProgress($)
900      const at = await $.clock.now()
901      await update($, runs, list => {
902        const run: Run = {
903          id: started.agentId ?? e.tool_use_id,
904          agentId: started.agentId,
905          type: e.subagentType,
906          description: e.description,
907          model: started.model,
908          status: 'running',
909          startedAt: at,
910          contextTokens: 0,
911          contextMax: /haiku/i.test(started.model) ? 200_000 : 1_000_000,
912          tokens: 0,
913          steps: 0,
914        }
915        return [...list.filter(r => r.id !== run.id), run].slice(-40)
916      })
917      await update($, now, () => at)
918    }
919    return started
920  })
921
922  on('turn.complete', async ($, e, next) => {
923    const at = await $.clock.now()
924    if (e.agentId) {
925      await update($, turn, t => ({ ...t, agents: Math.max(0, t.agents - 1) }))
926      await update($, crew, c => ({ ...c, done: Math.min(c.spawned, c.done + 1) }))
927      await publishProgress($)
928      const agentId = e.agentId
929      await update($, runs, list =>
930        list.map(r => (r.agentId === agentId ? { ...r, status: e.reason === 'answer' ? ('done' as const) : ('failed' as const), endedAt: at } : r)),
931      )
932    } else {
933      await update($, turn, t => ({
934        ...t,
935        isRunning: false,
936        lastSeconds: Math.round((at - t.startedAt) / 1000),
937        agents: 0,
938      }))
939    }
940    await refresh($)
941    return next(e)
942  })
943
944  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
945    const ui = $.ui.resolve(e)
946    const { Box, Text, Button } = ui
947    const list = await read($, runs)
948    const p: Panel = await read($, panel)
949    const nowMs = await $.clock.now()
950    await read($, slow) // the panel redraws on this slow clock, not every second
951    const at = nowMs
952    const running = list.filter(r => r.status === 'running').reverse()
953    const finished = list.filter(r => r.status !== 'running').reverse()
954    const rtkInfo = await read($, rtk)
955    const everySession = await read($, sessions)
956    const own = taskView(await read($, task), await read($, crew))
957    const sessionList = everySession
958      .filter(s => isShown(s, nowMs))
959      .map(s => (s.isSelf && own ? { ...s, task: { title: own.title, done: own.done, total: own.total, current: own.current, isFinished: own.isFinished } } : s))
960    const sessionsHidden = everySession.length - sessionList.length
961    const sessionsWorking = sessionList.filter(s => s.status === 'busy').length
962    const sessionsNeed = sessionList.filter(s => needsYou(s, nowMs)).length
963
964    const toggleCompact = (
965      <Button
966        key="compact"
967        label={p.isCompact ? 'Expand' : 'Collapse'}
968        plain
969        onPress={() => update($, panel, prev => ({ ...prev, isCompact: !prev.isCompact }))}
970      />
971    )
972    const toggleDone = (
973      <Button
974        key="done"
975        label={`${p.isDoneCollapsed ? '▸' : '▾'} Finished · ${finished.length}`}
976        plain
977        onPress={() => update($, panel, prev => ({ ...prev, isDoneCollapsed: !prev.isDoneCollapsed }))}
978      />
979    )
980
981    if ('Svg' in ui) {
982      const { Svg } = ui
983      const W = Math.max(240, Math.min(900, (e.props.bodyColumns || 40) * 8 - 8))
984      const card = (r: Run) => (
985        <Svg
986          key={r.id}
987          source={agentSvg(W, r, at, nowMs)}
988          alt={`${r.description || r.type}: ${r.status}, ${modelName(r.model)}, context ${runContext(r)}%`}
989          width={W}
990          height={100}
991        />
992      )
993      return (
994        <Box flexDirection="column" gap={1}>
995          <Svg
996            source={statsSvg(W, list, at)}
997            alt={`${running.length} of ${list.length} agents running, ${fmtTokens(list.reduce((s, r) => s + r.tokens, 0))} tokens`}
998            width={W}
999            height={46}
1000          />
1001          {toggleCompact}
1002          {rtkInfo?.project && !p.isCompact && (
1003            <Svg
1004              source={sectionSvg(W, 'RTK · THIS PROJECT', `${fmtSaved(rtkInfo.project.saved)} saved · ${rtkInfo.project.commands} commands · ${Math.round(rtkInfo.project.pct)}%`, rtkInfo.project.pct, true)}
1005              alt={`RTK in this project: ${fmtSaved(rtkInfo.project.saved)} tokens saved over ${rtkInfo.project.commands} commands, ${Math.round(rtkInfo.project.pct)} percent`}
1006              width={W}
1007              height={38}
1008            />
1009          )}
1010          {rtkInfo && !p.isCompact && (
1011            <Svg
1012              source={sectionSvg(W, 'RTK · ALL PROJECTS', `${fmtSaved(rtkInfo.saved)} saved · ${rtkInfo.commands} commands · ${Math.round(rtkInfo.pct)}%`, rtkInfo.pct, true)}
1013              alt={`RTK overall: ${fmtSaved(rtkInfo.saved)} tokens saved over ${rtkInfo.commands} commands, ${Math.round(rtkInfo.pct)} percent`}
1014              width={W}
1015              height={38}
1016            />
1017          )}
1018          {!p.isCompact && (
1019            <Svg
1020              source={sectionSvg(W, 'SESSIONS', `${sessionsWorking} working${sessionsNeed ? ` · ${sessionsNeed} need you` : ''}${sessionsHidden ? ` · ${sessionsHidden} idle hidden` : ''}`, sessionList.length ? (sessionsWorking / sessionList.length) * 100 : null)}
1021              alt={`Sessions: ${sessionsWorking} of ${sessionList.length} working, ${sessionsNeed} need you, ${sessionsHidden} idle hidden`}
1022              width={W}
1023              height={38}
1024            />
1025          )}
1026          {!p.isCompact && sessionList.length === 0 && <Text dimColor>No sessions found yet.</Text>}
1027          {!p.isCompact &&
1028            sessionList.map(s => (
1029              <Svg
1030                key={s.id}
1031                source={sessionSvg(W, s, nowMs, nowMs)}
1032                alt={`${s.name}${s.isSelf ? ' (this session)' : ''}: ${s.status === 'busy' ? 'working' : 'idle'}, ${s.project}, updated ${ago(nowMs - s.updatedAt)}`}
1033                width={W}
1034                height={96}
1035              />
1036            ))}
1037          {!p.isCompact && (
1038            <Svg
1039              source={sectionSvg(W, 'SUBAGENTS', list.length ? `${finished.length} / ${list.length} finished` : 'none yet', list.length ? (finished.length / list.length) * 100 : null, list.length > 0 && running.length === 0)}
1040              alt={`Subagents: ${finished.length} of ${list.length} finished`}
1041              width={W}
1042              height={38}
1043            />
1044          )}
1045          {list.length === 0 && <Text dimColor>No subagents yet. They show up here the moment one starts.</Text>}
1046          {!p.isCompact && running.length > 0 && <Text dimColor>Working · {running.length}</Text>}
1047          {!p.isCompact && running.map(card)}
1048          {!p.isCompact && finished.length > 0 && toggleDone}
1049          {!p.isCompact && !p.isDoneCollapsed && finished.slice(0, 8).map(card)}
1050        </Box>
1051      )
1052    }
1053
1054    // Terminal: the same rows in text.
1055    const cols = Math.max(24, e.props.bodyColumns || 40)
1056    const w = Math.max(6, Math.min(20, cols - 30))
1057    const row = (r: Run) => {
1058      const ctx = runContext(r)
1059      return (
1060        <Box key={r.id} flexDirection="column" marginBottom={1}>
1061          <Text bold wrap="truncate-end">
1062            <Text color={r.status === 'failed' ? RED : r.status === 'done' ? GREEN : BLUE}>
1063              {r.status === 'running' ? '●' : r.status === 'done' ? '✓' : '✗'}{' '}
1064            </Text>
1065            {r.description || r.type}
1066          </Text>
1067          <Text dimColor wrap="truncate-end">
1068            {'  '}
1069            {r.type.replace(/^[^:]*:/, '')} · {modelName(r.model)}
1070            {r.effort ? ` · ${r.effort}` : ''} · {fmtTime(runElapsed(r, at))} · {fmtTokens(r.tokens)} tok
1071          </Text>
1072          <Text wrap="truncate-end">
1073            {'  '}
1074            <Text color={tone(ctx)}>{bar(ctx, w)}</Text>
1075            <Text dimColor>
1076              {' '}
1077              ctx {ctx}% · {fmtTokens(r.contextTokens)}
1078            </Text>
1079          </Text>
1080        </Box>
1081      )
1082    }
1083    return (
1084      <Box flexDirection="column">
1085        <Text dimColor>
1086          {running.length}/{list.length} running · {fmtTokens(list.reduce((s, r) => s + r.tokens, 0))} tokens
1087        </Text>
1088        {toggleCompact}
1089        {!p.isCompact && sessionList.length > 0 && (
1090          <Text dimColor>
1091            sessions · {sessionsWorking}/{sessionList.length} working{sessionsNeed ? ` · ${sessionsNeed} need you` : ''}{sessionsHidden ? ` · ${sessionsHidden} hidden` : ''}{' '}
1092            {bar(sessionList.length ? (sessionsWorking / sessionList.length) * 100 : 0, 10)}
1093          </Text>
1094        )}
1095        {!p.isCompact &&
1096          sessionList.map(s => (
1097            <Text key={s.id} wrap="truncate-end">
1098              <Text color={s.status === 'busy' ? BLUE : needsYou(s, nowMs) ? AMBER : GREEN}>{s.status === 'busy' ? '●' : needsYou(s, nowMs) ? '!' : '○'} </Text>
1099              {s.name}
1100              <Text dimColor>
1101                {' '}
1102                {s.isSelf ? '(this) ' : ''}· {s.project} · {ago(nowMs - s.updatedAt)}
1103              </Text>
1104            </Text>
1105          ))}
1106        {!p.isCompact && list.length > 0 && (
1107          <Text dimColor>
1108            subagents · {finished.length}/{list.length} finished {bar((finished.length / list.length) * 100, 10)}
1109          </Text>
1110        )}
1111        {list.length === 0 && <Text dimColor>No subagents yet.</Text>}
1112        {!p.isCompact && running.map(row)}
1113        {!p.isCompact && finished.length > 0 && toggleDone}
1114        {!p.isCompact && !p.isDoneCollapsed && finished.slice(0, 8).map(row)}
1115      </Box>
1116    )
1117  })
1118
1119  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1120    if (e.props.hasSurvey || (await read($, isHidden))) return next(e)
1121
1122    const ui = $.ui.resolve(e)
1123    const { Box, Text, Button } = ui
1124    const u = await read($, usage)
1125    const rtkInfo = await read($, rtk)
1126    const rtkView = rtkInfo ? (rtkInfo.project ?? rtkInfo) : null
1127    const t = await read($, turn)
1128    const at = (await read($, now)) || (await $.clock.now())
1129    const m = await read($, model)
1130    const fx = await read($, effort)
1131    const tv = taskView(await read($, task), await read($, crew))
1132    const runList = await read($, runs)
1133    const shownAt = await $.clock.now()
1134    const allSessions = (await read($, sessions)).filter(s => isShown(s, shownAt))
1135    const sessionSummary = {
1136      total: allSessions.length,
1137      working: allSessions.filter(s => s.status === 'busy').length,
1138      attention: allSessions.filter(s => needsYou(s, shownAt)).length,
1139    }
1140    const crewCount = runList.length
1141
1142    // Agents go inline when the panel has no room (narrow window) or is not open.
1143    let paneOpen = false
1144    try {
1145      paneOpen = (await $.ui.panes()).some(p => p.id === PANE)
1146    } catch {
1147      // Treat as closed: the inline rows are the safe fallback.
1148    }
1149    const needInline = runList.length > 0 && (!paneOpen || (e.props.bodyColumns || 100) < 144)
1150    const maxRows = (e.props.bodyColumns || 100) < 70 ? 2 : 3
1151    const ordered = [...runList.filter(r => r.status === 'running').reverse(), ...runList.filter(r => r.status !== 'running').reverse()]
1152    const inline = {
1153      rows: needInline
1154        ? ordered.slice(0, maxRows).map((r): AgentRow => ({ name: r.description || r.type, status: r.status, ctx: runContext(r) }))
1155        : [],
1156      working: runList.filter(r => r.status === 'running').length,
1157      more: needInline ? Math.max(0, ordered.length - maxRows) : 0,
1158    }
1159    const cols = e.props.bodyColumns || 100
1160    const ctx = u.ctxPercent
1161
1162    const elapsed = t.isRunning ? fmtTime(at - t.startedAt) : t.lastSeconds ? fmtTime(t.lastSeconds * 1000) : ''
1163    const plural = (n: number, w: string): string => `${n} ${w}${n === 1 ? '' : 's'}`
1164    const state = t.isRunning ? 'Working' : 'Idle'
1165    const detail = t.isRunning
1166      ? `${elapsed} · ${plural(t.steps, 'step')} · ${plural(t.tools, 'tool')}${t.agents ? ` · ${plural(t.agents, 'agent')}` : ''}`
1167      : t.lastSeconds
1168        ? `last turn ${elapsed} · ${plural(t.steps, 'step')}`
1169        : 'waiting for a prompt'
1170    const status = `${state} · ${detail}`
1171
1172    const dismiss = <Button key="hide" label="✕" plain role="dismiss" onPress={() => update($, isHidden, () => true)} />
1173
1174    if ('Svg' in ui) {
1175      const { Svg } = ui
1176      const W = Math.max(300, Math.min(1100, cols * 8 - 56))
1177      const gauges: Gauge[] = [
1178        {
1179          label: 'CONTEXT',
1180          pct: ctx,
1181          caption: u.ctxTokens !== null && u.ctxWindow ? `${fmtTokens(u.ctxTokens)} of ${fmtTokens(u.ctxWindow)}` : 'no reading',
1182          sheen: true,
1183        },
1184        ...u.limits.map(
1185          (l): Gauge => ({
1186            label: LIMIT_LABEL[l.kind] ?? l.kind.toUpperCase(),
1187            pct: l.pct,
1188            caption: l.resetsAt ? `resets in ${fmtReset(l.resetsAt, at)}` : 'resets unknown',
1189            sheen: false,
1190          }),
1191        ),
1192        ...(rtkView
1193          ? [{ label: rtkInfo?.project ? 'RTK PROJECT' : 'RTK SAVED', pct: Math.round(rtkView.pct), caption: `${fmtSaved(rtkView.saved)} saved · ${rtkView.commands}`, sheen: false, good: true } as Gauge]
1194          : []),
1195      ]
1196      const { svg, H } = cardSvg({
1197        W,
1198        stack: W < 520,
1199        name: m ? modelName(m) : 'Claude',
1200        fx,
types/index.d.ts 90 lines
1export type Limit = { kind: string; pct: number; resetsAt?: string }
2
3export type Usage = {
4  ctxPercent: number | null
5  ctxTokens: number | null
6  ctxWindow: number
7  limits: Limit[]
8  costUsd: number | null
9}
10
11export type Turn = {
12  isRunning: boolean
13  startedAt: number
14  steps: number
15  tools: number
16  lastSeconds: number
17  agents: number
18}
19
20// The task being worked on, as reported through the `task` tool.
21export type Task = {
22  title: string
23  total: number
24  done: number
25  current: string
26  isFinished: boolean
27}
28
29// Subagents launched / finished since the turn began: the automatic fallback.
30export type Crew = { spawned: number; done: number }
31
32// One subagent, from agent.spawn to its last turn.
33export type Run = {
34  id: string
35  agentId?: string
36  type: string
37  description: string
38  model: string
39  effort?: string
40  status: 'running' | 'done' | 'failed'
41  startedAt: number
42  endedAt?: number
43  contextTokens: number
44  contextMax: number
45  tokens: number
46  steps: number
47}
48
49export type Panel = { isCompact: boolean; isDoneCollapsed: boolean }
50
51// RTK's token-savings summary (`rtk gain`), when RTK is installed.
52export type RtkScope = { saved: number; input: number; output: number; commands: number; pct: number }
53export type Rtk = RtkScope & { project: RtkScope | null }
54
55// One Claude Code session on this machine, from its entry in ~/.claude/sessions.
56export type SessionRow = {
57  id: string
58  pid: number
59  name: string
60  project: string
61  entry: string
62  status: 'busy' | 'idle'
63  updatedAt: number
64  startedAt: number
65  isSelf: boolean
66  // The task that session reports (see the `task` tool); absent when it reports none.
67  task?: { title: string; done: number; total: number; current: string; isFinished: boolean }
68}
69
70declare module 'claude-code' {
71  interface PluginState {
72    'live-status': {
73      usage: Usage
74      model: string
75      effort: string
76      turn: Turn
77      task: Task | null
78      crew: Crew
79      runs: Run[]
80      sessions: SessionRow[]
81      rtk: Rtk | null
82      panel: Panel
83      now: number
84      slow: number
85      isHidden: boolean
86      warned: string
87    }
88  }
89}
90