A box above the prompt that says what Claude is doing right now (reading, thinking, running a tool, waiting for you) in tail-claude-hud's icons and colors, and…

A box above the Claude Code prompt that says what Claude is doing right now, drawn with tail-claude-hud's icons and colors. Press the triangle to see every step it has taken.
╭────────────────────────────────────────────────────────────────╮
│ ▾ Idle · last turn done in 12s, 2 actions │
│ │
│ › Run the shell command `sleep 5 && echo done` with the Bash … │
│ Read VERSION 0.4s │
│ Wait five seconds 5.7s │
│ Wrote the reply (11 words) <0.1s │
│ Done in 12s, 2 actions │
╰────────────────────────────────────────────────────────────────╯
It is a Claude Code mod: a plugin of function hooks, which are early access and load only where function hooks are enabled. It replaces whats-agent-doing with the same states and history, restyled to match the statusline.
/plugin install tch-activity --marketplace kylesnowschwartz/tail-claude-hud
Answer y to add the marketplace, then pick a scope. If whats-agent-doing is installed too, disable it (claude plugin disable whats-agent-doing@tzafrir) or both boxes stack above the prompt.
At session start the mod runs tail-claude-hud style --json once, in the background, and keeps the answer for the session; the box draws with the built-in look until the answer arrives. That output carries the HUD's resolved icons (Nerd Font, unicode or ascii, per your [style] icons), its semantic colors, the agent palette and the tool categories, so the box draws with whatever your HUD config draws with.
The binary is found in this order:
binary option (/plugin → tch-activity → configure, or pluginConfigs."tch-activity".options.binary in settings).~/go/bin/tail-claude-hud, where go install puts it. A Claude Code session runs with the login PATH, which often lacks Go's bin folder.tail-claude-hud on the session's PATH.If your statusLine command passes --preset (for example tail-claude-hud --preset powerline), set the preset option to the same value so the box reads the same look. The HUD's automatic light theme for powerline layouts on a light terminal background is not part of the export.
The box uses the HUD's state colors (running, thinking, needs you, success, error, muted) and its agent palette. The per-widget colors in your theme file (theme-active.toml) are not used.
If the binary is missing, too old to have style --json, or prints something unreadable, the box draws with a built-in unicode look (✓ ✗ ⧗ ≡ $ ◆ ∴ ❝) in the HUD's default colors. Its icons are the HUD's own icons = "unicode" set: one-column symbols, no emoji (see Style). The expanded history then ends with one dim line saying why. Nothing else is reported. The mod asks again after a reload or an option change, so a newer binary is picked up without a new session.
| State | Headline | ||
|---|---|---|---|
| Before any turn | Idle, waiting for your prompt (clock icon, muted) | ||
| Reading the prompt | Reading your prompt | ||
| Thinking | Thinking: …the hook needs to await next (the thought's latest sentence), or, while none has streamed, the turn's last action under the thinking icon ( Reading app.ts), Reading your prompt before there is one | ||
| Writing a tool call | the turn's last action under the running icon ( Preparing the next action before there is one) until the call's input says what it does, then Run the tests, ` Writing register.tsx \ | 2.3 KB` | |
| Running a tool | the tool's category icon in the running color, then its label: Wait five seconds, Reading app.ts, Fetching example.org | ||
| Parallel calls | the newest, then (+N more) | ||
| A subagent at work | ` Running an agent: find the bug \ | Reading app.ts` | |
| Background agents | 2 agents working, and a row per agent under the headline label: ` Draft the plan \ | Searching the web \ | 1m 12s`. Each agent's icon and name take the color the HUD's agents widget gives it: its Agent call's position among the session's last 10, wrapped at the palette's 8 colors. |
| Waiting on you | Waiting for your approval: Run the tests, Waiting for your answer (permission icon and color). In the terminal the approval dialog takes the band's place while it is up; a subagent's row says it waits until its call runs. | ||
| Between calls | the turn's last action under the running icon: Reading app.ts | ||
| Writing the reply | ` Writing the reply \ | 120 words` | |
| Compacting | Compacting the conversation | ||
| Between turns | Idle · last turn done in 42s, 6 actions, or interrupted, stopped on an error, declined the request, stopped at a declined call; the glyph is the turn's outcome |
Labels are drawn in the default text color. A state's color is on its glyph and on the border: yellow while Claude works or thinks, red while it or a subagent waits on you, muted grey when idle. Numbers, timers and separators are faint. A timer after the label (| 4.2s) counts how long the current state has lasted, in tenths of a second under ten seconds; a tool's timer leaves out the time its approval dialog was up. While a turn runs, the turn's total time in whole seconds is drawn faint just right of the box, on the headline's line (│ · 1m 12s). It leaves out the time Claude waited on your approval or answer, as the turn's closing Done in time does, and is left off when the band has no room for it beside the box. The box widens to fit its widest row and keeps that width until the turn ends, then shrinks to fit what it shows between turns: the idle headline, any agents still at work, and the history when it is open.
Focus the band with ctrl+x tab and press Enter, or click the triangle, to expand the history: each prompt (›), stretch of thinking, tool call, reply and turn ending, with durations. A tool row is in the past tense and has one glyph, as the HUD's tools widget draws a finished tool: the tool's category icon in the success color, or the error color when it failed, as in Read VERSION 0.4s. A call you declined shows the HUD's declined icon and an interrupted one its interrupted icon (⊘ and ■ in the unicode set, both muted) in place of the category icon, so those rows never rely on color alone. A question to you shows the bell, and an agent's row the robot, under the same rule. Thought, reply and compaction (⇣) icons are faint. A background agent gets a Started an agent: row when it is launched and a Ran an agent: row when it finishes. The turn's last row says how it ended with its time in the label, Done in 12s, 2 actions, or ⊘ Stopped at a declined call after 7.1s when its last call was one you declined. A prompt the engine sends for you (<agent-message …>, <task-notification>) is listed by its tag, Agent message.
The box steps aside while a survey holds the band. Other mods that draw above the prompt keep their place beneath it.
In the terminal the mod hides Claude Code's spinner line (✶ Ionizing… (13s · ↓ 574 tokens)), with the task list, tips and API retry notices drawn under it. Set the hideSpinner option to false to keep it.
The mod runs one local command (tail-claude-hud style --json) when a session starts, and again after a reload while the HUD's look is not in place; it reads HOME to find the binary. It keeps its headline, history and look in the session's own state ($.state). It makes no network calls.
It writes one file: while a call of the main conversation waits on your approval, ~/.config/tail-claude-hud/waiting/<session id> holds the session id, the working folder's name and the tool's name, the file the HUD's hook permission-request writes. Other sessions' status lines read it to show that this one waits on you. The mod removes it, by running /bin/rm -f on that path, as soon as you approve or decline the call and when the session ends or is cleared. A file it fails to remove is ignored by the HUD after ten minutes.
Every hook passes its event on unchanged; it never answers a permission prompt.
The box shows your prompts, file names, URLs, command descriptions (or the command when it has none), MCP tool names and a line of the model's thinking where it streams. Labels are cleaned of control and invisible characters before they are drawn.
From the repository root:
just mod-dev # claude with this folder loaded (hot-reloads on save), whats-agent-doing off for the session
just mod-check # validate (mod and marketplace), run the tests, typecheck
just mod-dev builds this checkout's HUD binary to a temporary folder and points the mod at it, and passes --settings with "enabledPlugins":{"whats-agent-doing@tzafrir":false}, which turns an installed whats-agent-doing off for that session alone. Set TCH_HUD_BINARY=/path/to/tail-claude-hud to use another HUD binary. Loading the mod writes the API's types to .claude-plugin/types/ (git-ignored), which tsconfig.json extends. just mod-check typechecks only once that has happened; until then it validates and runs the tests, prints type check skipped: run 'just mod-dev' once to write the API types, and exits 0.
QA.md is a scripted checklist for driving the mod in tmux.
| File | What it does |
|---|---|
hooks/register.tsx | The hooks module: every hook, every function that takes $, the state atoms, the style load and the drawing. The engine follows $ and state references only within this file. |
hooks/live.ts | The live view of the session and the headline it yields (pure) |
hooks/marks.ts | The glyph and color for each state, outcome and history row (pure) |
hooks/style.ts | The built-in look, parsing style --json, and icon and color lookups (pure) |
hooks/activity-of.ts | A tool call, whole or streaming, as a short label |
hooks/text.ts | Printable labels, thought snippets, word counts, sizes, durations |
hooks/waiting.ts | The approval breadcrumb's path and contents (pure) |
types/index.d.ts | The $.state contract |
tests/ | The turn state by state, the history toggle, hostile labels, approvals, agents and their palette, the HUD look and its fallback |
MIT. Portions are adapted from whats-agent-doing by Tzafrir Rehan (MIT); see NOTICE.
hooks/register.tsx 1339 lines1// The tracking hooks are adapted from whats-agent-doing's register.tsx (MIT,
2// Copyright (c) 2026 Tzafrir Rehan); see NOTICE. The engine traces `$` and
3// state references only within the hooks module's own file, so every function
4// that takes `$` and every state atom lives here; the other files are pure.
5import { atom, read, update } from 'claude-code'
6import type {
7 AgentInfo,
8 EngineInterface,
9 PluginOptions,
10 Register,
11 RenderInput,
12 TurnStepChunk,
13} from 'claude-code'
14
15import type { ActivityAgent, ActivityEntry, ActivityOutcome, BoxWidth, TchStyle, TchStyleSource } from '../types'
16import { activityOf, isAgentTool } from './activity-of'
17import {
18 agentLabel,
19 callOf,
20 colorIndexOf,
21 createLive,
22 current,
23 dropMainCalls,
24 endWait,
25 entryOf,
26 IDLE,
27 isAgentWaiting,
28 outcomeOf,
29 pauseTurn,
30 QUESTION_TOOL,
31 resumeTurn,
32 STARTING_LABEL,
33 startTurn,
34 turnClockOf,
35 turnEndLabel,
36 turnEndOf,
37 turnTotalOf,
38 UNNAMED_AGENT,
39 type Agent,
40 type Call,
41 type Live,
42 type ModelPhase,
43 withAgentCall,
44 withAgentKey,
45} from './live'
46import { AGENT_INDENT_COLUMNS, bandLayout, boxColumnsOf, columnsOf, type Segment } from './layout'
47import { borderColor, entryMark, headlineMark, styleNote } from './marks'
48import {
49 agentColor,
50 BARE_BINARY,
51 BUILTIN_STYLE,
52 builtin,
53 GO_BIN_SUFFIX,
54 icon,
55 isStyleStale,
56 parseStyle,
57 type LoadedStyle,
58} from './style'
59import { breadcrumbOf, waitingPathOf } from './waiting'
60import {
61 capitalized,
62 durationOf,
63 elapsedOf,
64 oneLine,
65 TENTHS_UNDER_MS,
66 plural,
67 printable,
68 promptLabel,
69 wholeElapsedOf,
70 wordsAdded,
71} from './text'
72
73/** The headline. */
74const now = atom({ plugin: 'tch-activity', key: 'now' } as const, IDLE)
75
76/** The expanded box's rows, oldest first. */
77const history = atom(
78 { plugin: 'tch-activity', key: 'history' } as const,
79 [] as readonly ActivityEntry[],
80)
81
82/** The subagents at work, in the order they were met. */
83const team = atom(
84 { plugin: 'tch-activity', key: 'agents' } as const,
85 [] as readonly ActivityAgent[],
86)
87
88/** The Agent calls (or agent ids) whose position picks each agent's color. */
89const agentOrder = atom({ plugin: 'tch-activity', key: 'agentOrder' } as const, [] as readonly string[])
90
91/** How the last main turn ended, for the idle headline after a reload. */
92const lastTurn = atom(
93 { plugin: 'tch-activity', key: 'lastTurn' } as const,
94 null as { label: string; outcome: ActivityOutcome } | null,
95)
96
97const isExpanded = atom({ plugin: 'tch-activity', key: 'isExpanded' } as const, false)
98
99/**
100 * The widest the box has been since the last turn ended, in columns: it grows
101 * to fit, and a turn's end sets it back to 0 so the box fits what it shows.
102 * `turnEnds` counts those resets, so a width a draw measured before one is
103 * not kept after it.
104 */
105const boxWidth = atom(
106 { plugin: 'tch-activity', key: 'boxWidth' } as const,
107 { columns: 0, turnEnds: 0 } as BoxWidth,
108)
109
110/** The HUD's look, loaded once per session; `null` until then. */
111const styleState = atom({ plugin: 'tch-activity', key: 'style' } as const, null as TchStyle | null)
112
113const styleSource = atom(
114 { plugin: 'tch-activity', key: 'styleSource' } as const,
115 null as TchStyleSource | null,
116)
117
118/**
119 * Registers tch-activity: a box above the prompt naming what Claude is doing
120 * right now in tail-claude-hud's icons and colors, and, behind its triangle,
121 * what it has done.
122 *
123 * The model's stream (`turn.step`) says whether it is reading, thinking,
124 * writing the reply or composing a tool's input; `tool.call` which tool
125 * runs; `tool.check` when one is put to approval; `session.compact` when
126 * the conversation compacts; a subagent's calls carry its `agentId`. Every hook is display only: it reads
127 * its event and passes it on unchanged, but for the terminal's spinner line,
128 * which the box stands in for.
129 *
130 * @param on the engine's registrar
131 * @param options `userConfig` values; `binary` names the tail-claude-hud
132 * binary, `preset` its preset, `hideSpinner` whether the spinner line is hidden
133 */
134export const register: Register = (on, options) => {
135 const live = createLive()
136 const asked: StyleAsked = { isAsked: false, options }
137 /** Whether the terminal's last band draw drew the box. */
138 const band = { isBoxDrawn: true }
139
140 on('session.start', async ($, e, next) => {
141 const result = await next(e)
142
143 ensureStyle($, asked)
144 await publish($, live)
145
146 return result
147 })
148
149 on('turn.start', async ($, e, next) => {
150 // A module loaded after the session started (a plugin folder added or
151 // edited mid-session) saw no `session.start`: its first turn loads the look.
152 ensureStyle($, asked)
153
154 // A prompt folded into a running turn starts no new one.
155 if (live.turnStartMs !== null) {
156 return next(e)
157 }
158
159 startTurn(live, await $.clock.now())
160 live.turnActions = 0
161 live.isDeclinedLast = false
162 live.isFirstRequest = true
163 live.resultsToReview = 0
164 live.lastAction = null
165 dropMainCalls(live)
166
167 const prompt = promptLabel(e.text, MAX_PROMPT_CHARS)
168
169 if (prompt !== '') {
170 await remember($, entryOf('turn', prompt))
171 }
172
173 await enter($, live, 'requesting')
174
175 keepTicking($, live)
176 await publish($, live)
177
178 return next(e)
179 })
180
181 on('turn.step', async function* ($, e, next) {
182 if (e.agentId !== undefined) {
183 return yield* next(e)
184 }
185
186 // A module reloaded mid-turn missed the turn's start: it takes the turn
187 // up here, so the turn's end returns the box to idle.
188 if (live.turnStartMs === null) {
189 startTurn(live, await $.clock.now())
190 keepTicking($, live)
191 }
192
193 await enter($, live, 'requesting')
194 await publish($, live)
195
196 try {
197 for await (const chunk of next(e)) {
198 await follow($, live, chunk)
199 yield chunk
200 }
201 } finally {
202 live.isFirstRequest = false
203 live.composing = null
204 await enter($, live, 'requesting')
205 await publish($, live)
206 }
207 })
208
209 on('tool.call', async ($, e, next) => {
210 const args = e as unknown as Record<string, unknown>
211 const label = activityOf(e.tool, args)
212
213 if (e.agentId !== undefined) {
214 const agent = await agentOf($, live, e.agentId)
215 const startMs = await $.clock.now()
216
217 // Kept after the call: the agent's last action stands while it thinks.
218 agent.label = label
219 agent.activeMs = startMs
220 live.calls.set(e.tool_use_id, callOf(e.tool, label, startMs, e.agentId))
221 await publish($, live, false)
222
223 try {
224 return await next(e)
225 } finally {
226 live.calls.delete(e.tool_use_id)
227 await publish($, live, false)
228 }
229 }
230
231 const startMs = await $.clock.now()
232
233 if (isAgentTool(e.tool)) {
234 await rememberAgentKey($, live, e.tool_use_id)
235 }
236
237 const call = callOf(e.tool, label, startMs, null)
238
239 live.calls.set(e.tool_use_id, call)
240
241 if (e.tool === QUESTION_TOOL) {
242 pauseTurn(live, startMs)
243 }
244
245 // Kept after the call: the turn's last action stands while the model works.
246 live.lastAction = label
247 live.turnActions += 1
248 await publish($, live)
249
250 // A call that never settles (the turn was interrupted) keeps this.
251 let outcome: ActivityOutcome = 'interrupted'
252 let done = activityOf(e.tool, args, 'past')
253
254 try {
255 const result = await next(e)
256
257 outcome = result.deny !== undefined ? 'denied' : result.isError ? 'error' : 'ok'
258
259 if (isAgentTool(e.tool)) {
260 const handle = args['name']
261 const description = args['description']
262
263 // A named agent runs as a teammate, which the engine lists by the
264 // call's `name`; the call's `description` is what to show for it.
265 if (typeof handle === 'string' && typeof description === 'string' && oneLine(description) !== '') {
266 live.described.set(handle, description)
267 void sweep($, live)
268 }
269
270 if (await launched($, live, result.result, description, e.tool_use_id)) {
271 done = `Started an agent: ${typeof description === 'string' ? oneLine(description) : ''}`
272 }
273 }
274
275 return result
276 } finally {
277 // A call put to approval that errors without ever being seen running
278 // was refused by its decider, which the engine reports as an error.
279 if (outcome === 'error' && call.askedMs !== null) {
280 outcome = 'denied'
281 }
282
283 // Decided before it was taken for a dialog: no wait of yours to leave out.
284 if (!call.isPutToYou) {
285 call.askedMs = null
286 }
287
288 // Still waiting as it ends: the dialog was declined or the turn stopped.
289 if (call.isAwaitingApproval) {
290 clearWaiting($, live, call)
291 }
292
293 const endMs = await $.clock.now()
294
295 endWait(call, endMs)
296 live.calls.delete(e.tool_use_id)
297 resumeTurn(live, endMs)
298 live.resultsToReview += 1
299 live.isDeclinedLast = outcome === 'denied'
300
301 await remember($, {
302 ...entryOf('tool', done, outcome),
303 durationMs: endMs - startMs - call.waitedMs,
304 tool: e.tool,
305 })
306
307 await publish($, live)
308 }
309 })
310
311 // An `ask` verdict puts the call to the mode's decider: the person's
312 // dialog, or the auto-mode classifier. Display only: the verdict passes on
313 // unchanged.
314 on('tool.check', async ($, e, next) => {
315 const verdict = await next(e)
316 const call = e.tool_use_id === undefined ? undefined : live.calls.get(e.tool_use_id)
317
318 if (verdict.decision === 'ask' && call !== undefined && call.askedMs === null && !call.isAwaitingApproval) {
319 call.askedMs = await $.clock.now()
320 $.clock.after(DIALOG_GRACE_MS, () => void putToYou($, live, call))
321 }
322
323 return verdict
324 }).catch(($, e, next) => next(e))
325
326 // A call's row is drawn running once it runs, or at once when a decider
327 // other than the dialog (the auto-mode classifier) reviews it: for a call
328 // that waited on you, it means you approved it.
329 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
330 if (e.props.isRunning) {
331 await approved($, live, e.props.tool_use_id)
332 }
333
334 return next(e)
335 })
336
337 // The run-in-background pill shows only under a running call: the same sign.
338 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
339 await approved($, live, e.props.tool_use_id)
340
341 return next(e)
342 })
343
344 // The box says what the turn does and for how long, so the terminal's
345 // spinner line draws nothing in its place. A Spinner is drawn for the
346 // conversation in view, the main one or an agent's, and the box shows both.
347 // A render hook answers a tree, never null: an empty Box draws nothing.
348 on('ui.render', { component: 'Spinner' }, ($, e, next) => {
349 if (e.surface !== 'terminal' || !isSpinnerHidden(options) || !band.isBoxDrawn) {
350 return next(e)
351 }
352
353 const { Box } = $.ui.resolve(e)
354
355 return <Box />
356 }).catch(($, e, next) => next(e))
357
358 on('agent.spawn', async ($, e, next) => {
359 const result = await next(e)
360
361 if (result.agentId !== undefined) {
362 const startMs = await $.clock.now()
363 const name = e.description || e.name || UNNAMED_AGENT
364
365 live.agentNames.set(result.agentId, name)
366 live.agents.set(result.agentId, {
367 name,
368 label: STARTING_LABEL,
369 startMs,
370 activeMs: startMs,
371 toolUseId: e.tool_use_id,
372 isBackground: e.background,
373 colorKey: e.tool_use_id || result.agentId,
374 })
375 await placeAgent($, live, result.agentId, e.tool_use_id)
376 keepTicking($, live)
377 await publish($, live)
378 }
379
380 return result
381 })
382
383 // A compaction of the main conversation, timed from the call to its
384 // answer. One made ahead of time (`precompute`) runs unseen in the
385 // background and is not shown.
386 on('session.compact', async ($, e, next) => {
387 if (e.agentId !== undefined || e.trigger === 'precompute') {
388 return next(e)
389 }
390
391 await enter($, live, 'compacting')
392 keepTicking($, live)
393 await publish($, live)
394
395 let outcome: ActivityOutcome = 'error'
396
397 try {
398 const result = await next(e)
399
400 outcome = result.skip === undefined ? 'ok' : 'denied'
401
402 return result
403 } finally {
404 const durationMs = (await $.clock.now()) - live.phaseStartMs
405 const label = outcome === 'ok' ? 'Compacted the conversation' : outcome === 'denied' ? 'Compaction skipped' : 'Compaction failed'
406
407 await enter($, live, live.turnStartMs === null ? 'idle' : 'requesting')
408 await remember($, { ...entryOf('compact', label, outcome), durationMs })
409 keepTicking($, live)
410 await publish($, live)
411 }
412 })
413
414 // Every end, a /clear's included, takes the ending session's breadcrumb
415 // with it; a /clear's new session id is not the one that waited.
416 on('session.end', async ($, e, next) => {
417 clearWaiting($, live, null, e.sessionId)
418
419 return next(e)
420 })
421
422 on('turn.complete', async ($, e, next) => {
423 if (e.agentId !== undefined) {
424 await finish($, live, e.agentId, outcomeOf(e.reason))
425
426 return next(e)
427 }
428
429 const clock = turnClockOf(live)
430
431 if (clock === null) {
432 await shrinkBox($)
433
434 return next(e)
435 }
436
437 const durationMs = turnTotalOf(clock, await $.clock.now())
438 const end = turnEndOf(e.reason, live.isDeclinedLast)
439 const outcome = outcomeOf(end)
440 const label = turnEndLabel(end, durationMs, live.turnActions)
441
442 await enter($, live, 'idle')
443 // The row says its time in its label, so it has no duration of its own.
444 await remember($, entryOf('end', capitalized(label), outcome))
445
446 live.lastTurn = { label, outcome }
447 await update($, lastTurn, () => live.lastTurn)
448 live.turnStartMs = null
449 dropMainCalls(live)
450
451 keepTicking($, live)
452 await publish($, live)
453 // After the idle headline is out: a draw before it measured the working one.
454 await shrinkBox($)
455
456 return next(e)
457 })
458
459 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
460 const isBoxDrawn = !e.props.hasSurvey
461
462 // The spinner line is hidden only while the box stands in for it.
463 if (e.surface === 'terminal' && isBoxDrawn !== band.isBoxDrawn) {
464 band.isBoxDrawn = isBoxDrawn
465 $.clock.after(0, () => $.ui.invalidate('ui.render'))
466 }
467
468 if (!isBoxDrawn) {
469 return next(e)
470 }
471
472 // A reload (an edit, a changed option) sees no session start: the first
473 // draw after it checks the look, off the draw.
474 ensureStyle($, asked)
475
476 // The band is one site for every plugin: what the plugins beneath draw
477 // stays, under the box, so another mod's band is never hidden.
478 const below = await next(e)
479 const { Box } = $.ui.resolve(e)
480
481 return (
482 <Box flexDirection="column">
483 {await drawBox($, e)}
484 {below}
485 </Box>
486 )
487 })
488}
489
490const MAX_HISTORY = 100
491
492const MAX_PROMPT_CHARS = 60
493
494const MAX_THOUGHT_BUFFER = 2000
495
496const MAX_INPUT_HEAD = 4000
497
498/** Streaming chunks arrive far faster than anyone reads; publish at most this often. */
499const STREAM_THROTTLE_MS = 250
500
501/** The running timer shows tenths under ten seconds; the box redraws this often then. */
502const TICK_MS = 100
503
504/** Past ten seconds the timer counts whole seconds: the box redraws, and checks on agents, once a second. */
505const TICKS_PER_SECOND = 10
506
507/**
508 * Writes the headline. A streaming update (`isUrgent` false) lands at most
509 * every STREAM_THROTTLE_MS, the last one held on a timer.
510 */
511async function publish($: EngineInterface, live: Live, isUrgent = true): Promise<void> {
512 const nowMs = await $.clock.now()
513
514 if (!isUrgent && nowMs - live.lastPublishMs < STREAM_THROTTLE_MS) {
515 live.trailing ??= $.clock.after(STREAM_THROTTLE_MS, () => {
516 live.trailing = null
517 void publish($, live)
518 })
519
520 return
521 }
522
523 live.lastPublishMs = nowMs
524 await restore($, live)
525
526 const headline = current(live)
527 const working: ActivityAgent[] = [...live.agents.entries()].map(([id, agent]) => ({
528 name: agent.name,
529 label: agentLabel(live, { ...agent, id }),
530 sinceMs: agent.startMs,
531 colorIndex: colorIndexOf(live, agent.colorKey),
532 isWaiting: isAgentWaiting(live, id),
533 }))
534
535 await update($, now, () => headline)
536 await update($, team, () => working)
537}
538
539/**
540 * Takes up, once per module load, what the session's state kept across a
541 * reload: the agent order and how the last turn ended.
542 */
543async function restore($: EngineInterface, live: Live): Promise<void> {
544 if (live.isRestored) {
545 return
546 }
547
548 live.isRestored = true
549 live.agentOrder = await read($, agentOrder)
550 live.lastTurn ??= await read($, lastTurn)
551}
552
553/** Adds an agent to the order that picks its color, as the HUD's agents widget orders it. */
554async function rememberAgentKey($: EngineInterface, live: Live, key: string): Promise<void> {
555 await restore($, live)
556
557 const order = withAgentKey(live.agentOrder, key)
558
559 if (order !== live.agentOrder) {
560 live.agentOrder = order
561 await update($, agentOrder, () => order)
562 }
563}
564
565/**
566 * Places an agent in the color order by its Agent call, dropping the entry
567 * its id took if its own calls arrived first.
568 */
569async function placeAgent($: EngineInterface, live: Live, agentId: string, toolUseId: string): Promise<void> {
570 await restore($, live)
571
572 const order = toolUseId === '' ? withAgentKey(live.agentOrder, agentId) : withAgentCall(live.agentOrder, agentId, toolUseId)
573
574 if (order.join('\n') !== live.agentOrder.join('\n')) {
575 live.agentOrder = order
576 await update($, agentOrder, () => order)
577 }
578}
579
580/**
581 * Marks a call that waited on approval as approved, once it is seen running:
582 * the dialog has closed, and the call's timer counts from here.
583 */
584async function approved($: EngineInterface, live: Live, toolUseId: string): Promise<void> {
585 const call = live.calls.get(toolUseId)
586
587 // Drawn running within the grace: no dialog is up, the decider's time is the call's.
588 if (call !== undefined && call.askedMs !== null && !call.isPutToYou) {
589 call.askedMs = null
590
591 return
592 }
593
594 if (call?.isAwaitingApproval) {
595 call.isAwaitingApproval = false
596
597 if (call.agentId === null) {
598 clearWaiting($, live, call)
599 }
600
601 // The wait ends now, before the call can: a fast tool's end must find it closed.
602 const nowMs = await $.clock.now()
603
604 endWait(call, nowMs)
605 resumeTurn(live, nowMs)
606
607 // Drawing may not write state: the headline is published just after.
608 $.clock.after(0, () => void publish($, live))
609 }
610}
611
612/**
613 * How long a call put to approval may go undrawn before the box takes it for
614 * the dialog. The engine draws a call running at once when a decider other
615 * than the dialog (the auto-mode classifier, a host) reviews it, and only
616 * after you answer when the dialog asks you.
617 */
618const DIALOG_GRACE_MS = 250
619
620/**
621 * Takes a call still asked and undrawn after the grace as waiting on you:
622 * the headline and border say so and, for the main loop, the breadcrumb is
623 * written.
624 */
625async function putToYou($: EngineInterface, live: Live, call: Call): Promise<void> {
626 const isInFlight = [...live.calls.values()].includes(call)
627
628 if (!isInFlight || call.askedMs === null || call.isAwaitingApproval) {
629 return
630 }
631
632 call.isAwaitingApproval = true
633 call.isPutToYou = true
634
635 if (call.agentId === null) {
636 // From now, not from when it was asked: the total already shown never goes back.
637 pauseTurn(live, await $.clock.now())
638 await markWaiting($, call.tool)
639 }
640
641 await publish($, live)
642}
643
644/**
645 * Writes this session's approval breadcrumb, which other sessions' HUD
646 * status lines show as an alert. A failure is let go: the HUD ignores a
647 * breadcrumb past its staleness limit.
648 */
649async function markWaiting($: EngineInterface, tool: string): Promise<void> {
650 try {
651 const home = await $.env.get('HOME')
652
653 if (home === undefined || home === '') {
654 return
655 }
656
657 const sessionId = await $.session.id()
658
659 await $.fs.write(waitingPathOf(home, sessionId), breadcrumbOf(sessionId, await $.session.cwd(), tool))
660 } catch {
661 // The HUD's staleness limit retires a breadcrumb that never lands.
662 }
663}
664
665/** `rm` answers at once; this bounds a stuck one. */
666const REMOVE_TIMEOUT_MS = 1500
667
668/**
669 * Removes a session's approval breadcrumb, unless another main-loop call
670 * besides `ending` still waits. The session is `sessionId`, or the current
671 * one, read fresh since a /clear changes it. The removal runs just after:
672 * inside a declined call's chain the engine aborts `$` calls. `$.fs` has no
673 * delete, so `/bin/rm -f` removes the file; a failure is let go, as the HUD
674 * ignores a breadcrumb past its staleness limit.
675 */
676function clearWaiting($: EngineInterface, live: Live, ending: Call | null, sessionId?: string): void {
677 const isStillWaiting = [...live.calls.values()]
678 .some(call => call !== ending && call.agentId === null && call.isAwaitingApproval)
679
680 if (sessionId === undefined && isStillWaiting) {
681 return
682 }
683
684 $.clock.after(0, async () => {
685 try {
686 const home = await $.env.get('HOME')
687
688 if (home === undefined || home === '') {
689 return
690 }
691
692 const path = waitingPathOf(home, sessionId ?? (await $.session.id()))
693
694 await $.process.run(['/bin/rm', '-f', path], { timeoutMs: REMOVE_TIMEOUT_MS })
695 } catch {
696 // The HUD's staleness limit retires a breadcrumb left behind.
697 }
698 })
699}
700
701/** The agent at work under `agentId`, taken up if its spawn came before a reload. */
702async function agentOf($: EngineInterface, live: Live, agentId: string): Promise<Agent> {
703 const known = live.agents.get(agentId)
704
705 if (known) {
706 return known
707 }
708
709 const startMs = await $.clock.now()
710 const agent: Agent = {
711 name: live.agentNames.get(agentId) ?? UNNAMED_AGENT,
712 label: STARTING_LABEL,
713 startMs,
714 activeMs: startMs,
715 toolUseId: null,
716 isBackground: true,
717 colorKey: agentId,
718 }
719
720 live.agents.set(agentId, agent)
721 await rememberAgentKey($, live, agentId)
722 keepTicking($, live)
723
724 return agent
725}
726
727/**
728 * Lets an agent go. A background agent's run is recorded in the history; a
729 * foreground one's is its Agent call's row.
730 */
731async function finish(
732 $: EngineInterface,
733 live: Live,
734 agentId: string,
735 outcome: ActivityOutcome,
736): Promise<void> {
737 const agent = live.agents.get(agentId)
738
739 if (!agent) {
740 return
741 }
742
743 live.agents.delete(agentId)
744
745 if (agent.isBackground) {
746 await remember($, {
747 ...entryOf('tool', `Ran an agent: ${agent.name}`, outcome),
748 durationMs: (await $.clock.now()) - agent.startMs,
749 tool: 'Agent',
750 })
751 }
752
753 keepTicking($, live)
754 await publish($, live)
755}
756
757/**
758 * Names agents first met by their calls, and lets go of agents the engine
759 * lists as no longer running, in case their stop never reached the box.
760 */
761async function sweep($: EngineInterface, live: Live): Promise<void> {
762 if (live.agents.size === 0 || live.isSweeping) {
763 return
764 }
765
766 live.isSweeping = true
767
768 try {
769 await sweepListed($, live, await $.agent.list())
770 } catch {
771 // The list is a backstop; the box keeps going without it.
772 } finally {
773 live.isSweeping = false
774 }
775}
776
777async function sweepListed($: EngineInterface, live: Live, listed: readonly AgentInfo[]): Promise<void> {
778 const statuses = new Map(listed.map(info => [info.id, info.status]))
779 let isRenamed = false
780
781 for (const [agentId, agent] of [...live.agents.entries()]) {
782 const status = statuses.get(agentId)
783
784 // An agent first met by its calls is named once the engine lists it.
785 if (!live.agentNames.has(agentId)) {
786 const handle = listed.find(info => info.id === agentId)?.name
787 const described = handle === undefined ? undefined : live.described.get(handle)
788
789 if (described !== undefined) {
790 live.agentNames.set(agentId, described)
791 }
792
793 const name = described ?? handle
794
795 if (name !== undefined && name !== agent.name) {
796 agent.name = name
797 isRenamed = true
798 }
799 }
800
801 if (status !== undefined && status !== 'running') {
802 await finish($, live, agentId, status === 'completed' ? 'ok' : status === 'failed' ? 'error' : 'interrupted')
803 }
804 }
805
806 if (isRenamed) {
807 await publish($, live)
808 }
809}
810
811/**
812 * Keeps the elapsed time ticking while a turn runs, an agent works or the
813 * conversation compacts, and stops it once none does.
814 */
815function keepTicking($: EngineInterface, live: Live): void {
816 const isBusy = live.turnStartMs !== null || live.agents.size > 0 || live.phase === 'compacting'
817
818 if (isBusy && live.ticker === null) {
819 let ticks = 0
820
821 live.ticker = $.clock.every(TICK_MS, async () => {
822 ticks += 1
823
824 const isWholeSecond = ticks % TICKS_PER_SECOND === 0
825
826 if (isWholeSecond) {
827 void sweep($, live)
828 }
829
830 if (isWholeSecond || hasTenthsTimer(live, await $.clock.now())) {
831 $.ui.invalidate('ui.render')
832 }
833 })
834 } else if (!isBusy && live.ticker !== null) {
835 live.ticker.cancel()
836 live.ticker = null
837 }
838}
839
840/** Whether a timer the box draws is still under ten seconds, and so shows tenths. */
841function hasTenthsTimer(live: Live, nowMs: number): boolean {
842 const headline = current(live)
843 const starts = [...live.agents.values()].map(agent => agent.startMs)
844
845 if (headline.phase !== 'idle') {
846 starts.push(headline.sinceMs)
847 }
848
849 return starts.some(startMs => nowMs - startMs < TENTHS_UNDER_MS)
850}
851
852/**
853 * Lets the box shrink to fit what it shows, as a turn ends: the width the turn
854 * grew to is dropped, with any a draw measured before now.
855 */
856async function shrinkBox($: EngineInterface): Promise<void> {
857 await update($, boxWidth, width => ({ columns: 0, turnEnds: width.turnEnds + 1 }))
858}
859
860async function remember($: EngineInterface, entry: ActivityEntry): Promise<void> {
861 await update($, history, entries => [...entries, entry].slice(-MAX_HISTORY))
862}
863
864/** Enters a model phase, recording the thinking or reply block it closes. */
865async function enter($: EngineInterface, live: Live, next: ModelPhase): Promise<void> {
866 if (next === live.phase) {
867 return
868 }
869
870 const nowMs = await $.clock.now()
871 const durationMs = nowMs - live.phaseStartMs
872
873 if (live.phase === 'thinking') {
874 const words = live.thoughtWords
875 const label = words > 0 ? `Thought (${plural(words, 'word')})` : 'Thought'
876
877 await remember($, { ...entryOf('thought', label), durationMs })
878 }
879
880 if (live.phase === 'writing' && live.replyWords > 0) {
881 const label = `Wrote the reply (${plural(live.replyWords, 'word')})`
882
883 await remember($, { ...entryOf('reply', label), durationMs })
884 }
885
886 if (next === 'thinking') {
887 live.thought = ''
888 live.thoughtWords = 0
889 live.isThoughtInWord = false
890 }
891
892 if (next === 'writing') {
893 live.replyWords = 0
894 live.isReplyInWord = false
895 }
896
897 live.phase = next
898 live.phaseStartMs = nowMs
899}
900
901/** Follows one chunk of the main loop's response. */
902async function follow($: EngineInterface, live: Live, chunk: TurnStepChunk): Promise<void> {
903 // The model went on after a declined call: the decline did not end the turn.
904 if (chunk.kind === 'text' || chunk.kind === 'tool') {
905 live.isDeclinedLast = false
906 }
907
908 switch (chunk.kind) {
909 case 'thinking': {
910 const isNew = live.phase !== 'thinking'
911
912 await enter($, live, 'thinking')
913 live.resultsToReview = 0
914 const { added, isInWord } = wordsAdded(chunk.text, live.isThoughtInWord)
915
916 live.thought = (live.thought + chunk.text).slice(-MAX_THOUGHT_BUFFER)
917 live.thoughtWords += added
918 live.isThoughtInWord = isInWord
919 await publish($, live, isNew)
920
921 return
922 }
923 case 'text': {
924 const isNew = live.phase !== 'writing'
925
926 await enter($, live, 'writing')
927 live.resultsToReview = 0
928 const { added, isInWord } = wordsAdded(chunk.text, live.isReplyInWord)
929
930 live.replyWords += added
931 live.isReplyInWord = isInWord
932 await publish($, live, isNew)
933
934 return
935 }
936 case 'tool':
937 await enter($, live, 'composing')
938 live.resultsToReview = 0
939 live.composing = { tool: chunk.name, head: '', chars: 0 }
940
941 // The stream names Agent calls in the order the transcript keeps them,
942 // the order the HUD colors agents by.
943 if (isAgentTool(chunk.name)) {
944 await rememberAgentKey($, live, chunk.id)
945 }
946
947 await publish($, live)
948
949 return
950 case 'input': {
951 const { composing } = live
952
953 if (composing) {
954 composing.chars += chunk.json.length
955
956 if (composing.head.length < MAX_INPUT_HEAD) {
957 composing.head += chunk.json
958 }
959
960 await publish($, live, false)
961 }
962
963 return
964 }
965 }
966}
967
968/**
969 * Names a background agent by the Agent call that launched it: the call's
970 * short `description`, keyed by the id its result carries (the result's own
971 * `description` can hold the whole prompt). Its own calls may already have
972 * shown it.
973 *
974 * @returns whether the call launched a background agent
975 */
976async function launched(
977 $: EngineInterface,
978 live: Live,
979 result: unknown,
980 asked: unknown,
981 toolUseId: string,
982): Promise<boolean> {
983 if (typeof result !== 'object' || result === null) {
984 return false
985 }
986
987 const { agentId, description, status } = result as Record<string, unknown>
988
989 if (typeof agentId !== 'string' || status !== 'async_launched') {
990 return false
991 }
992
993 const name = [asked, description].find(
994 (text): text is string => typeof text === 'string' && oneLine(text) !== '',
995 )
996
997 if (name === undefined) {
998 return true
999 }
1000
1001 const agent = await agentOf($, live, agentId)
1002
1003 live.agentNames.set(agentId, name)
1004 agent.name = name
1005 agent.toolUseId ??= toolUseId
1006 agent.colorKey = toolUseId
1007 await placeAgent($, live, agentId, toolUseId)
1008 await publish($, live)
1009
1010 return true
1011}
1012
1013/**
1014 * The HUD answers in a few milliseconds. A binary too old to know `style`
1015 * runs as the statusline, which reads its JSON from stdin: the empty stdin
1016 * ends it at once, and this bounds anything slower.
1017 */
1018const STYLE_TIMEOUT_MS = 1500
1019
1020/** Whether this module load has asked the HUD for its look yet. */
1021type StyleAsked = { isAsked: boolean; options: PluginOptions }
1022
1023/**
1024 * Checks the look once per module load, off the hook that asks: the hook's
1025 * event goes on at once and the box redraws when the look arrives. A stored
1026 * look stands only when the HUD supplied it with this load's binary and
1027 * preset; the built-in look, or one from other options, is asked again.
1028 */
1029function ensureStyle($: EngineInterface, asked: StyleAsked): void {
1030 if (asked.isAsked) {
1031 return
1032 }
1033
1034 asked.isAsked = true
1035 $.clock.after(0, () => void refreshStyle($, asked.options))
1036}
1037
1038async function refreshStyle($: EngineInterface, options: PluginOptions): Promise<void> {
1039 const preset = presetOf(options)
1040 let binary = BARE_BINARY
1041
1042 try {
1043 binary = await binaryOf($, options)
1044 } catch {
1045 // Without HOME or the file check, the bare name is still worth a try.
1046 }
1047
1048 const stored = await read($, styleSource)
1049
1050 if (!isStyleStale(stored, binary, preset)) {
1051 return
1052 }
1053
1054 const loaded = await loadStyle($, binary, preset)
1055
1056 if (loaded.source.kind === 'builtin') {
1057 $.ui.log(`tch-activity: ${loaded.source.reason}; drawing the built-in look`, { to: 'debug' })
1058 }
1059
1060 await update($, styleState, () => loaded.style)
1061 await update($, styleSource, () => loaded.source)
1062 $.ui.invalidate('ui.render')
1063}
1064
1065/**
1066 * Asks the HUD for its look. Never rejects: a binary that is missing, slow,
1067 * failing or answering something unreadable yields the built-in look and the
1068 * reason, which the expanded history shows as one dim line.
1069 */
1070async function loadStyle($: EngineInterface, binary: string, preset: string): Promise<LoadedStyle> {
1071 const argv = [binary, 'style', '--json', ...(preset === '' ? [] : ['--preset', preset])]
1072 const command = argv.slice(0, 3).join(' ') + (preset === '' ? '' : ` --preset ${preset}`)
1073
1074 try {
1075 const ran = await $.process.run(argv, { stdin: '', timeoutMs: STYLE_TIMEOUT_MS })
1076
1077 if (ran.exitCode !== 0) {
1078 return builtin(`${command} exited ${ran.exitCode}`, binary, preset)
1079 }
1080
1081 const parsed = parseStyle(ran.stdout)
1082
1083 return parsed === null
1084 ? builtin(`${command} printed no style this mod reads`, binary, preset)
1085 : { style: parsed, source: { kind: 'hud', binary, preset } }
1086 } catch (error) {
1087 return builtin(`${binary} could not run: ${error instanceof Error ? error.message : String(error)}`, binary, preset)
1088 }
1089}
1090
1091/** The `preset` option: the preset the statusline command runs with, or empty. */
1092function presetOf(options: PluginOptions): string {
1093 const preset = options['preset']
1094
1095 return typeof preset === 'string' ? preset.trim() : ''
1096}
1097
1098/** The `hideSpinner` option: whether the terminal's spinner line is hidden; on unless set to false. */
1099function isSpinnerHidden(options: PluginOptions): boolean {
1100 return options['hideSpinner'] !== false
1101}
1102
1103/**
1104 * The HUD binary: the `binary` option when set; else `$HOME/go/bin`'s copy
1105 * when it exists, since a session's PATH is the login one and often lacks
1106 * Go's bin folder; else the bare name.
1107 */
1108async function binaryOf($: EngineInterface, options: PluginOptions): Promise<string> {
1109 const configured = options['binary']
1110
1111 if (typeof configured === 'string' && configured.trim() !== '') {
1112 return configured.trim()
1113 }
1114
1115 const home = await $.env.get('HOME')
1116
1117 if (home !== undefined && home !== '') {
1118 const goBin = `${home}${GO_BIN_SUFFIX}`
1119
1120 if (await $.fs.exists(goBin)) {
1121 return goBin
1122 }
1123 }
1124
1125 return BARE_BINARY
1126}
1127
1128const MAX_LABEL_CHARS = 120
1129const MAX_AGENT_NAME_CHARS = 40
1130
1131/** The HUD's segment separator, drawn faint as the statusline draws it. */
1132const SEPARATOR = ' | '
1133
1134/** The headline's show/hide arrow, one column wide. */
1135const TOGGLE_COLUMNS = 1
1136
1137/** What sets the turn's total apart from the box's right border. */
1138const TURN_TOTAL_LEAD = ' · '
1139
1140/** The box's top border: the headline is on the line below it. */
1141const HEADLINE_TOP_ROWS = 1
1142
1143type AbovePromptInput = RenderInput<'AbovePrompt'>
1144
1145/**
1146 * Draws the box above the prompt: the headline, a row per agent at work
1147 * beside the main loop, and, behind the triangle, the history. The box is as
1148 * wide as the widest row it has drawn since the last turn ended, so it never
1149 * shrinks between a turn's steps. While a turn runs, its total is drawn just
1150 * right of the box, on the headline's line.
1151 */
1152async function drawBox($: EngineInterface, e: AbovePromptInput) {
1153 const { Box, Text, Button } = $.ui.resolve(e)
1154
1155 const style = (await read($, styleState)) ?? BUILTIN_STYLE
1156 const source = await read($, styleSource)
1157 const headline = await read($, now)
1158 const entries = await read($, history)
1159 const working = await read($, team)
1160 const isOpen = await read($, isExpanded)
1161 const { columns: widest, turnEnds } = await read($, boxWidth)
1162 const nowMs = await $.clock.now()
1163
1164 /**
1165 * A row's segments as Text: a clipped segment gives way on a narrow
1166 * screen; the others keep their width, since they would wrap.
1167 */
1168 const line = (segments: readonly Segment[]) =>
1169 segments.map(segment => {
1170 const text = (
1171 <Text color={segment.color} dimColor={segment.isFaint === true} wrap={segment.isClipped ? 'truncate-end' : undefined}>
1172 {segment.text}
1173 </Text>
1174 )
1175
1176 return segment.isClipped ? text : <Box flexShrink={0}>{text}</Box>
1177 })
1178
1179 /**
1180 * One agent's row, as the HUD's agents widget draws a running agent: the
1181 * task icon and name in the agent's palette color, then its latest action
1182 * and its running time, each after a faint separator.
1183 */
1184 const agentRow = (agent: ActivityAgent): Segment[] => {
1185 const tint = agentColor(style, agent.colorIndex)
1186
1187 return [
1188 { text: `${icon(style, 'task')} `, color: tint },
1189 { text: printable(agent.name, MAX_AGENT_NAME_CHARS), color: tint, isClipped: true },
1190 { text: SEPARATOR, isFaint: true },
1191 { text: printable(agent.label, MAX_LABEL_CHARS), isClipped: true },
1192 { text: `${SEPARATOR}${elapsedOf(nowMs - agent.sinceMs)}`, isFaint: true },
1193 ]
1194 }
1195
1196 /**
1197 * One history row: its glyph (for a tool call, the category icon in the
1198 * outcome's color), the label, and the duration drawn faint, as the HUD's
1199 * tools widget draws a finished tool.
1200 */hooks/activity-of.ts 120 lines1// Adapted from whats-agent-doing (MIT, Copyright (c) 2026 Tzafrir Rehan);
2// see NOTICE.
3import { clip, oneLine } from './text'
4
5const MAX_DETAIL_CHARS = 60
6
7/** `present` for what a call is doing (the headline), `past` for what it did (the history). */
8export type Tense = 'present' | 'past'
9
10/**
11 * Says in a few words what a tool call is doing, or did.
12 *
13 * @param tool the tool's name; a string, as the declared names are only the
14 * tools of the build that wrote the types (Grep and Glob are on some only)
15 * @param args the call's arguments, whole or as far as they have streamed
16 * @param tense whether the label says what the call is doing or what it did
17 * @returns a short label such as `Reading register.tsx` or `Read register.tsx`
18 */
19export function activityOf(tool: string, args: Record<string, unknown>, tense: Tense = 'present'): string {
20 const verb = (present: string, past: string): string => (tense === 'present' ? present : past)
21
22 const raw = (key: string): string => {
23 const value = args[key]
24
25 return typeof value === 'string' ? oneLine(value) : ''
26 }
27
28 const arg = (key: string): string => clip(raw(key), MAX_DETAIL_CHARS)
29
30 // The base name is taken before the cut, so a long path still names its file.
31 const file = (key: string): string => clip(baseName(raw(key)), MAX_DETAIL_CHARS)
32
33 switch (tool) {
34 case 'Bash':
35 case 'PowerShell':
36 // The model's own description says what a command is for; the command
37 // itself is the fallback.
38 return arg('description') || `${verb('Running', 'Ran')} ${arg('command')}`
39 case 'Read':
40 return `${verb('Reading', 'Read')} ${file('file_path')}`
41 case 'Edit':
42 return `${verb('Editing', 'Edited')} ${file('file_path')}`
43 case 'Write':
44 return `${verb('Writing', 'Wrote')} ${file('file_path')}`
45 case 'NotebookEdit':
46 return `${verb('Editing', 'Edited')} ${file('notebook_path')}`
47 case 'Grep':
48 return `${verb('Searching', 'Searched')} for "${arg('pattern')}"`
49 case 'Glob':
50 return `${verb('Finding', 'Found')} files ${arg('pattern')}`
51 case 'WebFetch':
52 return `${verb('Fetching', 'Fetched')} ${hostOf(arg('url'))}`
53 case 'WebSearch':
54 return `${verb('Searching', 'Searched')} the web for "${arg('query')}"`
55 case 'Agent':
56 case 'Task':
57 return `${verb('Running', 'Ran')} an agent: ${arg('description')}`
58 case 'TodoWrite':
59 return `${verb('Updating', 'Updated')} the todo list`
60 case 'AskUserQuestion':
61 return verb('Waiting for your answer', 'Asked you a question')
62 case 'Skill':
63 return `${verb('Using', 'Used')} the ${arg('skill')} skill`
64 }
65
66 if (tool.startsWith('mcp__')) {
67 const [, server = '', name = ''] = tool.split('__')
68
69 return `${verb('Using', 'Used')} ${server}: ${name}`
70 }
71
72 return `${verb('Using', 'Used')} ${tool}`
73}
74
75/**
76 * The string arguments a tool call's input has streamed so far, read from
77 * its partial JSON: enough to name the file or command before it is whole.
78 */
79export function partialArgsOf(json: string): Record<string, unknown> {
80 const args: Record<string, unknown> = {}
81
82 for (const match of json.matchAll(/"([a-z_]+)"\s*:\s*"((?:[^"\\]|\\.)*)/g)) {
83 const [, key = '', raw = ''] = match
84
85 args[key] ??= unescaped(raw)
86 }
87
88 return args
89}
90
91export function isShellTool(tool: string): boolean {
92 return tool === 'Bash' || tool === 'PowerShell'
93}
94
95export function isAgentTool(tool: string): boolean {
96 return tool === 'Agent' || tool === 'Task'
97}
98
99function unescaped(raw: string): string {
100 try {
101 return JSON.parse(`"${raw}"`) as string
102 } catch {
103 // A partial escape at the stream's edge: the raw text reads well enough.
104 return raw
105 }
106}
107
108function baseName(path: string): string {
109 return path.split(/[\\/]/).pop() || path
110}
111
112function hostOf(url: string): string {
113 try {
114 return new URL(url).host
115 } catch {
116 // Not a whole URL yet (still streaming): show what there is.
117 return url
118 }
119}
120hooks/live.ts 446 lines1// Adapted from whats-agent-doing's register.tsx (MIT, Copyright (c) 2026
2// Tzafrir Rehan); see NOTICE.
3import type { Timer, TurnCompleteReason } from 'claude-code'
4
5import type { ActivityEntry, ActivityNow, ActivityOutcome, TurnClock } from '../types'
6import { activityOf, isAgentTool, isShellTool, partialArgsOf } from './activity-of'
7import { elapsedOf, plural, sizeOf, thoughtOf } from './text'
8
9/** The headline before any turn. */
10export const IDLE: ActivityNow = {
11 phase: 'idle',
12 label: 'Idle, waiting for your prompt',
13 detail: null,
14 sinceMs: 0,
15 tool: null,
16 colorIndex: null,
17 lead: null,
18 lastOutcome: null,
19 turn: null,
20}
21
22/** The tool that asks you questions; the main loop waits on your answer while it runs. */
23export const QUESTION_TOOL = 'AskUserQuestion'
24
25const MAX_THOUGHT_CHARS = 70
26
27/** A tool input this large is worth a size beside its label. */
28const LARGE_INPUT_CHARS = 1024
29
30export const STARTING_LABEL = 'Getting started'
31
32/** The headline while the model writes a call its input does not name yet. */
33export const PREPARING_LABEL = 'Preparing the next action'
34
35export const UNNAMED_AGENT = 'Agent'
36
37/** What the model is doing in the main loop, between and around tool calls. */
38export type ModelPhase = 'idle' | 'requesting' | 'thinking' | 'writing' | 'composing' | 'compacting'
39
40/**
41 * A tool call in flight: the main loop's, or a subagent's (`agentId`). An
42 * `ask` verdict (at `askedMs`) puts it to the mode's decider; it awaits your
43 * approval once that turns out to be the dialog, until it is seen running or
44 * ends. `isPutToYou` stays set once it was taken for the dialog. `waitedMs`
45 * is the approval wait already over, which its timer and duration leave out.
46 */
47export type Call = {
48 tool: string
49 label: string
50 startMs: number
51 agentId: string | null
52 isAwaitingApproval: boolean
53 isPutToYou: boolean
54 askedMs: number | null
55 waitedMs: number
56}
57
58/** A call that has just started, not put to approval. */
59export function callOf(tool: string, label: string, startMs: number, agentId: string | null): Call {
60 return { tool, label, startMs, agentId, isAwaitingApproval: false, isPutToYou: false, askedMs: null, waitedMs: 0 }
61}
62
63/**
64 * Forgets the main loop's calls, as a turn's start or end does. A background
65 * agent's calls outlive the main turn and stay, an approval wait included.
66 */
67export function dropMainCalls(live: Live): void {
68 for (const [id, call] of live.calls) {
69 if (call.agentId === null) {
70 live.calls.delete(id)
71 }
72 }
73}
74
75/** Ends a call's approval wait at `nowMs`, adding it to the time the call leaves out. */
76export function endWait(call: Call, nowMs: number): void {
77 if (call.askedMs !== null) {
78 call.waitedMs += Math.max(0, nowMs - call.askedMs)
79 call.askedMs = null
80 }
81}
82
83/**
84 * The agents tail-claude-hud's agents widget colors: Agent calls in the order
85 * the main conversation made them, the newest AGENT_ORDER_WINDOW kept, each
86 * taking the palette slot of its position. An agent met with no Agent call
87 * seen joins the list by its id.
88 */
89export const AGENT_ORDER_WINDOW = 10
90
91/** The HUD's agent palette has eight colors; a position wraps at that. */
92const AGENT_PALETTE_SIZE = 8
93
94/**
95 * A subagent at work, from its spawn (or its first call, when the spawn came
96 * before a reload) to its stop. `toolUseId` names the Agent call that started
97 * it; `activeMs` is when it last did something; `colorKey` its entry in the
98 * agent order, which picks its color.
99 */
100export type Agent = {
101 name: string
102 label: string
103 startMs: number
104 activeMs: number
105 toolUseId: string | null
106 isBackground: boolean
107 colorKey: string
108}
109
110/**
111 * The module's live view of the session, from which the headline is drawn:
112 * started over on a reload, while the headline and history in `$.state` stay.
113 * `turnPausedMs` is the time the turn has waited on you in waits now over,
114 * `turnPauseStartMs` when the wait still on began, and `turnPauseEndMs`
115 * when the last one ended.
116 */
117export type Live = {
118 calls: Map<string, Call>
119 agents: Map<string, Agent>
120 agentNames: Map<string, string>
121 described: Map<string, string>
122 agentOrder: readonly string[]
123 isRestored: boolean
124 phase: ModelPhase
125 phaseStartMs: number
126 turnStartMs: number | null
127 turnPausedMs: number
128 turnPauseStartMs: number | null
129 turnPauseEndMs: number
130 turnActions: number
131 isDeclinedLast: boolean
132 isFirstRequest: boolean
133 resultsToReview: number
134 thought: string
135 thoughtWords: number
136 isThoughtInWord: boolean
137 replyWords: number
138 isReplyInWord: boolean
139 composing: { tool: string; head: string; chars: number } | null
140 lastAction: string | null
141 lastTurn: { label: string; outcome: ActivityOutcome } | null
142 lastPublishMs: number
143 trailing: Timer | null
144 isSweeping: boolean
145 ticker: Timer | null
146}
147
148export function createLive(): Live {
149 return {
150 calls: new Map(),
151 agents: new Map(),
152 agentNames: new Map(),
153 described: new Map(),
154 agentOrder: [],
155 isRestored: false,
156 phase: 'idle',
157 phaseStartMs: 0,
158 turnStartMs: null,
159 turnPausedMs: 0,
160 turnPauseStartMs: null,
161 turnPauseEndMs: 0,
162 turnActions: 0,
163 isDeclinedLast: false,
164 isFirstRequest: false,
165 resultsToReview: 0,
166 thought: '',
167 thoughtWords: 0,
168 isThoughtInWord: false,
169 replyWords: 0,
170 isReplyInWord: false,
171 composing: null,
172 lastAction: null,
173 lastTurn: null,
174 lastPublishMs: 0,
175 trailing: null,
176 isSweeping: false,
177 ticker: null,
178 }
179}
180
181/** Starts the turn's clock at `startMs`, with no wait on you yet. */
182export function startTurn(live: Live, startMs: number): void {
183 live.turnStartMs = startMs
184 live.turnPausedMs = 0
185 live.turnPauseStartMs = null
186 live.turnPauseEndMs = startMs
187}
188
189/** Whether a call holds the main loop on you: its approval dialog is up, or it asks you a question. */
190function isOnYou(call: Call): boolean {
191 return call.agentId === null && (call.isAwaitingApproval || call.tool === QUESTION_TOOL)
192}
193
194/**
195 * Pauses the turn's clock from `fromMs`, as a main-loop call starts waiting
196 * on you; a pause already on stands, and none reaches back into one over.
197 */
198export function pauseTurn(live: Live, fromMs: number): void {
199 if (live.turnStartMs === null || live.turnPauseStartMs !== null) {
200 return
201 }
202
203 live.turnPauseStartMs = Math.max(fromMs, live.turnStartMs, live.turnPauseEndMs)
204}
205
206/** Resumes the turn's clock at `nowMs`, once no main-loop call in flight waits on you. */
207export function resumeTurn(live: Live, nowMs: number): void {
208 if (live.turnPauseStartMs === null || [...live.calls.values()].some(isOnYou)) {
209 return
210 }
211
212 live.turnPausedMs += Math.max(0, nowMs - live.turnPauseStartMs)
213 live.turnPauseStartMs = null
214 live.turnPauseEndMs = nowMs
215}
216
217/** The running turn's clock, or null between turns. */
218export function turnClockOf(live: Live): TurnClock | null {
219 return live.turnStartMs === null
220 ? null
221 : { sinceMs: live.turnStartMs + live.turnPausedMs, pausedAtMs: live.turnPauseStartMs }
222}
223
224/** The turn's total at `nowMs`: its time so far, less its waits on you. */
225export function turnTotalOf(clock: TurnClock, nowMs: number): number {
226 return Math.max(0, (clock.pausedAtMs ?? nowMs) - clock.sinceMs)
227}
228
229/** The headline as the live view has it. */
230export function current(live: Live): ActivityNow {
231 const base = { ...IDLE, lastOutcome: live.lastTurn?.outcome ?? null, turn: turnClockOf(live) }
232
233 if (live.phase === 'compacting') {
234 return { ...base, phase: 'compacting', label: 'Compacting the conversation', sinceMs: live.phaseStartMs }
235 }
236
237 const open = [...live.calls.entries()].filter(([, call]) => call.agentId === null)
238 const [newestId, newest] = open.at(-1) ?? []
239
240 if (newestId !== undefined && newest !== undefined) {
241 const more = open.length > 1 ? ` (+${open.length - 1} more)` : ''
242 const call = { ...base, sinceMs: newest.startMs + newest.waitedMs, tool: newest.tool }
243
244 if (newest.isAwaitingApproval) {
245 return { ...call, sinceMs: newest.askedMs ?? call.sinceMs, phase: 'approval', label: `Waiting for your approval: ${newest.label}${more}` }
246 }
247
248 if (newest.tool === QUESTION_TOOL) {
249 return { ...call, phase: 'question', label: newest.label }
250 }
251
252 const inner = isAgentTool(newest.tool) ? agentUnder(live, newestId) : undefined
253
254 return inner === undefined
255 ? { ...call, phase: 'tool', label: `${newest.label}${more}` }
256 : {
257 ...call,
258 phase: 'agent',
259 lead: newest.label,
260 label: `${agentLabel(live, inner)}${more}`,
261 colorIndex: colorIndexOf(live, inner.colorKey),
262 }
263 }
264
265 if (live.phase === 'idle' && live.agents.size > 0) {
266 // Between turns, background agents may still be at work.
267 const working = [...live.agents.entries()]
268 const sinceMs = Math.min(...working.map(([, agent]) => agent.startMs))
269 const [busiestId, busiest] = working.reduce((a, b) => (b[1].activeMs > a[1].activeMs ? b : a))
270 const isAlone = working.length === 1
271
272 return {
273 ...base,
274 phase: 'agent',
275 lead: isAlone ? busiest.name : null,
276 label: isAlone
277 ? agentLabel(live, { ...busiest, id: busiestId })
278 : `${plural(working.length, 'agent')} working`,
279 sinceMs,
280 tool: 'Agent',
281 colorIndex: isAlone ? colorIndexOf(live, busiest.colorKey) : null,
282 }
283 }
284
285 const sinceMs = live.phaseStartMs
286
287 // Between calls the turn's last action stands under the phase's glyph, so
288 // a run of quick calls reads as one stretch of work.
289 switch (live.phase) {
290 case 'requesting':
291 return {
292 ...base,
293 phase: 'requesting',
294 label: live.isFirstRequest
295 ? 'Reading your prompt'
296 : live.lastAction ?? (live.resultsToReview > 0
297 ? `Reviewing the results of ${plural(live.resultsToReview, 'action')}`
298 : 'Waiting for the model'),
299 sinceMs,
300 }
301 case 'thinking': {
302 const snippet = thoughtOf(live.thought, MAX_THOUGHT_CHARS)
303 const label = snippet ? `Thinking: ${snippet}` : standingLabel(live)
304
305 return { ...base, phase: 'thinking', label, sinceMs }
306 }
307 case 'writing':
308 return {
309 ...base,
310 phase: 'writing',
311 label: 'Writing the reply',
312 detail: plural(live.replyWords, 'word'),
313 sinceMs,
314 }
315 case 'composing':
316 return { ...base, ...composingHeadline(live), phase: 'composing', sinceMs }
317 case 'idle':
318 return live.lastTurn === null ? base : { ...base, label: `Idle · last turn ${live.lastTurn.label}` }
319 }
320}
321
322/**
323 * A call being written is named once its input says what it does: a file
324 * tool by its path, a command by its description, which streams after the
325 * command itself. Until then the turn's last action stands, or, before
326 * there is one, the headline says a call is being prepared.
327 */
328function composingHeadline(live: Live): { label: string; detail: string | null; tool: string | null } {
329 const { composing } = live
330 const args = composing ? partialArgsOf(composing.head) : {}
331 const isDescribed = composing !== null && (isShellTool(composing.tool)
332 ? typeof args['description'] === 'string'
333 : Object.keys(args).length > 0)
334
335 if (!composing || !isDescribed) {
336 return { label: live.lastAction ?? PREPARING_LABEL, detail: null, tool: null }
337 }
338
339 const detail = composing.chars >= LARGE_INPUT_CHARS ? sizeOf(composing.chars) : null
340
341 return { label: activityOf(composing.tool, args), detail, tool: composing.tool }
342}
343
344/**
345 * What the headline keeps saying while the model thinks with no thought text
346 * to quote: the turn's last action, or the prompt before there is one.
347 */
348function standingLabel(live: Live): string {
349 return live.lastAction ?? 'Reading your prompt'
350}
351
352/** The agent an Agent call started, or the one that last did something. */
353function agentUnder(live: Live, toolUseId: string): (Agent & { id: string }) | undefined {
354 const working = [...live.agents.entries()].map(([id, agent]) => ({ ...agent, id }))
355
356 return working.find(agent => agent.toolUseId === toolUseId)
357 ?? working.reduce<(Agent & { id: string }) | undefined>((a, b) => (a === undefined || b.activeMs > a.activeMs ? b : a), undefined)
358}
359
360/**
361 * What an agent is doing: waiting on approval for its newest call that
362 * waits, else its latest action. Derived on each read, so a second request
363 * never stacks a second prefix.
364 */
365export function agentLabel(live: Live, agent: Agent & { id: string }): string {
366 const waiting = waitingCallOf(live, agent.id)
367
368 return waiting === undefined ? agent.label : `Waiting for your approval: ${waiting.label}`
369}
370
371/** Whether a call of the agent's waits on approval. */
372export function isAgentWaiting(live: Live, agentId: string): boolean {
373 return waitingCallOf(live, agentId) !== undefined
374}
375
376function waitingCallOf(live: Live, agentId: string): Call | undefined {
377 return [...live.calls.values()].reverse().find(call => call.agentId === agentId && call.isAwaitingApproval)
378}
379
380/** The order with `key` added at its end, once, the newest window kept. */
381export function withAgentKey(order: readonly string[], key: string): readonly string[] {
382 return order.includes(key) ? order : [...order, key].slice(-AGENT_ORDER_WINDOW)
383}
384
385/**
386 * The order once an agent first met by its id is known by its Agent call:
387 * the id's entry goes, and the call keeps (or takes) its own place.
388 */
389export function withAgentCall(order: readonly string[], agentId: string, toolUseId: string): readonly string[] {
390 return withAgentKey(order.filter(key => key !== agentId), toolUseId)
391}
392
393/** An agent's palette slot: its position in the agent order, wrapped at the palette size. */
394export function colorIndexOf(live: Live, key: string): number {
395 return Math.max(0, live.agentOrder.indexOf(key)) % AGENT_PALETTE_SIZE
396}
397
398/**
399 * How a turn ended: the engine's reason, or `declined` when its last call was
400 * one you declined and nothing followed it.
401 */
402export type TurnEnd = TurnCompleteReason | 'declined'
403
404export function turnEndOf(reason: TurnCompleteReason, isDeclinedLast: boolean): TurnEnd {
405 return isDeclinedLast && (reason === 'answer' || reason === 'aborted') ? 'declined' : reason
406}
407
408/**
409 * How a turn ended, with its time counted as the running timer counts it:
410 * the idle headline's words, and, capitalized, the turn's last history row.
411 */
412export function turnEndLabel(end: TurnEnd, durationMs: number, actions: number): string {
413 const took = elapsedOf(durationMs)
414
415 switch (end) {
416 case 'aborted':
417 return `interrupted after ${took}`
418 case 'error':
419 return `stopped on an error after ${took}`
420 case 'refusal':
421 return 'declined the request'
422 case 'declined':
423 return `stopped at a declined call after ${took}`
424 case 'answer':
425 return `done in ${took}, ${plural(actions, 'action')}`
426 }
427}
428
429export function outcomeOf(end: TurnEnd): ActivityOutcome {
430 switch (end) {
431 case 'aborted':
432 return 'interrupted'
433 case 'error':
434 return 'error'
435 case 'refusal':
436 case 'declined':
437 return 'denied'
438 case 'answer':
439 return 'ok'
440 }
441}
442
443export function entryOf(kind: ActivityEntry['kind'], label: string, outcome: ActivityOutcome = 'ok'): ActivityEntry {
444 return { kind, label, durationMs: null, outcome, tool: null }
445}
446hooks/layout.ts 109 lines1/** Rows every box takes: the top and bottom border and the headline. */
2const FIXED_ROWS = 3
3
4/** The blank row between the headline (and agents) and the history. */
5const HISTORY_GAP_ROWS = 1
6
7export const MAX_AGENT_ROWS = 6
8export const MAX_HISTORY_ROWS = 12
9
10/** What the band shows, given the rows it may take. */
11export type BandLayout = {
12 /** Agent rows drawn, newest last. */
13 agentRows: number
14 /** Whether a `… N more agents` row follows them. */
15 hasMoreAgents: boolean
16 /** Whether the history is drawn: it is open and at least one row fits. */
17 isHistoryShown: boolean
18 /** History entries drawn, newest last. */
19 historyRows: number
20 /** Whether an `… N earlier` row leads them. */
21 hasEarlier: boolean
22 /** Whether the built-in-look note closes the history. */
23 hasNote: boolean
24}
25
26/**
27 * Fits the band into `maxRows`, counting every row it draws: the frame and
28 * headline, each agent row and the `more agents` row, the history's gap,
29 * its `earlier` row, its entries or `No actions yet`, and the note. A tree
30 * taller than `maxRows` scrolls in the band, so nothing past it is drawn.
31 */
32export function bandLayout(input: {
33 maxRows: number
34 agents: number
35 entries: number
36 isOpen: boolean
37 hasNote: boolean
38}): BandLayout {
39 let room = Math.max(0, input.maxRows - FIXED_ROWS)
40
41 const agentCap = Math.min(MAX_AGENT_ROWS, room)
42 const hasMoreAgents = input.agents > agentCap && agentCap > 0
43 const agentRows = hasMoreAgents ? agentCap - 1 : Math.min(input.agents, agentCap)
44
45 room -= agentRows + (hasMoreAgents ? 1 : 0)
46
47 // The history needs its gap and one row at least.
48 const isHistoryShown = input.isOpen && room >= HISTORY_GAP_ROWS + 1
49
50 if (!isHistoryShown) {
51 return { agentRows, hasMoreAgents, isHistoryShown, historyRows: 0, hasEarlier: false, hasNote: false }
52 }
53
54 room -= HISTORY_GAP_ROWS
55
56 // The note gives way before the entries do.
57 const hasNote = input.hasNote && room >= 2
58 room -= hasNote ? 1 : 0
59
60 const historyCap = Math.min(MAX_HISTORY_ROWS, room)
61 const hasEarlier = input.entries > historyCap
62 const historyRows = hasEarlier ? Math.max(0, historyCap - 1) : input.entries
63
64 return { agentRows, hasMoreAgents, isHistoryShown, historyRows, hasEarlier, hasNote }
65}
66
67/**
68 * Columns from the box's left edge to the headline label: the show/hide
69 * arrow, a space, the glyph and a space. Agent rows are indented by this, so
70 * they start under the label.
71 */
72export const AGENT_INDENT_COLUMNS = 4
73
74/** Columns the frame adds to its widest row: a border and a padding column each side. */
75const FRAME_COLUMNS = 4
76
77/**
78 * A run of text in a row, drawn in `color` (default foreground when absent),
79 * faint, and, when `isClipped`, cut short on a narrow screen rather than
80 * wrapped.
81 */
82export type Segment = {
83 text: string
84 color?: string | undefined
85 isFaint?: boolean | undefined
86 isClipped?: boolean
87}
88
89/**
90 * The columns a row's segments take. A glyph is one column, as the engine
91 * and tmux count Nerd Font icons, and an emoji drawn as one is two.
92 */
93export function columnsOf(segments: readonly Segment[]): number {
94 let columns = 0
95
96 for (const segment of segments) {
97 for (const char of segment.text) {
98 columns += /\p{Emoji_Presentation}/u.test(char) ? 2 : 1
99 }
100 }
101
102 return columns
103}
104
105/** The box's width, frame included, for rows of the given widths. */
106export function boxColumnsOf(rows: readonly number[]): number {
107 return Math.max(0, ...rows) + FRAME_COLUMNS
108}
109hooks/marks.ts 142 lines1// The glyph and color each state is drawn with: tail-claude-hud's icons and
2// semantic colors where the HUD has one, plain text marks where it has none.
3import type { ActivityAgent, ActivityEntry, ActivityNow, ActivityOutcome, TchStyle, TchStyleSource } from '../types'
4import { agentColor, color, icon, toolIcon } from './style'
5import { printable } from './text'
6
7const MAX_NOTE_CHARS = 120
8
9/** History marks for rows that are no tool call: a prompt (default text) and a compaction (faint). */
10const PROMPT_GLYPH = '›'
11const COMPACT_GLYPH = '⇣'
12
13/**
14 * The reply's speech bubble, which the HUD's icon set has no key for: the
15 * Nerd Font comment icon (nf-fa-comment), a narrow quote mark otherwise.
16 */
17const REPLY_GLYPHS: Readonly<Record<string, string>> = { nerdfont: '\uf075', unicode: '❝', ascii: '"' }
18const REPLY_FALLBACK = '❝'
19
20/** The tool that puts a question to you, drawn with the needs-you bell wherever it shows. */
21const QUESTION_TOOL = 'AskUserQuestion'
22
23/**
24 * A glyph, the color it is drawn in (`undefined`: default foreground), and
25 * whether it is drawn faint.
26 */
27export type Mark = { glyph: string; color: string | undefined; isFaint?: boolean }
28
29/** The headline's glyph: what kind of work, in the HUD's color for it. */
30export function headlineMark(style: TchStyle, headline: ActivityNow): Mark {
31 const running = color(style, 'running')
32
33 switch (headline.phase) {
34 case 'idle':
35 return headline.lastOutcome === null
36 ? { glyph: icon(style, 'clock'), color: color(style, 'muted') }
37 : outcomeMark(style, headline.lastOutcome)
38 case 'thinking':
39 return { glyph: icon(style, 'thinking'), color: color(style, 'thinking') }
40 case 'writing':
41 return { glyph: replyGlyph(style), color: running }
42 case 'tool':
43 case 'composing':
44 return headline.tool === null
45 ? { glyph: icon(style, 'running'), color: running }
46 : { glyph: toolIcon(style, headline.tool), color: running }
47 case 'agent':
48 return {
49 glyph: icon(style, 'task'),
50 color: headline.colorIndex === null ? running : agentColor(style, headline.colorIndex),
51 }
52 case 'approval':
53 case 'question':
54 return { glyph: icon(style, 'permission'), color: color(style, 'permission') }
55 case 'requesting':
56 case 'compacting':
57 return { glyph: icon(style, 'running'), color: running }
58 }
59}
60
61/** A finished thing's glyph: the HUD's check and error icons, its declined and interrupted icons muted. */
62export function outcomeMark(style: TchStyle, outcome: ActivityOutcome): Mark {
63 switch (outcome) {
64 case 'ok':
65 return { glyph: icon(style, 'check'), color: color(style, 'success') }
66 case 'error':
67 return { glyph: icon(style, 'error'), color: color(style, 'error') }
68 case 'denied':
69 return { glyph: icon(style, 'rejected'), color: color(style, 'muted') }
70 case 'interrupted':
71 return { glyph: icon(style, 'interrupted'), color: color(style, 'muted') }
72 }
73}
74
75export function entryMark(style: TchStyle, entry: ActivityEntry): Mark {
76 switch (entry.kind) {
77 case 'turn':
78 return { glyph: PROMPT_GLYPH, color: undefined }
79 case 'thought':
80 return { glyph: icon(style, 'thinking'), color: undefined, isFaint: true }
81 case 'reply':
82 return { glyph: replyGlyph(style), color: undefined, isFaint: true }
83 case 'compact':
84 return { glyph: COMPACT_GLYPH, color: undefined, isFaint: true }
85 case 'tool':
86 return entry.tool === null ? outcomeMark(style, entry.outcome) : toolMark(style, entry.tool, entry.outcome)
87 case 'end':
88 return outcomeMark(style, entry.outcome)
89 }
90}
91
92/**
93 * A finished tool's one glyph, as the HUD's tools widget draws it: the
94 * category icon in the success or error color. A declined or interrupted
95 * call shows its muted mark in the icon's place, so its row never depends
96 * on color alone.
97 */
98function toolMark(style: TchStyle, tool: string, outcome: ActivityOutcome): Mark {
99 switch (outcome) {
100 case 'ok':
101 return { glyph: entryToolIcon(style, tool), color: color(style, 'success') }
102 case 'error':
103 return { glyph: entryToolIcon(style, tool), color: color(style, 'error') }
104 case 'denied':
105 case 'interrupted':
106 return outcomeMark(style, outcome)
107 }
108}
109
110/** A history tool row's kind icon: the HUD's for the tool's category, the bell for a question to you. */
111function entryToolIcon(style: TchStyle, tool: string): string {
112 return tool === QUESTION_TOOL ? icon(style, 'permission') : toolIcon(style, tool)
113}
114
115function replyGlyph(style: TchStyle): string {
116 return REPLY_GLYPHS[style.iconMode] ?? REPLY_FALLBACK
117}
118
119/**
120 * The border's color: the needs-you color while the main loop or an agent
121 * waits on you, muted when idle, else the color of the work under way.
122 */
123export function borderColor(style: TchStyle, headline: ActivityNow, agents: readonly ActivityAgent[]): string | undefined {
124 if (headline.phase === 'approval' || headline.phase === 'question' || agents.some(agent => agent.isWaiting)) {
125 return color(style, 'permission')
126 }
127
128 switch (headline.phase) {
129 case 'idle':
130 return color(style, 'muted')
131 case 'thinking':
132 return color(style, 'thinking')
133 default:
134 return color(style, 'running')
135 }
136}
137
138/** The one line saying the HUD's look is not in use, and why. */
139export function styleNote(source: TchStyleSource | null): string | null {
140 return source?.kind === 'builtin' ? `Built-in look: ${printable(source.reason, MAX_NOTE_CHARS)}` : null
141}
142hooks/style.ts 236 lines1import type { TchStyle, TchStyleSource } from '../types'
2import { printable } from './text'
3
4/** The `style --json` schema this module reads. */
5const STYLE_SCHEMA = 1
6
7/** Where `go install` puts the HUD, which the login PATH often lacks. */
8export const GO_BIN_SUFFIX = '/go/bin/tail-claude-hud'
9
10/** The bare name, found on the session's PATH when nothing else is. */
11export const BARE_BINARY = 'tail-claude-hud'
12
13/** Icons and colors are short; anything longer is not one. */
14const MAX_ICON_CHARS = 8
15
16const MAX_REASON_CHARS = 120
17
18/**
19 * Mod color syntax the HUD emits. Any other string could make the engine
20 * refuse the whole tree, so it is dropped to the default foreground.
21 */
22const COLOR_PATTERN = /^(ansi256\(\d{1,3}\)|#[0-9a-fA-F]{6})$/
23
24/**
25 * The look drawn when the HUD binary is missing or answers badly: the HUD's
26 * own default colors with narrow unicode glyphs, which need no Nerd Font.
27 */
28export const BUILTIN_STYLE: TchStyle = {
29 iconMode: 'unicode',
30 icons: {
31 check: '✓',
32 running: '⧗',
33 clock: '◷',
34 folder: '⌂',
35 branch: '⎇',
36 read: '≡',
37 edit: '✎',
38 write: '✎',
39 bash: '$',
40 grep: '⌕',
41 glob: '⌕',
42 web: '◎',
43 task: '◆',
44 skill: '✦',
45 thinking: '∴',
46 other: '⚙',
47 error: '✗',
48 permission: '!',
49 rejected: '⊘',
50 interrupted: '■',
51 },
52 colors: {
53 running: 'ansi256(3)',
54 success: 'ansi256(2)',
55 error: 'ansi256(1)',
56 thinking: 'ansi256(3)',
57 permission: 'ansi256(1)',
58 muted: 'ansi256(8)',
59 normal: 'ansi256(2)',
60 warning: 'ansi256(3)',
61 critical: 'ansi256(1)',
62 },
63 agentColors: [
64 'ansi256(12)',
65 'ansi256(10)',
66 'ansi256(9)',
67 'ansi256(11)',
68 'ansi256(13)',
69 'ansi256(14)',
70 'ansi256(3)',
71 'ansi256(5)',
72 ],
73 toolCategories: {
74 byName: {
75 Agent: 'Task',
76 Bash: 'Bash',
77 Edit: 'Edit',
78 Glob: 'Glob',
79 Grep: 'Grep',
80 NotebookEdit: 'Write',
81 Read: 'Read',
82 Skill: 'Skill',
83 Task: 'Task',
84 WebFetch: 'Web',
85 WebSearch: 'Web',
86 Workflow: 'Task',
87 Write: 'Write',
88 },
89 default: 'Other',
90 icons: {
91 Bash: 'bash',
92 Edit: 'edit',
93 Glob: 'glob',
94 Grep: 'grep',
95 Read: 'read',
96 Skill: 'skill',
97 Task: 'task',
98 Thinking: 'thinking',
99 Web: 'web',
100 Write: 'write',
101 },
102 },
103}
104
105/** The semantic color names the box draws with. */
106export type ColorName = 'running' | 'success' | 'error' | 'thinking' | 'permission' | 'muted'
107
108/** The icon keys the box draws with, beyond the per-category ones. */
109export type IconName =
110 | 'check'
111 | 'running'
112 | 'clock'
113 | 'task'
114 | 'thinking'
115 | 'error'
116 | 'permission'
117 | 'rejected'
118 | 'interrupted'
119 | 'write'
120 | 'other'
121
122/**
123 * The icon for a tool: its HUD category (Read, Bash, Web, ...) mapped to
124 * that category's icon key, `other` for tools the HUD does not categorize.
125 */
126export function toolIcon(style: TchStyle, tool: string): string {
127 const category = style.toolCategories.byName[tool] ?? style.toolCategories.default
128 const key = style.toolCategories.icons[category] ?? 'other'
129
130 return icon(style, key)
131}
132
133export function icon(style: TchStyle, key: IconName | string): string {
134 return style.icons[key] || BUILTIN_STYLE.icons[key] || '•'
135}
136
137/** A semantic color, or `undefined` for the terminal's default foreground. */
138export function color(style: TchStyle, name: ColorName): string | undefined {
139 return style.colors[name] || undefined
140}
141
142/** The palette color of the agent spawned `colorIndex`-th in the session. */
143export function agentColor(style: TchStyle, colorIndex: number): string | undefined {
144 const palette = style.agentColors.length > 0 ? style.agentColors : BUILTIN_STYLE.agentColors
145
146 return palette[colorIndex % palette.length] || undefined
147}
148
149/** A loaded look and where it came from. */
150export type LoadedStyle = { style: TchStyle; source: TchStyleSource }
151
152/**
153 * Reads `style --json` output into a look, the built-in one filling any key
154 * the output lacks. `null` when it is not JSON or not schema 1.
155 */
156export function parseStyle(stdout: string): TchStyle | null {
157 let raw: unknown
158
159 try {
160 raw = JSON.parse(stdout)
161 } catch {
162 return null
163 }
164
165 if (!isRecord(raw) || raw['schema'] !== STYLE_SCHEMA) {
166 return null
167 }
168
169 const categories = isRecord(raw['toolCategories']) ? raw['toolCategories'] : {}
170 const agentColors = Array.isArray(raw['agentColors'])
171 ? raw['agentColors'].filter((one): one is string => typeof one === 'string').map(colorOf)
172 : []
173
174 return {
175 iconMode: typeof raw['iconMode'] === 'string' ? raw['iconMode'] : BUILTIN_STYLE.iconMode,
176 icons: { ...BUILTIN_STYLE.icons, ...stringsOf(raw['icons'], iconOf) },
177 colors: { ...BUILTIN_STYLE.colors, ...stringsOf(raw['colors'], colorOf) },
178 agentColors: agentColors.length > 0 ? agentColors : BUILTIN_STYLE.agentColors,
179 toolCategories: {
180 byName: { ...BUILTIN_STYLE.toolCategories.byName, ...stringsOf(categories['byName'], plainOf) },
181 default: typeof categories['default'] === 'string' ? categories['default'] : BUILTIN_STYLE.toolCategories.default,
182 icons: { ...BUILTIN_STYLE.toolCategories.icons, ...stringsOf(categories['icons'], plainOf) },
183 },
184 }
185}
186
187export function builtin(reason: string, binary: string, preset: string): LoadedStyle {
188 return {
189 style: BUILTIN_STYLE,
190 source: { kind: 'builtin', reason: printable(reason, MAX_REASON_CHARS), binary, preset },
191 }
192}
193
194function isRecord(value: unknown): value is Record<string, unknown> {
195 return typeof value === 'object' && value !== null && !Array.isArray(value)
196}
197
198/** The string entries of `value`, each passed through `clean`; others dropped. */
199function stringsOf(value: unknown, clean: (text: string) => string): Record<string, string> {
200 if (!isRecord(value)) {
201 return {}
202 }
203
204 const out: Record<string, string> = {}
205
206 for (const [key, entry] of Object.entries(value)) {
207 if (typeof entry === 'string') {
208 out[key] = clean(entry)
209 }
210 }
211
212 return out
213}
214
215/** A color the engine accepts, or empty for the default foreground. */
216function colorOf(text: string): string {
217 return COLOR_PATTERN.test(text) ? text : ''
218}
219
220function iconOf(text: string): string {
221 return printable(text, MAX_ICON_CHARS)
222}
223
224function plainOf(text: string): string {
225 return printable(text, MAX_REASON_CHARS)
226}
227
228/**
229 * Whether to ask the HUD for its look: always, unless the stored look came
230 * from the HUD run with this binary and preset. The built-in look is never
231 * kept, so a binary that gains `style` later is picked up.
232 */
233export function isStyleStale(stored: TchStyleSource | null, binary: string, preset: string): boolean {
234 return !(stored?.kind === 'hud' && stored.binary === binary && stored.preset === preset)
235}
236hooks/waiting.ts 22 lines1// The approval breadcrumb tail-claude-hud's `permission` widget reads: one
2// file per session waiting on an approval, which other sessions' status lines
3// show as an alert. The HUD's own `hook permission-request` writes the same file.
4
5/** Where the HUD keeps breadcrumbs, under the home folder. */
6const WAITING_DIR_SUFFIX = '/.config/tail-claude-hud/waiting'
7
8/** The breadcrumb file of a session. */
9export function waitingPathOf(home: string, sessionId: string): string {
10 return `${home}${WAITING_DIR_SUFFIX}/${sessionId}`
11}
12
13/**
14 * The breadcrumb's JSON, as the HUD writes it: the session, its project (the
15 * working directory's last component, empty at a root) and the tool waiting.
16 */
17export function breadcrumbOf(sessionId: string, cwd: string, tool: string): string {
18 const project = cwd.split('/').filter(part => part !== '').at(-1) ?? ''
19
20 return JSON.stringify({ session_id: sessionId, project, tool_name: tool })
21}
22hooks/text.ts 168 lines1// Portions adapted from whats-agent-doing (MIT, Copyright (c) 2026 Tzafrir
2// Rehan); see NOTICE.
3
4/** Collapses runs of whitespace, newlines included, to single spaces. */
5export function oneLine(text: string): string {
6 return text.replace(/\s+/g, ' ').trim()
7}
8
9/** Cuts `text` to `max` characters, marking the cut with an ellipsis. */
10export function clip(text: string, max: number): string {
11 return text.length > max ? `${text.slice(0, max - 1)}…` : text
12}
13
14/**
15 * A label safe to draw: control, format and line-separator characters out
16 * (the engine refuses a whole tree holding one), whitespace collapsed, and
17 * cut to `max`. Labels carry paths, commands and thoughts the model wrote.
18 */
19export function printable(text: string, max: number): string {
20 const spaced = text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, ' ').replace(/\p{Cf}/gu, '')
21
22 return clip(oneLine(spaced), max)
23}
24
25/** A sentence this short has barely started; its predecessor gives context. */
26const SHORT_SENTENCE_CHARS = 25
27
28/**
29 * The sentence Claude is thinking right now: the tail of the thought so far,
30 * with the sentence before it when the current one has barely started.
31 *
32 * @param thought the thinking block's text so far
33 * @param max the longest snippet, cut from the front
34 */
35export function thoughtOf(thought: string, max: number): string {
36 const flat = oneLine(thought.replace(/[*_`#>]/g, ''))
37
38 if (flat === '') {
39 return ''
40 }
41
42 const sentences = flat.split(/(?<=[.!?:])\s+/)
43 const last = sentences.at(-1) ?? ''
44 const before = sentences.at(-2)
45 const tail = last.length < SHORT_SENTENCE_CHARS && before !== undefined ? `${before} ${last}` : last
46
47 return tail.length > max ? `…${tail.slice(-(max - 1))}` : tail
48}
49
50export function plural(count: number, word: string): string {
51 return `${count} ${word}${count === 1 ? '' : 's'}`
52}
53
54/** `840 B`, `2.3 KB`, `1.1 MB`. */
55export function sizeOf(chars: number): string {
56 if (chars < 1024) {
57 return `${chars} B`
58 }
59
60 if (chars < 1024 * 1024) {
61 return `${(chars / 1024).toFixed(1)} KB`
62 }
63
64 return `${(chars / 1024 / 1024).toFixed(1)} MB`
65}
66
67/**
68 * A finished duration as tail-claude-hud's widgets print it:
69 * `<0.1s`, `0.6s`, `12.3s`, `1m 48s`, `1h 3m`.
70 */
71export function durationOf(ms: number): string {
72 const whole = Math.floor(ms)
73
74 if (whole <= 0) {
75 return '0.0s'
76 }
77
78 if (whole < 100) {
79 return '<0.1s'
80 }
81
82 if (whole < 60_000) {
83 const seconds = Math.floor(whole / 1000)
84 const tenths = Math.floor((whole % 1000) / 100)
85
86 return tenths === 0 ? `${seconds}s` : `${seconds}.${tenths}s`
87 }
88
89 if (whole < 3_600_000) {
90 const minutes = Math.floor(whole / 60_000)
91 const seconds = Math.floor((whole % 60_000) / 1000)
92
93 return `${minutes}m ${seconds}s`
94 }
95
96 const hours = Math.floor(whole / 3_600_000)
97 const minutes = Math.floor((whole % 3_600_000) / 60_000)
98
99 return `${hours}h ${minutes}m`
100}
101
102/** Under this, a running timer shows tenths of a second. */
103export const TENTHS_UNDER_MS = 10_000
104
105/**
106 * A running timer: tenths under ten seconds (`4.2s`), whole seconds to a
107 * minute, then minutes and seconds.
108 */
109export function elapsedOf(ms: number): string {
110 const clamped = Math.max(0, ms)
111
112 if (clamped < TENTHS_UNDER_MS) {
113 return `${(Math.floor(clamped / 100) / 10).toFixed(1)}s`
114 }
115
116 return wholeElapsedOf(clamped)
117}
118
119/**
120 * A running timer in whole seconds, never ahead of the time passed: `7s`,
121 * `46s`, `1m 12s`, `1h 3m`.
122 */
123export function wholeElapsedOf(ms: number): string {
124 const total = Math.floor(Math.max(0, ms) / 1000)
125
126 if (total < 60) {
127 return `${total}s`
128 }
129
130 const hours = Math.floor(total / 3600)
131 const minutes = Math.floor((total % 3600) / 60)
132
133 return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m ${total % 60}s`
134}
135
136/**
137 * Counts the words a streamed chunk adds, carrying whether the text so far
138 * ends inside a word, so a reply is never counted again from its start.
139 *
140 * @param chunk the newly streamed text
141 * @param isInWord whether the text before it ended inside a word
142 */
143export function wordsAdded(chunk: string, isInWord: boolean): { added: number; isInWord: boolean } {
144 const words = chunk.match(/\S+/g)?.length ?? 0
145 const continues = isInWord && /^\S/.test(chunk)
146
147 return {
148 added: continues ? words - 1 : words,
149 isInWord: chunk === '' ? isInWord : /\S$/.test(chunk),
150 }
151}
152
153/**
154 * A prompt as the history lists it. A turn the engine started with a tagged
155 * message (`<agent-message …>`, `<task-notification>`) is named by its tag,
156 * since the markup says nothing to a reader.
157 */
158export function promptLabel(text: string, max: number): string {
159 const flat = oneLine(text)
160 const tag = /^<([a-z][a-z-]*)[\s>]/.exec(flat)?.[1]
161
162 return tag === undefined ? clip(flat, max) : capitalized(tag.replace(/-/g, ' '))
163}
164
165export function capitalized(text: string): string {
166 return text.charAt(0).toUpperCase() + text.slice(1)
167}
168types/index.d.ts 126 lines1/**
2 * What the box says Claude is doing: `idle` between turns, a model phase
3 * (`requesting`, `thinking`, `writing`, `composing`), a tool phase (`tool`,
4 * `agent`, `approval`, `question`), or `compacting`.
5 */
6export type ActivityPhase =
7 | 'idle'
8 | 'requesting'
9 | 'thinking'
10 | 'writing'
11 | 'composing'
12 | 'tool'
13 | 'agent'
14 | 'approval'
15 | 'question'
16 | 'compacting'
17
18export type ActivityOutcome = 'ok' | 'error' | 'denied' | 'interrupted'
19
20/**
21 * The box's headline: the phase, its words, and when it began. `tool` is the
22 * tool the headline is about (its category picks the icon); `colorIndex` the
23 * agent palette slot when the headline names an agent, and `lead` the agent's
24 * name, drawn in that color before `label`; `detail` a count or size drawn
25 * faint after it (`120 words`); `lastOutcome` how the previous turn ended,
26 * for the idle glyph; `turn` the running turn's clock, null between turns.
27 */
28export type ActivityNow = {
29 phase: ActivityPhase
30 label: string
31 detail: string | null
32 sinceMs: number
33 tool: string | null
34 colorIndex: number | null
35 lead: string | null
36 lastOutcome: ActivityOutcome | null
37 turn: TurnClock | null
38}
39
40/**
41 * A running turn's clock, which leaves out the time the main loop waits on
42 * you: the total runs from `sinceMs` (the turn's start, moved on by the
43 * waits already over) to now, or to `pausedAtMs` while a wait is on.
44 */
45export type TurnClock = {
46 sinceMs: number
47 pausedAtMs: number | null
48}
49
50/**
51 * A subagent at work: what it was asked to do, its latest action, when it
52 * started, its palette slot (its spawn order in the session), and whether a
53 * call of its waits on your approval.
54 */
55export type ActivityAgent = {
56 name: string
57 label: string
58 sinceMs: number
59 colorIndex: number
60 isWaiting: boolean
61}
62
63/**
64 * One row of the expanded box: a prompt that started a turn, a stretch of
65 * thinking, a reply, a tool call, a compaction, or how a turn ended. `tool`
66 * names the tool of a `tool` row.
67 */
68export type ActivityEntry = {
69 kind: 'turn' | 'thought' | 'reply' | 'tool' | 'compact' | 'end'
70 label: string
71 durationMs: number | null
72 outcome: ActivityOutcome
73 tool: string | null
74}
75
76/**
77 * The look tail-claude-hud draws with, as `tail-claude-hud style --json`
78 * prints it (schema 1). Colors are mod color strings (`ansi256(N)`,
79 * `#rrggbb`), or empty for the terminal's default foreground.
80 */
81export type TchStyle = {
82 iconMode: string
83 icons: Readonly<Record<string, string>>
84 colors: Readonly<Record<string, string>>
85 agentColors: readonly string[]
86 toolCategories: {
87 byName: Readonly<Record<string, string>>
88 default: string
89 icons: Readonly<Record<string, string>>
90 }
91}
92
93/**
94 * Where the box's look came from: the HUD binary run with `preset` (empty
95 * for none), or the built-in look with the reason that binary could not
96 * supply one.
97 */
98export type TchStyleSource =
99 | { kind: 'hud'; binary: string; preset: string }
100 | { kind: 'builtin'; reason: string; binary: string; preset: string }
101
102/**
103 * The widest the box has been since the last turn ended (`columns`), and how
104 * many turns have ended, each of which set `columns` back to 0.
105 */
106export type BoxWidth = {
107 columns: number
108 turnEnds: number
109}
110
111declare module 'claude-code' {
112 interface PluginState {
113 'tch-activity': {
114 now: ActivityNow
115 history: readonly ActivityEntry[]
116 agents: readonly ActivityAgent[]
117 isExpanded: boolean
118 boxWidth: BoxWidth
119 style: TchStyle | null
120 styleSource: TchStyleSource | null
121 agentOrder: readonly string[]
122 lastTurn: { label: string; outcome: ActivityOutcome } | null
123 }
124 }
125}
126