Status band above the prompt in the Claude Desktop app's Code tab: folder, git branch and state, session age, prompt count and cost, a context meter, 5-hour…

A Claude Code mod that puts a status band above the prompt in the Claude Desktop app's Code tab.
The Claude Code CLI has a statusLine setting that runs a script and prints its output under the prompt. The desktop Code tab never runs that script, so desktop sessions show none of it. This mod reads the same session data from inside Claude Code and draws it in the desktop app instead.

statusLine keeps working as before.git, in the session's folder.Four lines on a normal window. On a narrow window the two limit meters stack, which makes five.
/autocompact, the autoCompactWindow setting, or CLAUDE_CODE_AUTO_COMPACT_WINDOW), it measures against that window, as /context does.🔎 advisor ×2), how long the session has been idle, and how many times it has compacted, with the token count before and after the last compaction.Each subagent still out gets a row of its own, up to three, followed by a +N more agents running line: running (⏳), and dimmed, queued (⋯), held (⏸) and teammates idle between turns (💤).
Each workflow run gets one row while any of its agents is still out, such as ⚙ workflow wf_… · 2 active with 1/3 done on the right. Refused, errored or aborted agents show as · N failed in amber. An agent that hasn't answered after an hour stops counting as active.
Meters turn amber at 80% and red at 95%. A cache hit rate under 50% shows as a warning, and so does an idle time past the prompt-cache TTL, marked (cache cold). When a usage limit crosses 80% and again at 95%, once per limit window, it sends a notification through your terminal's notification channel where one delivers it, and pops up a toast otherwise. In the desktop app expect the toast.
Mods need Claude Code v2.1.287 or later. The desktop app ships its own copy of Claude Code, so keep the app updated too.
Run these inside the Claude Code terminal CLI (claude in your shell):
/plugin marketplace add centminmod/claude-plugins
/plugin install desktop-statusline@centminmod
Then start a new session in the desktop app's Code tab. The band appears once the session has data to show, usually right away.
One setting, cache_ttl, sets how long your session can sit idle before the band marks the prompt cache cold. Claude Code asks for it when you enable the plugin, and you can change it later in /plugin or /config. Enter 1h or 5m; any other value counts as 1h.
Claude Code's prompt caching docs give these defaults for the main conversation:
| Account | Default TTL | Set cache_ttl to | | :- | :- | :- | | Claude subscription, within plan usage | 1 hour | 1h, the default | | API key, cloud provider, or a subscription drawing on usage credits | 5 minutes | 5m |
A promptCacheTtl setting or the CLAUDE_CODE_PROMPT_CACHE_TTL environment variable overrides those defaults, so match whatever you set there. The docs don't split Pro from Max. If you're not sure which TTL you get, run this and look at usage.cache_creation in the output:
claude -p "hello" --output-format json
One-hour cache writes count under ephemeral_1h_input_tokens, five-minute writes under ephemeral_5m_input_tokens.
Claude Code stores your answer in ~/.claude/settings.json:
{
"pluginConfigs": {
"desktop-statusline@centminmod": {
"options": { "cache_ttl": "5m" }
}
}
}
See Cache lifetime for which TTL your sessions get.
The band refreshes when the session starts, when the desktop app attaches, after every turn and every subagent answer, when a plan limit's percentage changes, two seconds after Claude or a workflow starts a subagent, and every 60 seconds.
Programs it runs. Only git, with two fixed read-only commands, in the session's folder and with a 5-second timeout:
git status --porcelain=v2 --branch, for the branch, commits ahead or behind upstream, and the uncommitted file countgit rev-parse --git-dir --git-common-dir, to tell a worktree from the main checkoutNeither command contacts a remote, and the mod runs them only in desktop sessions. It starts no other program. Both commands are written out in full at their $.process.run calls in hooks/register.tsx. The session's folder ($.session.cwd) is passed to them only as the working directory; nothing else the mod reads, such as the prompt count from $.session.turns, is passed to them. Their output goes only into the band.
What it reads. Through Claude Code's mods API, it reads the session's usage (context size, cost, and the 5-hour and weekly plan limits), the session's folder, the number of prompts, the start time, and the type, state and short task description of each subagent. For workflow-started subagents it reads the run ID and agent ID at spawn, and whether each one's answer ended normally; never its prompt or answer text. From each model request of the main conversation it reads the names of any server-side tools the API ran. It asks for the usage with Claude Code's local /context estimate (no API call) and uses only its auto-compact window and whether auto-compaction is on; it ignores the rest of that estimate, such as memory file paths and tool names. From each finished turn it reads the duration, the model, and the token counts used for the cache hit rate. After a compaction it reads the token counts before and after. It doesn't read prompt or response text, files, environment variables, or credentials such as API keys or tokens. The plan limits come from Claude Code, not from your login.
What it sends. Nothing over the network. It makes no network calls and writes no files. What it reads goes only into the band above the prompt, the usage-limit notification or toast (its text is the limit name, percentage and reset time, handed to Claude Code's local notification channel), and the session's $.state, which ends with the session.
The one URL in the code, http://www.w3.org/2000/svg, is the standard SVG namespace in the meter bars' xmlns attribute. It labels the markup as SVG and is never fetched. The token counts next to it are the context and compaction sizes the band displays, not API keys or login tokens.
What its hooks change. Nothing. The session.compact hook waits for the compaction to finish, records the before and after token counts, and returns the result unchanged. The tool.call hook for the Agent tool and the agent.spawn hook schedule a band refresh two seconds later and pass the call through unchanged; agent.spawn also notes a workflow agent's run ID, and if anything in it fails the spawn still goes ahead. The turn.step hook forwards every model response chunk untouched and only reads the finished step's server-tool names. The turn.complete hook reads the finished turn and passes it through unchanged.
Before installing a mod, you can list what it hooks and calls without running it. Clone this repo and run:
claude plugin validate plugins/desktop-statusline
For this mod the report lists:
session.start, session.attach for the desktop, session.measure, turn.complete, turn.step, agent.spawn, tool.call for the Agent tool only, session.compact, and ui.render for the AbovePrompt band.$.process.run for git status --porcelain=v2 --branch and git rev-parse --git-dir --git-common-dir.It keeps its values in the session's $.state and writes no files. To run its tests against the engine: claude plugin test plugins/desktop-statusline.
cache_ttl says.claude -p, or cloud sessions. Mods only draw in the terminal and the desktop Code tab, and this one only draws in the desktop.Disable it from the Installed tab in /plugin, or uninstall it from your shell:
claude plugin uninstall desktop-statusline@centminmod
MIT. See LICENSE.
hooks/register.tsx 446 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, ProcessRunResult, Register } from 'claude-code'
3
4import type { Limit, Snapshot, WorkflowRun } from '../types'
5
6const snapshot = atom({ plugin: 'desktop-statusline', key: 'snap' } as const, null)
7const warned = atom({ plugin: 'desktop-statusline', key: 'warned' } as const, [])
8const lastTurn = atom({ plugin: 'desktop-statusline', key: 'lastTurn' } as const, null)
9const compactions = atom({ plugin: 'desktop-statusline', key: 'compactions' } as const, null)
10const workflowRuns = atom({ plugin: 'desktop-statusline', key: 'runTally' } as const, {})
11// An agent out this long without an answer stops counting as active: one killed without an
12// answer, or a remote one, whose answer never reaches this session.
13const AGENT_STALE_MS = 60 * 60_000
14const MAX_RUNS = 20
15// Answers from subagent loops that matched no tracked run yet: a fast workflow agent can answer
16// before its spawn hook has recorded it. Newest last, a few kept.
17const early = new Map<string, 'done' | 'failed'>()
18const EARLY_MAX = 50
19
20// Server tools (web search, advisor, ...) the API ran inside the main loop's current turn.
21let serverTurnId: string | null = null
22let serverTools: Record<string, number> = {}
23
24const AGENT_ICON: Record<string, string> = { pending: '⋯', running: '⏳', waiting: '⏸', idle: '💤' }
25const ACTIVE = ['pending', 'running', 'waiting']
26
27const REFRESH_MS = 60_000
28const WARN_AT = [95, 80]
29const LABELS: Record<string, string> = { five_hour: '5-hour', seven_day: 'Weekly' }
30const LABEL_CELLS = 8
31const PERCENT_CELLS = 5
32const DETAIL_GAP = 2
33const METER_GAP = 3
34const AGENT_ROWS = 3
35// Desktop metrics in CSS px, measured from screenshots of the band: a Box `width` cell, one
36// column of `bodyColumns`, and an average glyph of the band's proportional font. Bars are SVG
37// in px, so the limits row is fitted in px, keeping 5% spare for the estimate.
38const CELL_PX = 15
39const COL_PX = 12.5
40const CHAR_PX = 13
41const SPARE = 0.95
42const MIN_BAR_PX = 60
43const MAX_BAR_PX = 180
44
45const label = (kind: string) => LABELS[kind] ?? kind.replace(/_/g, ' ')
46const tone = (percent: number) => (percent >= 95 ? 'error' : percent >= 80 ? 'warning' : undefined)
47const tokens = (n: number) =>
48 n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`
49
50// Drawn as an image, so it cannot follow the theme: a translucent track reads on light and dark.
51const bar = (percent: number, width: number) => {
52 const fill = percent >= 95 ? '#e5484d' : percent >= 80 ? '#e0a030' : '#2f7de1'
53 const filled = Math.round((Math.min(percent, 100) / 100) * width)
54 return (
55 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8" viewBox="0 0 ${width} 8">` +
56 `<rect width="${width}" height="8" rx="4" fill="#808080" fill-opacity="0.3"/>` +
57 `<rect width="${filled}" height="8" rx="4" fill="${fill}"/></svg>`
58 )
59}
60
61const until = (iso: string, now: number) => {
62 const minutes = Math.max(0, Math.round((Date.parse(iso) - now) / 60_000))
63 if (minutes < 60) return `${minutes}m`
64 if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
65 return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`
66}
67
68const elapsed = (ms: number) => {
69 const s = Math.round(ms / 1000)
70 if (s < 60) return `${s}s`
71 if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`
72 return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
73}
74
75const ago = (ms: number) => {
76 const minutes = Math.floor(ms / 60_000)
77 if (minutes < 1) return '<1m'
78 if (minutes < 60) return `${minutes}m`
79 if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
80 return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`
81}
82
83const cacheHit = (u: ModelUsage) => {
84 const input = u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
85 return input === 0 ? null : Math.round((u.cache_read_input_tokens / input) * 100)
86}
87
88const isOnDesktop = async ($: EngineInterface) => (await $.session.surfaces()).includes('desktop')
89
90// Each git command is written out in full at its call; this only reads the result.
91const output = async (run: Promise<ProcessRunResult>) => {
92 try {
93 const ran = await run
94 return ran.exitCode === 0 ? ran.stdout.trim() : null
95 } catch {
96 return null
97 }
98}
99
100const warn = async ($: EngineInterface, limits: Limit[], now: number) => {
101 const seen = await read($, warned)
102 const fresh: string[] = []
103
104 for (const limit of limits) {
105 const threshold = WARN_AT.find(t => limit.percent >= t)
106 const key = `${limit.kind}@${threshold}@${limit.resetsAt}`
107 if (threshold === undefined || seen.includes(key)) continue
108
109 fresh.push(key)
110 const resets = limit.resetsAt ? ` · resets in ${until(limit.resetsAt, now)}` : ''
111 const text = `${label(limit.kind)} usage limit at ${limit.percent}%${resets}`
112 // A system notification where the person's channel delivers one; the toast otherwise.
113 if (!(await $.ui.notify(text, { title: 'Usage limit' })).isSent) $.ui.toast(text, { timeoutMs: 8000 })
114 }
115
116 if (fresh.length > 0) await update($, warned, s => [...s, ...fresh].slice(-50))
117}
118
119const refresh = async ($: EngineInterface) => {
120 if (!(await isOnDesktop($))) return
121
122 const [usage, cwd, now, agents, prompts, tracked] = await Promise.all([
123 // A local estimate (no API calls), asked for only its compaction window.
124 $.session.usage({ breakdown: 'summary' }),
125 $.session.cwd(),
126 $.clock.now(),
127 $.agent.list(),
128 $.session.turns(),
129 read($, workflowRuns),
130 ])
131 // `$.agent.list()` leaves a workflow's agents out, so runs are counted from their own spawn and
132 // turn.complete events: one line per run while any agent is active and the run is not stale.
133 const runs: WorkflowRun[] = []
134 for (const [runId, run] of Object.entries(tracked)) {
135 const active = Object.values(run.active).filter(at => now - at <= AGENT_STALE_MS).length
136 if (active === 0) continue
137 runs.push({ runId, total: active + run.done + run.failed, active, done: run.done, failed: run.failed })
138 }
139 const [status, dirs] = await Promise.all([
140 output($.process.run(['git', 'status', '--porcelain=v2', '--branch'], { cwd, timeoutMs: 5000 })),
141 output($.process.run(['git', 'rev-parse', '--git-dir', '--git-common-dir'], { cwd, timeoutMs: 5000 })),
142 ])
143
144 const lines = status?.split('\n') ?? []
145 const head = lines.find(l => l.startsWith('# branch.head '))?.slice(14)
146 const ab = lines.find(l => l.startsWith('# branch.ab '))?.match(/\+(\d+) -(\d+)/)
147 const [gitDir, commonDir] = dirs?.split('\n') ?? []
148 const limits = usage.rateLimits.map(r => ({
149 kind: r.kind,
150 percent: r.percentUsed,
151 resetsAt: r.resetsAt ?? null,
152 }))
153 // Measure against the auto-compact window when one smaller than the model's is set (the
154 // autoCompactWindow setting, /autocompact, CLAUDE_CODE_AUTO_COMPACT_WINDOW), as /context does.
155 const { tokens: contextTokens, window: modelWindow, breakdown } = usage.context
156 const contextWindow = breakdown?.isAutoCompactEnabled ? Math.min(modelWindow, breakdown.rawMaxTokens) : modelWindow
157
158 const snap: Snapshot = {
159 at: now,
160 startedAt: usage.startedAt,
161 prompts,
162 dir: cwd.split('/').pop() || cwd,
163 branch: head && head !== '(detached)' ? head : null,
164 isWorktree: gitDir !== commonDir,
165 ahead: Number(ab?.[1] ?? 0),
166 behind: Number(ab?.[2] ?? 0),
167 changed: lines.filter(l => l && !l.startsWith('#')).length,
168 contextPercent: contextTokens === undefined ? null : Math.round((contextTokens / contextWindow) * 100),
169 contextTokens: contextTokens ?? null,
170 contextWindow,
171 costUsd: usage.cost?.usd ?? null,
172 limits,
173 // Held and queued agents too, and teammates idle between turns; not finished ones.
174 agents: agents
175 .filter(a => ACTIVE.includes(a.status) || (a.status === 'idle' && a.teammateId))
176 .map(a => ({ type: a.type, description: a.description, status: a.status })),
177 runs,
178 }
179
180 await update($, snapshot, () => snap)
181 await warn($, limits, now)
182}
183
184export const register: Register = (on, options) => {
185 // The main conversation's prompt-cache TTL (the `cache_ttl` option): 1 hour on a Claude
186 // subscription within plan usage, 5 minutes with pay-as-you-go API billing, a cloud provider or usage credits.
187 const cacheTtlMs = options.cache_ttl === '5m' ? 5 * 60_000 : 60 * 60_000
188 on('session.start', async ($, e, next) => {
189 const started = await next(e)
190 await refresh($)
191 $.clock.every(REFRESH_MS, () => void refresh($))
192
193 return started
194 })
195
196 on('session.attach', { surface: 'desktop' }, async ($, e, next) => {
197 const attached = await next(e)
198 await refresh($)
199
200 return attached
201 })
202
203 on('session.measure', async ($, e, next) => {
204 const measured = await next(e)
205 await refresh($)
206
207 return measured
208 })
209
210 on('turn.complete', async ($, e, next) => {
211 const completed = await next(e)
212 if (!e.agentId) {
213 const at = await $.clock.now()
214 await update($, lastTurn, () => ({
215 at,
216 durationMs: e.durationMs,
217 model: e.usage?.model ?? null,
218 cacheHit: e.usage ? cacheHit(e.usage) : null,
219 serverTools: serverTurnId === e.turnId ? serverTools : {},
220 }))
221 } else {
222 // A workflow agent's answer: mark it in its run, if it is one this mod tracks.
223 const agentId = e.agentId
224 // Aborted, refused or errored all count as failed.
225 const state = e.reason === 'answer' ? 'done' : 'failed'
226 const runId = Object.entries(await read($, workflowRuns)).find(([, r]) => agentId in r.active)?.[0]
227 if (runId === undefined) {
228 early.set(agentId, state)
229 if (early.size > EARLY_MAX) early.delete(early.keys().next().value!)
230 } else {
231 const at = await $.clock.now()
232 await update($, workflowRuns, m => {
233 const run = m[runId]
234 if (!run || !(agentId in run.active)) return m
235 const { [agentId]: _, ...active } = run.active
236 return { ...m, [runId]: { ...run, at, active, [state]: run[state] + 1 } }
237 })
238 }
239 }
240 await refresh($)
241
242 return completed
243 })
244
245 // A streaming event: forward the chunks untouched and read the step's result at the end.
246 on('turn.step', async function* (_$, e, next) {
247 const step = yield* next(e)
248 if (e.agentId || !step.serverToolUses?.length) return step
249
250 if (serverTurnId !== e.turnId) {
251 serverTurnId = e.turnId
252 serverTools = {}
253 }
254 for (const use of step.serverToolUses) serverTools[use.name] = (serverTools[use.name] ?? 0) + 1
255
256 return step
257 })
258
259 on('agent.spawn', async ($, e, next) => {
260 const spawned = await next(e)
261 if (e.workflow && spawned.agentId) {
262 const { runId } = e.workflow
263 const agentId = spawned.agentId
264 const at = await $.clock.now()
265 const answered = early.get(agentId)
266 early.delete(agentId)
267 // Newest runs last; keep the last MAX_RUNS. Agents out past AGENT_STALE_MS are let go here.
268 await update($, workflowRuns, m => {
269 const { [runId]: run, ...rest } = m
270 const kept = Object.fromEntries(Object.entries(run?.active ?? {}).filter(([, t]) => at - t <= AGENT_STALE_MS))
271 const base = { at, done: run?.done ?? 0, failed: run?.failed ?? 0, active: kept }
272 const touched = answered ? { ...base, [answered]: base[answered] + 1 } : { ...base, active: { ...kept, [agentId]: at } }
273 return Object.fromEntries([...Object.entries(rest), [runId, touched]].slice(-MAX_RUNS))
274 })
275 // Not an Agent tool call, so the tool.call hook below misses it.
276 $.clock.after(2000, () => void refresh($))
277 }
278
279 return spawned
280 }).catch((_$, e, next) => next(e))
281
282 // A spawned agent shows as running only once it has started; look again shortly after.
283 on('tool.call', { tool: 'Agent' }, ($, e, next) => {
284 $.clock.after(2000, () => void refresh($))
285
286 return next(e)
287 })
288
289 on('session.compact', async ($, e, next) => {
290 const result = await next(e)
291 if (e.trigger === 'precompute' || e.agentId || result.messages === undefined) return result
292
293 const { startedAt } = await $.session.usage()
294 await update($, compactions, c => ({
295 since: startedAt,
296 count: (c?.since === startedAt ? c.count : 0) + 1,
297 before: result.tokensBefore ?? null,
298 after: result.tokensAfter ?? null,
299 }))
300
301 return result
302 })
303
304 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
305 if (e.surface !== 'desktop' || e.props.hasSurvey) return next(e)
306
307 const snap = await read($, snapshot)
308 if (snap === null) return next(e)
309
310 const { Box, Svg, Text } = $.ui.resolve(e)
311
312 const meter = (name: string, percent: number | null, detail: string, barPx: number) => (
313 <Box flexDirection="row" alignItems="center">
314 <Box width={LABEL_CELLS} flexShrink={0}>
315 <Text>{name}</Text>
316 </Box>
317 {percent === null ? (
318 <Text dimColor>{'waiting for first response'}</Text>
319 ) : (
320 <Box flexDirection="row" alignItems="center" flexShrink={0}>
321 <Svg source={bar(percent, barPx)} alt={`${name} ${percent}% used`} width={barPx} height={8} />
322 <Box width={PERCENT_CELLS} justifyContent="flex-end">
323 <Text color={tone(percent)}>{`${percent}%`}</Text>
324 </Box>
325 </Box>
326 )}
327 <Box marginLeft={DETAIL_GAP} flexShrink={0}>
328 <Text dimColor>{detail}</Text>
329 </Box>
330 </Box>
331 )
332
333 // Fit the limit meters on one row: try "resets in 2h 8m", then "↻ 2h 8m", and stack them
334 // (the one case of 5 lines) only when even the short form leaves a bar under MIN_BAR_PX.
335 const availPx = e.props.bodyColumns * COL_PX * SPARE
336 const fixedPx = (LABEL_CELLS + PERCENT_CELLS + DETAIL_GAP) * CELL_PX
337 const n = Math.max(1, snap.limits.length)
338 const fit = (isLong: boolean) => {
339 const details = snap.limits.map(l => (l.resetsAt ? `${isLong ? 'resets in ' : '↻ '}${until(l.resetsAt, snap.at)}` : ''))
340 const textPx = details.reduce((sum, d) => sum + d.length * CHAR_PX, 0)
341 const barPx = Math.floor((availPx - n * fixedPx - (n - 1) * METER_GAP * CELL_PX - textPx) / n)
342 return { details, barPx: Math.min(MAX_BAR_PX, barPx) }
343 }
344 const long = fit(true)
345 const { details, barPx: sharedBar } = long.barPx >= MIN_BAR_PX ? long : fit(false)
346 const isStacked = sharedBar < MIN_BAR_PX
347 const longestPx = Math.max(0, ...details.map(d => d.length * CHAR_PX))
348 const limitBar = isStacked
349 ? Math.max(40, Math.min(MAX_BAR_PX, Math.floor(availPx - fixedPx - longestPx)))
350 : sharedBar
351 const used = snap.contextTokens === null ? '' : `${tokens(snap.contextTokens)} / ${tokens(snap.contextWindow)}`
352 const contextRoomPx = Math.floor(availPx - fixedPx - used.length * CHAR_PX)
353 const contextBar = Math.max(40, Math.min(isStacked ? limitBar : 2 * limitBar, contextRoomPx))
354
355 const where =
356 `📁 ${snap.dir}` +
357 (snap.branch === null ? '' : ` 🌿 ${snap.branch}${snap.isWorktree ? ' 🌳' : ''}`) +
358 `${snap.ahead ? ` ↑${snap.ahead}` : ''}${snap.behind ? ` ↓${snap.behind}` : ''}` +
359 `${snap.changed ? ` ● ${snap.changed} changed` : ''}`
360 const session =
361 `session ${ago(snap.at - snap.startedAt)} · ${snap.prompts} prompt${snap.prompts === 1 ? '' : 's'}` +
362 (snap.costUsd === null ? '' : ` · $${snap.costUsd.toFixed(2)}`)
363
364 // Bottom line parts: dim unless they need attention (warning) or are live (agents).
365 const activity: { text: string; emphasis?: 'warning' | 'live' }[] = []
366 const turn = await read($, lastTurn)
367 if (turn !== null && turn.at >= snap.startedAt) {
368 const idleMs = Math.max(0, snap.at - turn.at)
369 const isCold = idleMs >= cacheTtlMs
370 activity.push({ text: `Last turn ${elapsed(turn.durationMs)}${turn.model ? ` on ${turn.model}` : ''}` })
371 if (turn.cacheHit !== null) {
372 activity.push({ text: `cache ${turn.cacheHit}%`, emphasis: turn.cacheHit < 50 ? 'warning' : undefined })
373 }
374 // Older snapshots (before serverTools existed) carry none.
375 const used = Object.entries(turn.serverTools ?? {})
376 if (used.length > 0) activity.push({ text: `🔎 ${used.map(([n, k]) => `${n.replace(/_/g, ' ')} ×${k}`).join(', ')}` })
377 if (!e.props.isWorking) {
378 activity.push({ text: `idle ${ago(idleMs)}${isCold ? ' (cache cold)' : ''}`, emphasis: isCold ? 'warning' : undefined })
379 }
380 }
381 const c = await read($, compactions)
382 if (c !== null && c.since === snap.startedAt) {
383 const sizes = c.before === null || c.after === null ? '' : ` (last ${tokens(c.before)} → ${tokens(c.after)})`
384 activity.push({ text: `compacted ${c.count}×${sizes}` })
385 }
386 // Running agents get rows of their own (description truncated, type kept), so a
387 // long description never runs off the "Last turn" line.
388 const agentRows = snap.agents.slice(0, AGENT_ROWS)
389 const moreAgents = snap.agents.length - agentRows.length
390
391 return (
392 <Box flexDirection="column">
393 <Box flexDirection="row" justifyContent="space-between" width="100%">
394 <Text wrap="truncate-end">{where}</Text>
395 <Box marginLeft={2} flexShrink={0}>
396 <Text dimColor>{session}</Text>
397 </Box>
398 </Box>
399 {meter('Context', snap.contextPercent, used, contextBar)}
400 {snap.limits.length > 0 && (
401 <Box flexDirection={isStacked ? 'column' : 'row'} columnGap={METER_GAP}>
402 {snap.limits.map((l, i) => meter(label(l.kind), l.percent, details[i] ?? '', limitBar))}
403 </Box>
404 )}
405 {activity.length > 0 && (
406 <Box flexDirection="row">
407 {activity.map((a, i) => (
408 <Box flexDirection="row">
409 {i > 0 && <Text dimColor>{' · '}</Text>}
410 <Text
411 wrap="truncate-end"
412 color={a.emphasis === 'warning' ? 'warning' : undefined}
413 dimColor={a.emphasis === undefined}
414 >
415 {a.text}
416 </Text>
417 </Box>
418 ))}
419 </Box>
420 )}
421 {agentRows.map(a => (
422 <Box flexDirection="row" justifyContent="space-between" width="100%">
423 <Text wrap="truncate-end" dimColor={a.status !== 'running'}>
424 {`${AGENT_ICON[a.status] ?? '⏳'} ${a.description || a.type}`}
425 </Text>
426 <Box marginLeft={2} flexShrink={0}>
427 <Text dimColor>{a.type.split(':').pop()}</Text>
428 </Box>
429 </Box>
430 ))}
431 {(snap.runs ?? []).map(r => (
432 <Box flexDirection="row" justifyContent="space-between" width="100%">
433 <Text wrap="truncate-end">{`⚙ workflow ${r.runId} · ${r.active} active`}</Text>
434 <Box marginLeft={2} flexShrink={0}>
435 <Text dimColor={r.failed === 0} color={r.failed > 0 ? 'warning' : undefined}>
436 {`${r.done}/${r.total} done${r.failed > 0 ? ` · ${r.failed} failed` : ''}`}
437 </Text>
438 </Box>
439 </Box>
440 ))}
441 {moreAgents > 0 &&<Text dimColor>{` +${moreAgents} more agent${moreAgents > 1 ? 's' : ''} running`}</Text>}
442 </Box>
443 )
444 })
445}
446types/index.d.ts 54 lines1export type Limit = { kind: string; percent: number; resetsAt: string | null }
2
3export type Agent = {
4 type: string
5 description: string
6 status: 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
7}
8
9export type WorkflowRun = { runId: string; total: number; active: number; done: number; failed: number }
10
11export type Snapshot = {
12 at: number
13 startedAt: number
14 prompts: number
15 dir: string
16 branch: string | null
17 isWorktree: boolean
18 ahead: number
19 behind: number
20 changed: number
21 contextPercent: number | null
22 contextTokens: number | null
23 contextWindow: number
24 costUsd: number | null
25 limits: Limit[]
26 agents: Agent[]
27 runs: WorkflowRun[]
28}
29
30export type TurnStat = {
31 at: number
32 durationMs: number
33 model: string | null
34 cacheHit: number | null
35 serverTools: Record<string, number>
36}
37
38export type Compactions = { since: number; count: number; before: number | null; after: number | null }
39
40declare module 'claude-code' {
41 interface PluginState {
42 'desktop-statusline': {
43 snap: Snapshot | null
44 warned: string[]
45 lastTurn: TurnStat | null
46 compactions: Compactions | null
47 // Workflow runs by run id, from `agent.spawn` and each agent's own `turn.complete`
48 // (`$.agent.list()` leaves workflow agents out): when last touched, finished counts, and the
49 // agents still out, each with its spawn time.
50 runTally: Record<string, { at: number; done: number; failed: number; active: Record<string, number> }>
51 }
52 }
53}
54