SLOPSHOPPER

agentpane

A side pane for Claude Code that lists the subagents a session runs, what each is doing and what it costs in tokens, with each one's conversation a click away.

panebandguardcommandtoaststatus
★ 12v1.2.0MITupdated 2026-10-15xuanji86/claude-agentpane
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agentpane
│ ┃ Agents ✕ › fix the failing auth test and add an audit log call │ ┃ ✻ Agents │ ┃ No agents yet. They show here while they r ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ╷ › /agentpane │ ┃ │ ⎿ agentpane: Agents pane opened. │ ┃ ▸ │ ┃ │ │ ┃ ╵ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩
Pane · Agents
✻ Agents No agents yet. They show here while they run. ╷ │ ▸ │ ╵
README

agentpane

See your subagents at work, beside the conversation.<br> Every subagent a Claude Code session runs, what it is doing right now, what it costs in tokens, and its whole conversation one click away.

Version Claude Code mod License: MIT validates

English · 中文

<img src="assets/pane.svg" alt="The agents pane beside the transcript" width="760">

Why

When Claude fans work out to subagents, the terminal shows one line per agent and a footer list. agentpane is a mod that keeps them in a side pane, drawn the way Claude Code draws its own rows; click one and Claude Code's main view shows its conversation.

Features

Live list⏺ Type(description), the tool call it runs now, +N more tool uses, and ✶ Running… (1m 12s · Opus 5.5 · 412k in · 1.9k out), or ✻ Waiting… while it waits on its own background work; listed the moment it spawns
Nested agentsAn agent's own subagents sit indented under it
Tokens, model and effortInput (cached share shown), output, context size and requests per agent, from the API's own usage figures; the model and thinking effort each agent's requests actually use; max_tokens in red when a response was cut off
Other loopsModel loops no listed agent claims (a workflow's agents, compaction and memory forks), counted under the list
TimelineThe latest batch of agents on one time axis, a bar each: what ran side by side, and what took longest
Batch receiptOnce a batch ends: ✓ 4 agents in 31s · 1m 18s of agent time (2.5× in parallel) · 21 tool uses · 190k tokens
Status line✻ 2 of 4 agents running under the prompt while the pane is folded or closed
Follows the main viewThe agent you open from Claude Code's footer list is marked ◂ main view
ConversationsClick an agent: the main view switches to its transcript, and ◂ Main in the pane's header goes back. Where the main view can't switch (Claude Code before 2.1.300), it opens in the pane: its brief, replies in Markdown, tool calls with their results, runs of calls folded into one line
Stop■ Stop on a running agent's row, then Confirm stop, ends it through Claude Code's TaskStop
NoticesA toast when an agent finishes, one for several at once
Opens and folds itselfOpens when an agent starts, folds 10 s after the last one ends, to a tab above the prompt
Theme coloursClaude Code's own theme keys: follows dark, light and colourblind themes
Light on redrawsThe spinner, shimmer, clocks and timeline run on the terminal's own frame clock; the pane redraws only when something changes
Main screen tooWithout fullscreen, a summary of up to eight rows above the prompt instead of a side pane

Install

Needs Claude Code 2.1.287 or later, the release that brought mods (function hooks); tested on 2.1.300. The side pane needs the fullscreen layout (/tui fullscreen); on the main screen agentpane is a summary above the prompt. Mods are early access: their API may change between releases, and a release that breaks the pane gets a fix here.

/plugin marketplace add xuanji86/claude-agentpane
/plugin install agentpane@claude-agentpane
claude plugin marketplace add xuanji86/claude-agentpane
claude plugin install agentpane@claude-agentpane

Use

<table> <tr> <td width="60%" valign="top">

A conversation in the pane — before Claude Code 2.1.300

<img src="assets/conversation.svg" alt="One agent's conversation in the widened pane" width="100%">

Where the main view can't switch, clicking an agent opens its conversation here, and the pane widens to read it. ▲ ▼ step through it (k j), ← goes back (b); scrolled back, the view holds still while the agent writes on. Click a folded run of tool calls to open it.

</td> <td width="40%" valign="top">

Folded — the ▸ handle on the pane's left edge

<img src="assets/tab.svg" alt="The tab above the prompt" width="100%">

The pane hides and a tab above the prompt keeps the counts. Click it to bring the pane back; a new agent brings it back by itself.

</td> </tr> </table>

  • /agentpane opens or closes the pane.
  • 3 done in the header hides the finished agents (their running children stay in sight).
  • The pane opens by itself where Claude Code seats a pane nobody asked for: at least 144 columns (110 once you have opened it yourself). Below that, /agentpane opens it.
  • The keys b k j work while the pane holds the keyboard: it takes it when you open a conversation (over an empty prompt), Esc gives it back.

Configure

In /config, or under pluginConfigs["agentpane"].options in settings.json:

OptionDefaultMeaning
autoOpentrueopen the pane when an agent starts
foldAfter10seconds after the last agent finishes before the pane folds; 0 keeps it open
motiontrueanimate the spinner and shimmer; off, they stand still and the clocks still run
toaststruea toast when agents finish
keepFinished8finished agents the list keeps (1–30)
statusLinetruethe running agents under the prompt while the pane is not on screen

What it can reach

Its footprint, as the awesome-claude-code-mods scan reads it from claude plugin validate:

reach

agentpane watches, and acts only when you click an agent or press Stop. Every hook passes its event on unchanged.

It seesThrough
the session's agents and their status$.agent.list(), agent.spawn
each agent's tool calls (name and a short argument)tool.call
each agent's token usage and stop reasonturn.step
an agent's transcript, while you have it open$.session.messages({ agentId })
which agent the main view showsthe pane's view
the main view, switched to an agent you click (◂ Main back)$.ui.view

What it draws outside its pane: the tab above the prompt, toasts, and one status line ($.ui.status).

It makes no network requests, runs no processes, reads and writes no files, stores nothing across sessions and calls no model. Its actions are yours: switching the main view on your click, and Stop: Claude Code's own TaskStop, on your second press, naming the agent in a cleaned, shortened line. Text from transcripts is stripped of control, bidi and zero-width characters and cut to length before it is drawn. claude plugin validate . prints exactly what it hooks and calls.

What is inferred, not measured

  • Start times are when the pane first saw the agent: at its spawn, or, for one already running when agentpane loaded, the next poll.
  • Tokens count from when agentpane loaded; an agent that finished before then shows none.
  • Other loops cannot tell a workflow's agent from a compaction fork: both are model loops no listed agent claims.
  • Tool counts are the calls the pane saw, and show only for agents it watched.
  • A batch is the agents that ran with no quiet minute between them; the timeline and the receipt cover the latest. Agent time is the sum of their run times, so 2.5× in parallel is that sum over the batch's wall time.

Limits

  • The main view switches only on your click, and only from Claude Code 2.1.300 ($.ui.view). Before that, and in Claude Desktop until its own copy of Claude Code catches up, the conversation opens in the pane instead.
  • Workflow agents have no names to list: the engine does not hand them to mods. They count under other loops.

Troubleshooting

The pane doesn't appear. Check claude --version is 2.1.287 or later, run /reload-plugins, then /agentpane. Below 144 columns Claude Code won't seat a pane nobody asked for; /agentpane opens it at any width. Look in the transcript for a dim line starting agentpane:: it names a hook that failed or why the pane was refused. Please open an issue with it.

b k j do nothing. The pane needs the keyboard: click in it, or open a conversation over an empty prompt.

Too much motion. Set motion to false in /config.

Develop

git clone https://github.com/xuanji86/claude-agentpane
cd claude-agentpane
claude plugin validate .
claude plugin test .
claude --plugin-dir .        # or add the folder to CLAUDE_CODE_PLUGIN_DIRS

A session that loaded the mod from its folder reloads it each time you save a file. The tests draw the pane on every surface (terminal, desktop, VS Code, mobile) at 40–120 columns. python3 assets/make_previews.py redraws the README pictures. Changes are listed in CHANGELOG.md. Issues and pull requests are welcome.

License

MIT © Anji Xu

Source 5 files
hooks/register.tsx 1160 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register, RenderChildren, RenderElement, SessionMessage, TurnUsage } from 'claude-code'
3
4import type { AgentpaneAgent as Agent, AgentpaneLoop as Loop, AgentpaneTokens as Tokens } from '../types'
5import { fmtDuration, laneRows } from './time'
6import type { Lane } from './time'
7
8const PANE = 'agents'
9const TITLE = 'Agents'
10// lazy: polls the engine's agent list every second, as no agent-status event reaches a mod; move to one if it lands.
11const SYNC_MS = 1_000
12const CONFIRM_MS = 5_000 // a pressed Stop waits this long for the press that confirms it
13const SPAWN_GRACE_MS = 10_000 // a spawn the engine's list does not show yet stays this long
14const LOOP_SHOWN_MS = 60_000 // a model loop no agent claims shows while it made a request this recently
15const LOOP_KEPT_MS = 300_000 // and is forgotten after this long
16const INLINE_ROWS = 8 // the pane above the prompt, where it cannot dock: a summary
17const INLINE_READ_ROWS = 24 // and while it shows one conversation
18const PROMPT_LINES = 4 // a prompt is the agent's brief: its head is enough
19const PREVIEW_LINES = 3 // of a tool's result
20const MAX_BLOCKS = 40 // of a conversation, drawn at most
21// The engine refuses a tree with a text over 10,000 characters, or over 100,000 in all: stay well under.
22const MAX_ARG = 300 // characters of a tool call's argument kept
23const MAX_LINE = 500 // characters of one result line kept
24const MAX_REPLY = 6_000 // characters of one reply drawn as Markdown
25const TEXT_BUDGET = 60_000 // characters of a conversation drawn at once
26const GROUP_BUDGET = 30_000 // characters of one opened run of tool calls: its newest calls
27const GROUP_CALLS = 40 // and at most this many of them
28const PREVIEW_SCAN = 8_192 // characters of a tool's result read for its preview
29const MIN_ROWS = 3
30const BATCH_GAP_MS = 60_000 // an agent started this long after the last one ended begins a new batch
31const MAX_LANES = 8 // rows of the time axis
32const DUR_COLS = 8 // a lane's clock, right-aligned
33
34const agents = atom({ plugin: 'agentpane', key: 'agents' } as const, [])
35const activity = atom({ plugin: 'agentpane', key: 'activity' } as const, {})
36const viewing = atom({ plugin: 'agentpane', key: 'viewing' } as const, null)
37const scrollTop = atom({ plugin: 'agentpane', key: 'scrollTop' } as const, null)
38const rev = atom({ plugin: 'agentpane', key: 'rev' } as const, 0)
39const expanded = atom({ plugin: 'agentpane', key: 'expanded' } as const, [])
40const folded = atom({ plugin: 'agentpane', key: 'folded' } as const, false)
41const tab = atom({ plugin: 'agentpane', key: 'tab' } as const, false)
42const tokens = atom({ plugin: 'agentpane', key: 'tokens' } as const, {})
43const loops = atom({ plugin: 'agentpane', key: 'loops' } as const, {})
44const confirmStop = atom({ plugin: 'agentpane', key: 'confirmStop' } as const, null)
45const hideDone = atom({ plugin: 'agentpane', key: 'hideDone' } as const, false)
46
47// Colors are theme keys, so the pane follows the person's theme (dark, light, colorblind) as Claude Code's
48// own rows do. The spinner and shimmer live in live.tsx, on the surface's frame clock.
49const WIDE_SHARE = 0.62 // of the terminal, for the pane while it shows one agent's conversation
50const MIN_WIDE = 60
51const HANDLE_COLS = 2 // the hide handle's column, against the pane's left edge: its glyph and one space
52const RIGHT_MARGIN = 1 // matches that one space on the right, so the content sits centred
53// The handle: a tab several rows tall, each row of it a press target, so a click anywhere on it lands.
54const HANDLE = ['╷ ', '│ ', '▸ ', '│ ', '╵ ']
55const CLOSE_MARK_COLS = 3 // the engine draws its close mark over the end of the pane's first row
56const STOP_COLS = 7 // a row's "■ Stop" and the space before it
57const CONFIRM_COLS = 17 // a row's "[ Confirm stop ]" and the space before it
58const BAND_RIGHT_PAD = 5 // clear of the engine's [-] band toggle at the band's top right
59
60// The person's settings (`/config`, or pluginConfigs.agentpane.options in settings.json).
61export type Config = { autoOpen: boolean; foldAfterMs: number; motion: boolean; toasts: boolean; keepFinished: number; statusLine: boolean }
62export const parseConfig = (options: unknown): Config => {
63  const o = (options && typeof options === 'object' ? options : {}) as Record<string, unknown>
64  const num = (v: unknown, d: number, lo: number, hi: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : d)
65  const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d)
66  return {
67    autoOpen: bool(o.autoOpen, true),
68    foldAfterMs: num(o.foldAfter, 10, 0, 3600) * 1000,
69    motion: bool(o.motion, true),
70    toasts: bool(o.toasts, true),
71    keepFinished: num(o.keepFinished, 8, 1, 30),
72    statusLine: bool(o.statusLine, true),
73  }
74}
75let cfg = parseConfig(undefined) // set by register from the options it is given
76
77// "claude-sonnet-5-5" -> "Sonnet 5.5", "claude-haiku-4-5-20251001" -> "Haiku 4.5"; anything else as given.
78export const prettyModel = (id: string | undefined) => {
79  if (!id) return ''
80  const m = /^claude-([a-z]+)-(\d{1,2})(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/.exec(id)
81  if (!m) return id
82  const [, family = '', major, minor, wide] = m
83  return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${major}${minor ? `.${minor}` : ''}${wide ? ' (1M)' : ''}`
84}
85
86// How hard it is asked to think, as its requests name it: 'high', or a number where the model takes a budget.
87export const prettyEffort = (effort: string | number | undefined) =>
88  effort === undefined || effort === '' ? '' : typeof effort === 'number' ? `effort ${effort}` : effort
89
90// What an agent runs on, for a detail line: 'Opus 5.5 (1M) · high'.
91export const runsOn = (a: { model?: string; effort?: string | number }) =>
92  [prettyModel(a.model), prettyEffort(a.effort)].filter(Boolean).join(' · ')
93
94// How a status reads and shows, wherever an agent's status is drawn.
95export const look = (status: string): { word: string; mark: string; color?: string; dim?: boolean } =>
96  status === 'running' ? { word: 'Running', mark: '✻', color: 'claude' }
97  : status === 'waiting' ? { word: 'Waiting', mark: '✻', color: 'warning' }
98  : status === 'pending' ? { word: 'Starting', mark: '✻', color: 'claude', dim: true }
99  : status === 'idle' ? { word: 'Idle', mark: '·', dim: true }
100  : status === 'completed' ? { word: 'Done', mark: '✓', color: 'success' }
101  : status === 'failed' ? { word: 'Failed', mark: '✗', color: 'error' }
102  : status === 'killed' ? { word: 'Stopped', mark: '⊘', dim: true }
103  : { word: status, mark: '·', dim: true }
104
105// At work: not started yet, in a turn, or held (on its own background work, a plan's approval or, run in the
106// background, an Agent call). Not: ended (completed, failed, killed), or a teammate idle between turns, which may
107// stay idle for good and so holds no pane open and no status line.
108const LIVE = new Set(['pending', 'running', 'waiting'])
109export const isLive = (status: string) => LIVE.has(status)
110
111// Terminal columns a string takes: East Asian wide and fullwidth characters and emoji take two.
112// lazy: range table, not full Unicode East Asian Width; upgrade to a generated table if a script draws wrong.
113export const cols = (s: string) => {
114  let n = 0
115  for (const ch of s) {
116    const c = ch.codePointAt(0) ?? 0
117    const wide =
118      (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) ||
119      (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) ||
120      (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff) || (c >= 0x20000 && c <= 0x3fffd)
121    n += wide ? 2 : 1
122  }
123  return n
124}
125
126// Cut text to `max` columns with an ellipsis.
127export const fit = (s: string, max: number) => {
128  if (cols(s) <= max) return s
129  let out = ''
130  let n = 1
131  for (const ch of s) {
132    if (n + cols(ch) > max) break
133    n += cols(ch)
134    out += ch
135  }
136  return `${out}…`
137}
138
139// Text from the agents' transcripts: no control, escape or bidi characters; tabs as spaces; reminders the
140// engine injected left out.
141const UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g
142export const clean = (s: string) =>
143  s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').replace(/\t/g, '  ').replace(UNSAFE, '').trim()
144const oneLine = (s: string) => clean(s).replace(/\s+/g, ' ')
145
146// Word-wrap to `width` columns; a word longer than a line is cut where the line ends.
147export const wrap = (text: string, width: number): string[] => {
148  const w = Math.max(8, width)
149  const out: string[] = []
150  for (const para of text.split('\n')) {
151    let line = ''
152    let n = 0
153    for (const ch of para) {
154      if (n + cols(ch) > w) {
155        const cut = line.lastIndexOf(' ')
156        if (cut > 0 && cut >= line.length / 2) {
157          out.push(line.slice(0, cut))
158          line = line.slice(cut + 1)
159        } else {
160          out.push(line)
161          line = ''
162        }
163        n = cols(line)
164      }
165      line += ch
166      n += cols(ch)
167    }
168    out.push(line.trimEnd())
169  }
170  return out
171}
172
173// A tool call in Claude Code's words: "Bash(npm test)", "Read(register.tsx)", "github:list_issues".
174export const toolParts = (tool: string, input: Record<string, unknown>) => {
175  const s = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : '')
176  const base = (p: string) => p.split(/[\\/]/).pop() ?? p
177  const arg =
178    tool === 'Bash' ? s('command')
179    : ['Read', 'Write', 'Edit', 'NotebookEdit'].includes(tool) ? base(s('file_path') || s('notebook_path'))
180    : tool === 'Grep' || tool === 'Glob' ? s('pattern')
181    : tool === 'WebFetch' ? s('url')
182    : tool === 'WebSearch' ? s('query')
183    : tool === 'Agent' ? s('description')
184    : tool === 'Skill' ? s('skill')
185    : ''
186  return { name: tool.startsWith('mcp__') ? tool.split('__').slice(1).join(':') : tool, arg: fit(oneLine(arg), MAX_ARG) }
187}
188export const describeTool = (tool: string, input: Record<string, unknown>) => {
189  const { name, arg } = toolParts(tool, input)
190  return arg ? `${name}(${arg})` : name
191}
192
193// The engine's list over what the pane knew: when each was first seen, and when it was first seen done.
194export const mergeAgents = (before: readonly Agent[], list: readonly AgentInfo[], now: number): Agent[] => {
195  const prev = new Map(before.map(a => [a.id, a]))
196  const listed = new Set(list.map(a => a.id))
197  // A spawn the hook recorded that the engine's list does not show yet: kept a moment, not dropped.
198  const pending = before.filter(a => !listed.has(a.id) && isLive(a.status) && now - a.firstSeen < SPAWN_GRACE_MS)
199  const merged = list.map(info => {
200    const old = prev.get(info.id)
201    const live = isLive(info.status)
202    const seenRunning = (old?.seenRunning ?? false) || live
203    const endedAt = live ? undefined : (old?.endedAt ?? (seenRunning ? now : undefined))
204    const resumed = live && old?.endedAt !== undefined // ended, then sent a message: a new run from now
205    return {
206      id: info.id, description: info.description, type: info.type, status: info.status,
207      ...(info.name && { name: info.name }), ...(info.parentId && { parentId: info.parentId }),
208      firstSeen: resumed ? now : (old?.firstSeen ?? now), seenRunning, ...(endedAt !== undefined && { endedAt }),
209      ...(old?.model && { model: old.model }), ...(old?.effort !== undefined && { effort: old.effort }),
210    }
211  })
212  return [...merged, ...pending]
213}
214
215// A spawn as the pane records it the moment it starts, before the engine's list shows it.
216export const spawned = (list: readonly Agent[], a: Agent): Agent[] =>
217  list.some(x => x.id === a.id) ? list.map(x => (x.id === a.id ? { ...x, model: a.model ?? x.model } : x)) : [...list, a]
218
219// A model loop no agent claims, one more request.
220export const stepLoop = (all: Readonly<Record<string, Loop>>, id: string, now: number): Record<string, Loop> => {
221  const old = all[id]
222  return { ...all, [id]: { firstSeen: old?.firstSeen ?? now, lastSeen: now, requests: (old?.requests ?? 0) + 1 } }
223}
224
225// What the list shows: every running agent and the most recently finished ones, in the engine's order.
226export const visibleAgents = (all: readonly Agent[], keep = 8): Agent[] => {
227  const ended = (a: Agent, i: number) => [a.endedAt ?? a.firstSeen, i] as const
228  const recent = all
229    .map((a, i) => ({ a, key: ended(a, i) }))
230    .filter(({ a }) => !isLive(a.status))
231    .sort((x, y) => y.key[0] - x.key[0] || y.key[1] - x.key[1])
232    .slice(0, keep)
233    .map(({ a }) => a)
234  return all.filter(a => isLive(a.status) || recent.includes(a))
235}
236
237// Pure: the list as groups, each agent whose parent is not listed heading one with its descendants under
238// it; running groups first. With `onlyRunning`, finished agents are left out and their running children
239// head groups of their own.
240export const arrange = (shown: readonly Agent[], onlyRunning = false) => {
241  const list = onlyRunning ? shown.filter(a => isLive(a.status)) : shown
242  const ids = new Set(list.map(a => a.id))
243  const under = (id: string) => {
244    const out: { agent: Agent; depth: number }[] = []
245    const walk = (parent: string, depth: number) => {
246      if (depth > 3) return // a loop in the parents, or a tree deeper than the pane can indent
247      for (const a of list) if (a.parentId === parent) out.push({ agent: a, depth }), walk(a.id, depth + 1)
248    }
249    walk(id, 1)
250    return out
251  }
252  const tops = list.filter(a => !a.parentId || !ids.has(a.parentId)).map(a => ({ agent: a, kids: under(a.id) }))
253  return { running: tops.filter(t => isLive(t.agent.status)), finished: tops.filter(t => !isLive(t.agent.status)) }
254}
255
256const elapsed = (a: Agent, now: number) => (a.seenRunning ? fmtDuration((a.endedAt ?? now) - a.firstSeen) : '')
257
258// One response's usage added to an agent's tally; `context` is what its latest request carried.
259export const addUsage = (
260  t: Tokens | undefined,
261  u: Pick<TurnUsage, 'input_tokens' | 'output_tokens' | 'cache_read_input_tokens' | 'cache_creation_input_tokens'>,
262  stopReason: string | null = null,
263): Tokens => {
264  const input = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
265  const truncated = (t?.truncated ?? 0) + (stopReason === 'max_tokens' ? 1 : 0)
266  return {
267    ...(truncated && { truncated }),
268    input: (t?.input ?? 0) + input,
269    cached: (t?.cached ?? 0) + u.cache_read_input_tokens,
270    output: (t?.output ?? 0) + u.output_tokens,
271    context: input + u.output_tokens,
272    requests: (t?.requests ?? 0) + 1,
273  }
274}
275
276// "950", "12.3k", "312k", "1.2M".
277export const fmtTokens = (n: number) =>
278  n < 1000 ? String(n) : n < 99_950 ? `${+(n / 1000).toFixed(1)}k` : n < 999_500 ? `${Math.round(n / 1000)}k` : `${+(n / 1_000_000).toFixed(1)}M`
279
280export type CallState = 'running' | 'ok' | 'error' | 'stopped'
281export type Call = { id: string; name: string; arg: string; state: CallState; result: string[]; more: number }
282export type Block =
283  | { kind: 'prompt'; text: string }
284  | { kind: 'reply'; text: string }
285  | { kind: 'tools'; key: string; calls: Call[] }
286const STATE_COLOR: Record<CallState, string> = { running: 'claude', ok: 'success', error: 'error', stopped: 'inactive' }
287
288// A tool's result as its first lines, each cut to length, and how many more it had.
289// Only the head is cleaned and split; the rest, often megabytes, is counted by its newlines.
290export const preview = (text: string) => {
291  const lines = clean(text.slice(0, PREVIEW_SCAN)).split('\n').map(l => l.trimEnd()).filter(l => l.trim())
292  let rest = 0 // lazy: counts blank lines past the head too; exact would need the whole text split
293  for (let i = text.indexOf('\n', PREVIEW_SCAN); i !== -1; i = text.indexOf('\n', i + 1)) rest++
294  return { result: lines.slice(0, PREVIEW_LINES).map(l => fit(l, MAX_LINE)), more: Math.max(0, lines.length - PREVIEW_LINES) + rest }
295}
296
297// Pure: an agent's conversation as blocks: its brief (and any later message to it), each reply, and each
298// run of tool calls between them as one group. A call left unanswered by an agent that `ended` was cut off.
299export const transcriptBlocks = (msgs: readonly SessionMessage[], ended = false): Block[] => {
300  const out: Block[] = []
301  for (const m of msgs) {
302    const text = clean(m.text)
303    if (m.role === 'user') {
304      if (text) out.push({ kind: 'prompt', text })
305      continue
306    }
307    if (text) out.push({ kind: 'reply', text })
308    for (const use of m.toolUses) {
309      const { name, arg } = toolParts(use.tool, use.input)
310      const state: CallState = use.text === undefined ? (ended ? 'stopped' : 'running') : use.isError ? 'error' : 'ok'
311      const call: Call = { id: use.tool_use_id, name, arg, state, ...(use.text === undefined ? { result: [], more: 0 } : preview(use.text)) }
312      const last = out[out.length - 1]
313      if (last?.kind === 'tools') last.calls.push(call)
314      else out.push({ kind: 'tools', key: use.tool_use_id, calls: [call] })
315    }
316  }
317  return out
318}
319
320// Pure: the blocks to draw, within MAX_BLOCKS and the text budget: from `top` down when scrolled back, the
321// newest otherwise. Always at least one.
322export const pickBlocks = (blocks: readonly Block[], top: number | null) => {
323  const size = (b: Block) =>
324    b.kind === 'tools' ? b.calls.reduce((n, c) => n + c.arg.length + c.result.join('').length + 40, 0) : Math.min(b.text.length, MAX_REPLY) + 40
325  const out: Block[] = []
326  let used = 0
327  const take = (b: Block | undefined, add: (b: Block) => void) => {
328    if (!b || out.length >= MAX_BLOCKS) return false
329    used += size(b)
330    if (used > TEXT_BUDGET && out.length) return false
331    add(b)
332    return true
333  }
334  if (top === null) for (let i = blocks.length - 1; take(blocks[i], b => out.unshift(b)); i--);
335  else for (let i = Math.max(0, top); take(blocks[i], b => out.push(b)); i++);
336  return out
337}
338
339// Pure: the newest calls of an opened run that fit GROUP_BUDGET and GROUP_CALLS (always one), and how many
340// earlier ones are left out: an agent that only calls tools makes one run of hundreds.
341export const lastCalls = (calls: readonly Call[]) => {
342  let used = 0
343  let from = calls.length
344  while (from > 0 && calls.length - from < GROUP_CALLS) {
345    const c = calls[from - 1]!
346    used += c.arg.length + c.result.join('').length + 40
347    if (used > GROUP_BUDGET && from < calls.length) break
348    from--
349  }
350  return { shown: calls.slice(from), hidden: from }
351}
352
353// A run of tool calls in Claude Code's words: "Read 3 files, ran 2 commands".
354const VERBS: Record<string, [string, string, string]> = {
355  Read: ['read', 'file', 'files'], Bash: ['ran', 'command', 'commands'], Edit: ['edited', 'file', 'files'],
356  Write: ['wrote', 'file', 'files'], NotebookEdit: ['edited', 'notebook', 'notebooks'], Grep: ['searched for', 'pattern', 'patterns'],
357  Glob: ['searched for', 'pattern', 'patterns'], WebFetch: ['fetched', 'page', 'pages'], WebSearch: ['searched the web', 'time', 'times'],
358  Agent: ['ran', 'agent', 'agents'],
359}
360export const groupSummary = (calls: readonly Call[]) => {
361  const counts = new Map<string, number>()
362  for (const c of calls) counts.set(c.name, (counts.get(c.name) ?? 0) + 1)
363  const parts = [...counts].map(([name, n]) => {
364    const verb = VERBS[name]
365    return verb ? `${verb[0]} ${n} ${n === 1 ? verb[1] : verb[2]}` : `called ${name}${n > 1 ? ` ${n} times` : ''}`
366  })
367  const text = parts.join(', ')
368  return text.charAt(0).toUpperCase() + text.slice(1)
369}
370const groupState = (calls: readonly Call[]): CallState =>
371  calls.some(c => c.state === 'running') ? 'running'
372  : calls.some(c => c.state === 'error') ? 'error'
373  : calls.some(c => c.state === 'stopped') ? 'stopped'
374  : 'ok'
375
376// An agent's name as the pane, its toasts and its Stop say it: type and description, cleaned and cut.
377const nameOf = (a: Agent, max = 60) => `${fit(oneLine(a.type), 30)}(${fit(oneLine(a.description || a.type), max)})`
378
379// Pure: the toast for agents that finished since the last look, or null when none did.
380export const finishNotice = (before: readonly Agent[], after: readonly Agent[], now: number) => {
381  const ended = after.filter(a => !isLive(a.status) && before.some(b => b.id === a.id && isLive(b.status)))
382  if (!ended.length) return null
383  if (ended.length === 1) {
384    const a = ended[0]!
385    const l = look(a.status)
386    const t = elapsed(a, now)
387    return `${nameOf(a, 40)} ${l.mark} ${l.word.toLowerCase()}${t ? ` · ${t}` : ''}`
388  }
389  const failed = ended.filter(a => a.status === 'failed').length
390  return `✓ ${ended.length} agents finished${failed ? ` · ✗ ${failed} failed` : ''}`
391}
392
393const uses = (n: number) => `${n} tool use${n === 1 ? '' : 's'}`
394
395// Pure: the latest batch, oldest first: the agents that ran, back from the newest to a start more than
396// BATCH_GAP_MS after everything before it had ended.
397export const latestBatch = (all: readonly Agent[]): Agent[] => {
398  const ran = all.filter(a => a.seenRunning).sort((x, y) => x.firstSeen - y.firstSeen)
399  let start = 0
400  let reach = -Infinity // when the agents so far had all ended; never, while one runs
401  ran.forEach((a, i) => {
402    if (a.firstSeen > reach + BATCH_GAP_MS) start = i
403    reach = Math.max(reach, isLive(a.status) ? Infinity : (a.endedAt ?? a.firstSeen))
404  })
405  return ran.slice(start)
406}
407
408// Pure: what a batch of two or more came to, once none of it runs: how long it took, how much agent time
409// that was and so how much ran side by side, and what it used.
410export const batchReceipt = (
411  batch: readonly Agent[],
412  act: Readonly<Record<string, { tools: number }>>,
413  tok: Readonly<Record<string, Tokens>>,
414) => {
415  if (batch.length < 2 || batch.some(a => isLive(a.status))) return null
416  const end = (a: Agent) => a.endedAt ?? a.firstSeen
417  const wall = Math.max(...batch.map(end)) - Math.min(...batch.map(a => a.firstSeen))
418  // An agent's subagents run inside its own time: only the agents at the top of the batch add to it.
419  const work = batch.filter(a => !batch.some(p => p.id === a.parentId)).reduce((n, a) => n + end(a) - a.firstSeen, 0)
420  const count = (s: string) => batch.filter(a => a.status === s).length
421  const tools = batch.reduce((n, a) => n + (act[a.id]?.tools ?? 0), 0)
422  const used = batch.reduce((n, a) => n + (tok[a.id] ? tok[a.id]!.input + tok[a.id]!.output : 0), 0)
423  const together = wall > 0 ? work / wall : 1
424  const who = count('completed') === batch.length
425    ? `${batch.length} agents`
426    : [...new Set(['completed', 'failed', 'killed', ...batch.map(a => a.status)])]
427        .map(s => (count(s) ? `${count(s)} ${look(s).word.toLowerCase()}` : '')).filter(Boolean).join(' · ')
428  return {
429    failed: count('failed') > 0,
430    text: [
431      `${who} in ${fmtDuration(wall)}`,
432      `${fmtDuration(work)} of agent time${together >= 1.2 ? ` (${together.toFixed(1)}× in parallel)` : ''}`,
433      tools ? uses(tools) : '',
434      used ? `${fmtTokens(used)} tokens` : '',
435    ].filter(Boolean).join(' · '),
436  }
437}
438
439// Pure: the status line under the prompt while a batch runs, or undefined to clear it.
440export const statusOf = (batch: readonly Agent[]) => {
441  const live = batch.filter(a => isLive(a.status)).length
442  if (!live) return undefined
443  const waiting = batch.filter(a => a.status === 'waiting').length
444  const running = live - waiting
445  const failed = batch.filter(a => a.status === 'failed').length
446  const of =
447    !running ? `${waiting} agent${waiting === 1 ? '' : 's'} waiting`
448    : running === batch.length ? `${running} agent${running === 1 ? '' : 's'} running`
449    : `${running} of ${batch.length} agents running`
450  return `${look(running ? 'running' : 'waiting').mark} ${of}${running && waiting ? ` · ${waiting} waiting` : ''}${failed ? ` · ${look('failed').mark} ${failed} failed` : ''}`
451}
452
453// Module state that nothing draws from (a reload resets it to "nothing opened yet").
454let autoOpened = false // the mod opened the pane unasked, rather than the person
455let closedByPerson = false // closed by hand while agents ran: stays shut until a new one starts
456let foldingAway = false // the close under way is a fold: the tab above the prompt brings the pane back
457let foldWhenIdle = false // agents ran while the pane was open: fold it once they are all done
458let isFullscreen: boolean | undefined // from the last drawing: only the fullscreen layout docks a pane
459let lastPlacement: string | null = null
460let lastColumns = 0 // the terminal's width, from the last drawing
461let lastRunningAt = 0
462let armedAt = 0 // when Stop was pressed once
463let viewedNow: string | null = null // the agent the main view showed at the pane's last drawing
464// The status line as last set, so it is set only when it changes; null: not yet by this module, so a line a
465// reload left behind is cleared on the first sync.
466let lastStatus: string | undefined | null = null
467let viewingId: string | null = null // the conversation on screen, for the events that redraw it
468let transcript = { key: '', blocks: [] as Block[] } // that conversation's blocks, read once per change
469// lazy: one sync at a time by a module flag; a slow agent.list only skips ticks.
470let syncing = false
471// Agents the spawn hook listed since the last sync: new to the pane, though the list already holds them.
472const spawnedSinceSync = new Set<string>()
473
474// Never rejects. Keeps the list current, opens the pane when an agent starts, folds it once they are done.
475async function sync($: EngineInterface) {
476  if (syncing) return
477  syncing = true
478  try {
479    const now = await $.clock.now()
480    // The desktop app has its own agents view: where nothing else draws, nothing opens or shows unasked. It attaches
481    // only while its window shows the session, so a desktop session off screen draws on no surface at all.
482    const surfaces = await $.session.surfaces().catch((): readonly string[] => [])
483    const quiet = !surfaces.some(s => s !== 'desktop')
484    const info = await $.agent.list()
485    const before = await read($, agents)
486    let list = mergeAgents(before, info, now)
487    // Written over the list as it stands then, so an agent the spawn hook records meanwhile keeps its model.
488    if (JSON.stringify(list) !== JSON.stringify(before)) list = await update($, agents, cur => mergeAgents(cur, info, now))
489    const notice = finishNotice(before, list, now)
490    if (notice && cfg.toasts && !quiet) $.ui.toast(notice)
491    const ids = new Set(list.map(a => a.id))
492    if (Object.keys(await read($, activity)).some(id => !ids.has(id)))
493      await update($, activity, m => Object.fromEntries(Object.entries(m).filter(([id]) => ids.has(id))))
494
495    const running = list.filter(a => isLive(a.status))
496    const pane = (await $.ui.panes()).find(p => p.id === PANE)
497    // A new agent unfolds the pane, whoever folded or closed it, and shows the list.
498    const fresh = running.some(a => spawnedSinceSync.has(a.id) || !before.some(b => b.id === a.id))
499    for (const a of list) spawnedSinceSync.delete(a.id) // a spawn recorded after this list was read waits for the next
500    if (fresh) {
501      closedByPerson = false
502      // With autoOpen off the pane stays shut, and a fold the person made keeps its tab.
503      if (!pane && cfg.autoOpen) await showList($, { clearFold: true })
504    }
505    // The conversation on screen belongs to an agent no longer listed (/clear): back to the list, so it can fold.
506    const open = await read($, viewing)
507    if (open && !ids.has(open)) await showList($)
508    if (running.length) lastRunningAt = now
509    if (pane && running.length) foldWhenIdle = true
510    if (!pane && running.length && cfg.autoOpen && !quiet && !closedByPerson && !(await read($, folded))) {
511      autoOpened = true
512      await openPane($, 'list') // docked beside a fullscreen transcript, else the summary above the prompt
513    } else if (
514      pane && foldWhenIdle && !running.length && cfg.foldAfterMs > 0 && now - lastRunningAt >= cfg.foldAfterMs &&
515      !pane.isFocused && !viewedNow && !(await read($, viewing))
516    ) {
517      await foldAway($) // all done; not while the person reads a conversation
518    }
519    // Folded, the tab above the prompt stands in for the pane while the session has agents to show.
520    const showTab = (await read($, folded)) && list.length > 0
521    if (showTab !== (await read($, tab))) await update($, tab, () => showTab)
522    if ((await read($, confirmStop)) && now - armedAt > CONFIRM_MS) await update($, confirmStop, () => null)
523
524    // Loops that turned out to be agents, or went quiet long ago, are forgotten; tokens of neither go too.
525    const loopsNow = await read($, loops)
526    const keptLoops = Object.fromEntries(Object.entries(loopsNow).filter(([id, l]) => !ids.has(id) && now - l.lastSeen < LOOP_KEPT_MS))
527    if (Object.keys(keptLoops).length !== Object.keys(loopsNow).length) await update($, loops, () => keptLoops)
528    const kept = (id: string) => ids.has(id) || id in keptLoops
529    if (Object.keys(await read($, tokens)).some(id => !kept(id)))
530      await update($, tokens, m => Object.fromEntries(Object.entries(m).filter(([id]) => kept(id))))
531
532    // Under the prompt while a batch runs and the pane is not on screen (folded, closed, or waiting for room).
533    const placed = cfg.statusLine && (await $.ui.panes()).some(p => p.id === PANE && p.isPlaced && p.isShown)
534    const status = cfg.statusLine && !placed && !quiet ? statusOf(latestBatch(list)) : undefined
535    if (status !== lastStatus) {
536      lastStatus = status
537      $.ui.status(status)
538    }
539  } catch {
540    // the next tick tries again
541  } finally {
542    syncing = false
543  }
544}
545
546// Back to the list, live, nothing armed; `clearFold` also clears the fold.
547async function showList($: EngineInterface, { clearFold = false } = {}) {
548  await update($, viewing, () => null)
549  await update($, scrollTop, () => null)
550  await update($, expanded, () => [])
551  await update($, confirmStop, () => null)
552  if (clearFold) await update($, folded, () => false)
553}
554
555// The pane sized for what it shows: docked, at its usual width or widened to read a conversation; above the
556// prompt, a summary's rows or a conversation's. `focus` asks for the keyboard (granted over an empty
557// composer), so the conversation's b/k/j keys work.
558async function openPane($: EngineInterface, view: 'list' | 'conversation', focus = false) {
559  const docked = lastPlacement ? lastPlacement === 'dock' : isFullscreen !== false
560  const columns = docked && view === 'conversation' && lastColumns ? Math.max(MIN_WIDE, Math.round(lastColumns * WIDE_SHARE)) : undefined
561  const rows = docked ? undefined : view === 'conversation' ? INLINE_READ_ROWS : INLINE_ROWS
562  await $.ui.open({ id: PANE, title: TITLE, ...(columns && { columns }), ...(rows && { rows }), ...(focus && { focus: true as const }) })
563}
564
565// Fold: the pane closes, so the transcript has the width back, and a tab above the prompt reopens it.
566async function foldAway($: EngineInterface) {
567  await update($, folded, () => true)
568  await update($, tab, () => true)
569  foldingAway = true
570  try {
571    await $.ui.close({ id: PANE })
572  } finally {
573    foldingAway = false
574  }
575}
576
577// The person unfolds it from the tab: theirs now, so it folds again only after agents run in it.
578async function unfold($: EngineInterface) {
579  await update($, folded, () => false)
580  await update($, tab, () => false)
581  closedByPerson = false
582  autoOpened = false
583  foldWhenIdle = (await read($, agents)).some(a => isLive(a.status))
584  await openPane($, (await read($, viewing)) ? 'conversation' : 'list')
585}
586
587// Stop pressed once on an agent: armed for CONFIRM_MS, and a second press stops it.
588async function armStop($: EngineInterface, id: string) {
589  armedAt = await $.clock.now()
590  await update($, confirmStop, () => id)
591}
592
593// Puts an agent's transcript in the main view, or with no id the main conversation; whether the view moved.
594// Called before the press it answers awaits anything: the engine moves the view only while answering the person.
595function viewIn($: EngineInterface, agentId?: string): Promise<boolean> {
596  try {
597    return $.ui.view(agentId ? { agentId } : {}).then(r => !r.deny, () => false)
598  } catch {
599    return Promise.resolve(false) // a Claude Code before $.ui.view
600  }
601}
602
603// Stop a running agent with Claude Code's own TaskStop, on the person's confirmed press of Stop.
604async function stopAgent($: EngineInterface, a: Agent) {
605  const name = nameOf(a)
606  const done = (await $.tool
607    // The consent reads to the engine as the person's words: the type and id, never the description a model wrote.
608    .call({ tool: 'TaskStop', task_id: a.id, consent: `The user pressed "Stop" on the ${JSON.stringify(fit(oneLine(a.type), 30))} agent ${fit(a.id, 40)} in the agents pane` } as never)
609    .catch((err: unknown) => ({ deny: String(err) }))) as { deny?: string; isError?: boolean; text?: string }
610  const why = done.deny || (done.isError ? oneLine(String(done.text ?? '')) || 'the tool reported an error' : '')
611  if (why) $.ui.toast(`Could not stop ${name}: ${fit(why, 120)}`)
612}
613
614// The conversation on screen changed: draw it again.
615const redraw = ($: EngineInterface, agentId: string | undefined) => {
616  if (agentId && agentId === viewingId) void update($, rev, n => n + 1).catch(() => undefined)
617}
618
619export const register: Register = (on, options) => {
620  cfg = parseConfig(options)
621
622  on('session.start', async ($, e, next) => {
623    await $.command.register({ name: 'agentpane', description: 'Show or hide the pane of running agents' })
624    $.clock.every(SYNC_MS, () => void sync($))
625    return next(e)
626  })
627
628  on('command.run', { command: 'agentpane' }, async $ => {
629    const pane = (await $.ui.panes()).find(p => p.id === PANE)
630    if (pane?.isPlaced) {
631      await $.ui.close({ id: PANE })
632      return { text: 'Agents pane closed.' }
633    }
634    autoOpened = false // opened by hand: the mod leaves it open
635    closedByPerson = false
636    foldWhenIdle = false
637    await update($, folded, () => false)
638    await update($, tab, () => false)
639    await openPane($, 'list', true) // asked for, so placed even where an unasked pane waits
640    return { text: 'Agents pane opened.' }
641  })
642
643  on('ui.close', async ($, e, next) => {
644    const result = await next(e)
645    if (e.id === PANE && !('deny' in result && result.deny)) {
646      foldWhenIdle = false
647      autoOpened = false
648      await update($, confirmStop, () => null)
649      if (!foldingAway) {
650        // closed by hand (its close mark, Esc, ctrl+x x, /agentpane) while agents run: stays shut until a new one starts
651        closedByPerson = (await read($, agents)).some(a => isLive(a.status))
652        await update($, viewing, () => null)
653      }
654    }
655    return result
656  })
657
658  // What each agent is doing: its latest tool call; and its conversation, if on screen, grows.
659  on('tool.call', async ($, e, next) => {
660    const id = e.agentId
661    if (id) {
662      const text = describeTool(e.tool, e as unknown as Record<string, unknown>)
663      void update($, activity, m => ({ ...m, [id]: { text, tools: (m[id]?.tools ?? 0) + 1 } })).catch(() => undefined)
664      redraw($, id)
665    }
666    const result = await next(e)
667    redraw($, id)
668    return result
669  })
670
671  // An agent is listed the moment it starts, with the model it runs on, ahead of the next poll.
672  on('agent.spawn', async ($, e, next) => {
673    const started = await next(e)
674    const id = started.agentId
675    if (id && !started.deny) {
676      const a: Agent = {
677        id, description: e.description, type: e.subagentType, status: 'running',
678        ...(e.parentAgentId && { parentId: e.parentAgentId }), ...(e.name && { name: e.name }),
679        firstSeen: await $.clock.now(), seenRunning: true, ...(started.model && { model: started.model }),
680      }
681      spawnedSinceSync.add(id)
682      void update($, agents, list => spawned(list, a)).catch(() => undefined)
683    }
684    return started
685  })
686
687  // What each agent's responses cost, as the API reported each one; a response grows its conversation. A
688  // loop no listed agent claims (a workflow's agent, a compaction or memory fork) is counted on its own.
689  on('turn.step', async function* ($, e, next) {
690    const result = yield* next(e)
691    const id = e.agentId
692    if (id) {
693      const usage = result?.usage
694      if (usage) void update($, tokens, m => ({ ...m, [id]: addUsage(m[id], usage, result.stopReason) })).catch(() => undefined)
695      const listed = (await read($, agents)).find(a => a.id === id)
696      // The model and effort its requests name, as the engine resolved them: an agent whose spawn named no model (a
697      // forked skill, an inherited model) still shows what it runs on, and an alias the spawn gave ('sonnet') reads as
698      // the real id. Effort is the step's alone (a spawn reports none); absent for a model without it.
699      if (listed && ((e.model && listed.model !== e.model) || listed.effort !== e.effort)) {
700        const ran = { ...(e.model && { model: e.model }), effort: e.effort }
701        void update($, agents, l => l.map(a => (a.id === id ? { ...a, ...ran } : a))).catch(() => undefined)
702      }
703      if (!listed) {
704        const now = await $.clock.now()
705        void update($, loops, l => stepLoop(l, id, now)).catch(() => undefined)
706      }
707    }
708    redraw($, id)
709    return result
710  })
711
712  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
713    const els = $.ui.resolve(e)
714    const { Box, Button, Markdown, Text } = els
715    // Live lines run on the surface's own frame clock where it has one (terminal, desktop); elsewhere they are
716    // static. Every surface's table names Client, but on the others it draws nothing: ask by surface.
717    const Client = (e.surface === 'terminal' || e.surface === 'desktop') && 'Client' in els ? els.Client : null
718    lastPlacement = e.props.placement
719    lastColumns = e.viewport?.columns ?? lastColumns
720    isFullscreen = e.viewport?.isFullscreen ?? isFullscreen
721    const inline = e.props.placement === 'inline' // above the prompt: a summary, no handle
722    const W = Math.max(22, e.props.bodyColumns - (inline ? 0 : HANDLE_COLS) - RIGHT_MARGIN) // the content, right of the handle
723    const viewed = e.props.view?.agentId ?? null // the agent the person has open in the main view
724    viewedNow = viewed
725    const rows = Math.max(MIN_ROWS + 6, e.props.scroll.bodyRows)
726    const now = await $.clock.now()
727    const all = await read($, agents)
728    const act = await read($, activity)
729    const tok = await read($, tokens)
730    const id = await read($, viewing)
731    const agent = id ? all.find(a => a.id === id) : undefined
732    viewingId = agent ? agent.id : null
733    const liveCount = all.filter(a => isLive(a.status)).length
734    const waitingCount = all.filter(a => a.status === 'waiting').length
735    const doneCount = all.length - liveCount
736    const active = [liveCount - waitingCount ? `${liveCount - waitingCount} running` : '', waitingCount ? `${waitingCount} waiting` : ''].filter(Boolean).join(' · ')
737    const hint = (text: string) => <Text dimColor wrap="truncate-end">{text}</Text>
738    const alertOf = (a: Agent) => (tok[a.id]?.truncated ? `max_tokens ×${tok[a.id]!.truncated}` : '')
739    // A running agent's spinner, shimmering "Running…" and clock, redrawn by the surface, not by this hook.
740    const liveLine = (a: Agent, pad: string, detail: string) => {
741      const l = look(a.status)
742      const word = `${l.word}…`
743      return Client && a.seenRunning ? (
744        <Client
745          key={`live-${a.id}`}
746          module="./live.tsx"
747          props={{ since: a.firstSeen, now, pad, detail, alert: alertOf(a), word, mark: l.mark, color: l.color, dim: !!l.dim, motion: cfg.motion && a.status === 'running', clockOnly: false }}
748        />
749      ) : (
750        <Text wrap="truncate-end">
751          <Text color={l.color} dimColor={l.dim}>{`${pad}  ${l.mark} ${word}`}</Text>
752          <Text dimColor>{` (${[elapsed(a, now), detail].filter(Boolean).join(' · ')}`}</Text>
753          {alertOf(a) ? <Text color="error">{` · ${alertOf(a)}`}</Text> : null}
754          <Text dimColor>)</Text>
755        </Text>
756      )
757    }
758    const clock = (a: Agent) =>
759      Client && isLive(a.status) && a.seenRunning ? (
760        <Client key={`clock-${a.id}`} module="./live.tsx" props={{ since: a.firstSeen, now, pad: '', detail: '', alert: '', word: '', mark: '', dim: true, motion: false, clockOnly: true }} />
761      ) : (
762        <Text dimColor>{elapsed(a, now)}</Text>
763      )
764    // The first row, clear of the engine's close mark at its end.
765    const header = (left: RenderChildren, right: RenderChildren) => (
766      <Box width={W - CLOSE_MARK_COLS} justifyContent="space-between">
767        {left}
768        {typeof right === 'string' ? <Text dimColor>{right}</Text> : right}
769      </Box>
770    )
771    // A handle on the pane's left edge, halfway down: ▸ hides the pane. Above the prompt there is no edge to hold.
772    const withHandle = (body: RenderChildren) =>
773      inline ? (
774        <Box flexDirection="column" width={W}>
775          {body}
776        </Box>
777      ) : (
778      <Box flexDirection="row">
779        <Box key="handle" flexDirection="column" width={HANDLE_COLS} flexShrink={0}>
780          {Array.from({ length: Math.max(0, Math.floor((rows - HANDLE.length) / 2)) }, () => <Text> </Text>)}
781          {HANDLE.map((glyph, i) => (
782            <Button
783              key={glyph.startsWith('▸') ? 'collapse' : `collapse-${i}`}
784              label={glyph}
785              plain
786              dimColor
787              hover={{ color: 'claude', bold: true }}
788              onPress={() => foldAway($)}
789            />
790          ))}
791        </Box>
792        <Box flexDirection="column" width={W} height={rows}>
793          {body}
794        </Box>
795      </Box>
796      )
797
798    // One agent's conversation, as Claude Code draws its own: > the brief, ⏺ replies and tool calls, ⎿ results.
799    if (agent) {
800      const key = `${agent.id}:${await read($, rev)}:${agent.status}`
801      if (transcript.key !== key) {
802        const msgs = await $.session.messages({ agentId: agent.id })
803        transcript = { key, blocks: Array.isArray(msgs) ? transcriptBlocks(msgs, !isLive(agent.status)) : [] }
804      }
805      const blocks = transcript.blocks
806      const open = new Set(await read($, expanded))
807      const armed = await read($, confirmStop)
808      const savedTop = await read($, scrollTop)
809      const top = savedTop === null ? null : Math.min(savedTop, Math.max(0, blocks.length - 1))
810      const shown = pickBlocks(blocks, top)
811      const newer = top === null ? 0 : blocks.length - top - 1 // blocks after the one at the top
812      const used = tok[agent.id]
813      const l = look(agent.status)
814      const leave = async () => {
815        await showList($)
816        await openPane($, 'list') // back to the usual size
817      }
818      const toggle = (k: string) => update($, expanded, list => (list.includes(k) ? list.filter(x => x !== k) : [...list, k]))
819      const result = (c: Call) =>
820        c.state === 'running' ? [<Text color="claude">{'  ⎿  Running…'}</Text>]
821        : c.state === 'stopped' ? [<Text dimColor>{'  ⎿  Interrupted'}</Text>]
822        : [
823            ...(c.result.length ? c.result : ['(No output)']).map((r, i) => (
824              <Text color={c.state === 'error' ? 'error' : undefined} dimColor={c.state !== 'error'} wrap="truncate-end">
825                {`${i ? '     ' : '  ⎿  '}${r}`}
826              </Text>
827            )),
828            ...(c.more ? [<Text dimColor>{`     … +${c.more} line${c.more === 1 ? '' : 's'}`}</Text>] : []),
829          ]
830      const call = (c: Call) => (
831        <Box flexDirection="column" flexShrink={0}>
832          <Text wrap="truncate-end">
833            <Text color={STATE_COLOR[c.state]}>⏺ </Text>
834            <Text bold>{c.name}</Text>
835            <Text>{c.arg ? `(${c.arg})` : ''}</Text>
836          </Text>
837          {result(c)}
838        </Box>
839      )
840      const block = (b: Block): RenderElement => {
841        if (b.kind === 'prompt') {
842          const lines = wrap(b.text.slice(0, PROMPT_LINES * W * 2), W - 2)
843          return (
844            <Box flexDirection="column" flexShrink={0} marginTop={1}>
845              {lines.slice(0, PROMPT_LINES).map((line, i) => (
846                <Text dimColor wrap="truncate-end">{`${i ? '  ' : '> '}${line}`}</Text>
847              ))}
848              {lines.length > PROMPT_LINES ? <Text dimColor>{'  …'}</Text> : null}
849            </Box>
850          )
851        }
852        if (b.kind === 'reply') {
853          const text = b.text.length > MAX_REPLY ? `${b.text.slice(0, MAX_REPLY)}\n\n… (${b.text.length - MAX_REPLY} more characters)` : b.text
854          return (
855            <Box flexDirection="row" flexShrink={0} marginTop={1}>
856              <Text>⏺ </Text>
857              <Box flexDirection="column" width={W - 2}>
858                <Markdown text={text} />
859              </Box>
860            </Box>
861          )
862        }
863        if (b.calls.length === 1) return <Box flexShrink={0} marginTop={1}>{call(b.calls[0]!)}</Box>
864        const isOpen = open.has(b.key)
865        const opened = lastCalls(b.calls)
866        const live = b.calls.find(c => c.state === 'running')
867        const failed = b.calls.find(c => c.state === 'error')
868        return (
869          <Box key={`grp-${b.key}`} flexDirection="column" flexShrink={0} marginTop={1}>
870            <Box>
871              <Text color={STATE_COLOR[groupState(b.calls)]}>⏺ </Text>
872              <Button key={`group-${b.key}`} label={groupSummary(b.calls)} plain hover={{ color: 'claude' }} onPress={() => toggle(b.key)} />
873              <Text dimColor>{isOpen ? ' (click to collapse)' : ' (click to expand)'}</Text>
874            </Box>
875            {isOpen ? (
876              <Box flexDirection="column" paddingLeft={2}>
877                {opened.hidden ? <Text dimColor>{`… +${opened.hidden} earlier call${opened.hidden === 1 ? '' : 's'}`}</Text> : null}
878                {opened.shown.map(call)}
879              </Box>
880            ) : live ? (
881              <Text color="claude" wrap="truncate-end">{`  ⎿  ${live.name}${live.arg ? `(${live.arg})` : ''} · Running…`}</Text>
882            ) : failed ? (
883              <Text color="error" wrap="truncate-end">{`  ⎿  ${failed.name} failed: ${failed.result[0] ?? ''}`}</Text>
884            ) : null}
885          </Box>
886        )
887      }
888      return withHandle([
889        header(
890          <Box>
891            <Button key="back" label="←" hotkey="b" dimColor onPress={leave} />
892            <Text color={l.color} dimColor={l.dim}> ⏺ </Text>
893            <Text bold>{fit(oneLine(agent.type), 20)}</Text>
894            <Text>{`(${fit(oneLine(agent.description), Math.max(8, W - 42 - cols(agent.type)))})`}</Text>
895          </Box>,
896          <Box>
897            {clock(agent)}
898            {!isLive(agent.status) ? null : armed === agent.id ? (
899              <Button key="stop" label="Confirm stop" variant="primary" onPress={() => update($, confirmStop, () => null).then(() => stopAgent($, agent))} />
900            ) : (
901              <Button key="stop" label="■ Stop" dimColor onPress={() => armStop($, agent.id)} />
902            )}
903          </Box>,
904        ),
905        <Text wrap="truncate-end">
906          <Text dimColor>
907            {`  ⎿  ${[l.word, act[agent.id] ? uses(act[agent.id]!.tools) : '', runsOn(agent), viewed === agent.id ? 'also in the main view' : ''].filter(Boolean).join(' · ')}`}
908          </Text>
909          {alertOf(agent) ? <Text color="error">{` · ${alertOf(agent)}`}</Text> : null}
910        </Text>,
911        <Text dimColor wrap="truncate-end">
912          {used
913            ? `     ${fmtTokens(used.input)} in (${fmtTokens(used.cached)} cached) · ${fmtTokens(used.output)} out · context ${fmtTokens(used.context)} · ${used.requests} request${used.requests === 1 ? '' : 's'}`
914            : '     no token figures yet'}
915        </Text>,
916        // Live: the newest blocks, anchored to the bottom (the oldest cut at the top). Scrolled back: from the
917        // block at `top` down, so a block taller than the pane shows its start and new blocks do not move it.
918        <Box height={rows - 5} flexDirection="column" justifyContent={top === null ? 'flex-end' : 'flex-start'} overflow="hidden">
919          {shown.length ? shown.map(block) : <Text dimColor>Its conversation is not available yet.</Text>}
920        </Box>,
921        <Text> </Text>,
922        <Box width={W} justifyContent="space-between">
923          <Box>
924            <Button key="older" label="▲" hotkey="k" dimColor onPress={() => update($, scrollTop, v => Math.max(0, (v ?? blocks.length - 1) - 1))} />
925            <Button
926              key="newer"
927              label="▼"
928              hotkey="j"
929              dimColor
930              onPress={() => update($, scrollTop, v => (v === null || v + 1 >= blocks.length - 1 ? null : v + 1))}
931            />
932            {top === null ? (
933              <Text color="success"> ● live</Text>
934            ) : (
935              <Button key="live" label={newer > 0 ? `⇣ ${newer} newer` : '⇣ live'} onPress={() => update($, scrollTop, () => null)} />
936            )}
937          </Box>
938          {hint(e.props.isFocused ? 'b back · k/j scroll · esc to prompt ' : 'click here for keys b/k/j ')}
939        </Box>,
940      ])
941    }
942
943    // The list, as Claude Code draws an Agent call: ⏺ Type(description), ⎿ what it does, and a status line.
944    const shown = visibleAgents(all, cfg.keepFinished)
945    const hidingDone = await read($, hideDone)
946    const { running, finished } = arrange(shown, hidingDone)
947    // The agent's transcript in the main view; where it cannot go there (a Claude Code before $.ui.view, a
948    // refusal), its conversation in the pane.
949    const goTo = (to: string) =>
950      viewIn($, to).then(async shown => {
951        if (shown) return
952        await showList($)
953        await update($, viewing, () => to)
954        await openPane($, 'conversation', true)
955      })
956    const armed = await read($, confirmStop)
957    // Stop on a live agent's row: pressed once it asks to be pressed again.
958    const stopButton = (a: Agent) =>
959      armed === a.id ? (
960        <Button key={`stop-${a.id}`} label="Confirm stop" variant="primary" onPress={() => update($, confirmStop, () => null).then(() => stopAgent($, a))} />
961      ) : (
962        <Button key={`stop-${a.id}`} label="■ Stop" dimColor onPress={() => armStop($, a.id)} />
963      )
964    // Model loops no agent claims, recently active: a workflow's agents, compaction and memory forks.
965    const quiet = Object.entries(await read($, loops)).filter(([, x]) => now - x.lastSeen < LOOP_SHOWN_MS)
966    const loopsLine = quiet.length
967      ? `⏺ ${quiet.length} other model loop${quiet.length === 1 ? '' : 's'} (workflow agents or forks) · ${quiet.reduce((n, [, x]) => n + x.requests, 0)} requests · ${fmtTokens(quiet.reduce((n, [lid]) => n + (tok[lid]?.input ?? 0), 0))} in`
968      : ''
969    // The latest batch on one time axis (two agents or more, where there is room), and once it has ended,
970    // what it came to.
971    const batch = latestBatch(all)
972    const receipt = batchReceipt(batch, act, tok)
973    const receiptLine = receipt ? (
974      <Text wrap="truncate-end">
975        <Text color={receipt.failed ? 'error' : 'success'}>{receipt.failed ? '✗ ' : '✓ '}</Text>
976        <Text dimColor>{receipt.text}</Text>
977      </Text>
978    ) : null
979    const nameCols = Math.min(30, Math.floor(W * 0.38))
980    const barCols = W - 2 - nameCols - 1 - DUR_COLS
981    const onAxis = batch.length >= 2 && barCols >= 8 ? batch.slice(-Math.min(MAX_LANES, Math.floor(rows / 3))) : []
982    const lanes: Lane[] = onAxis.map(a => {
983      const l = look(a.status)
984      const name = fit(oneLine(a.description || a.type), nameCols)
985      return {
986        name: name + ' '.repeat(Math.max(0, nameCols - cols(name))), mark: l.mark, color: l.color ?? '', dim: !!l.dim,
987        from: a.firstSeen, to: isLive(a.status) ? null : (a.endedAt ?? a.firstSeen),
988      }
989    })
990    const axisTitle = ` timeline${onAxis.length < batch.length ? ` · latest ${onAxis.length} of ${batch.length}` : ''} `
991    const axis = lanes.length ? (
992      <Box flexDirection="column" flexShrink={0} marginTop={1}>
993        <Text dimColor wrap="truncate-end">{`──${axisTitle}${'─'.repeat(Math.max(0, W - 2 - axisTitle.length))}`}</Text>
994        {Client ? (
995          <Client key="lanes" module="./lanes.tsx" props={{ lanes, now, bar: barCols }} />
996        ) : (
997          laneRows(lanes, now, barCols).map((g, i) => (
998            <Text wrap="truncate-end">
999              <Text color={lanes[i]!.color || undefined} dimColor={lanes[i]!.dim}>{`${lanes[i]!.mark} `}</Text>
1000              <Text>{lanes[i]!.name}</Text>
1001              <Text dimColor>{` ${'·'.repeat(g.before)}`}</Text>
1002              <Text color={lanes[i]!.color || undefined} dimColor={lanes[i]!.dim}>{'━'.repeat(g.bar)}</Text>
1003              <Text dimColor>{`${'·'.repeat(g.after)}${fmtDuration(g.ms).padStart(DUR_COLS)}`}</Text>
1004            </Text>
1005          ))
1006        )}
1007        {receiptLine}
1008      </Box>
1009    ) : receiptLine ? (
1010      <Box flexShrink={0} marginTop={1}>
1011        {receiptLine}
1012      </Box>
1013    ) : null
1014    const mark = (a: Agent) => (viewed === a.id ? ' ◂ main view' : '')
1015    const counts = <Box key="counts">
1016      <Text dimColor>{active}</Text>
1017      <Text dimColor>{active && doneCount ? ' · ' : ''}</Text>
1018      {doneCount ? (
1019        <Button key="toggle-done" label={hidingDone ? `${doneCount} done (show)` : `${doneCount} done`} plain dimColor hover={{ color: 'claude', underline: true }} onPress={() => update($, hideDone, v => !v)} />
1020      ) : null}
1021    </Box>
1022
1023    // Above the prompt (no fullscreen to dock in): a summary of at most INLINE_ROWS rows.
1024    if (inline) {
1025      const live = all.filter(a => isLive(a.status)) // a finished parent's running children too
1026      const SHOW = INLINE_ROWS - 3
1027      const ended = (s2: string) => all.filter(a => a.status === s2).length
1028      const tally = ['completed', 'failed', 'killed'].map(s2 => (ended(s2) ? `${look(s2).mark} ${ended(s2)} ${look(s2).word.toLowerCase()}` : '')).filter(Boolean)
1029      return (
1030        <Box flexDirection="column" width={W}>
1031          {header(
1032            <Text>
1033              <Text color="claude">✻ </Text>
1034              <Text bold>Agents</Text>
1035            </Text>,
1036            <Box>
1037              {counts}
1038              <Text> </Text>
1039              <Button key="collapse" label="▾ hide" dimColor onPress={() => foldAway($)} />
1040            </Box>,
1041          )}
1042          {live.slice(0, SHOW).map(a => {
1043            const room = Math.max(10, Math.floor(W * 0.45))
1044            return (
1045              <Box key={`row-${a.id}`} width={W} justifyContent="space-between">
1046                <Box>
1047                  <Text color="claude">⏺ </Text>
1048                  <Button key={`agent-${a.id}`} label={fit(nameOf(a, room), room)} plain hover={{ color: 'claude', underline: true }} onPress={() => goTo(a.id)} />
1049                  <Text dimColor wrap="truncate-end">{act[a.id] ? `  ⎿ ${fit(act[a.id]!.text, Math.max(6, W - room - 14))}` : ''}</Text>
1050                </Box>
1051                {clock(a)}
1052              </Box>
1053            )
1054          })}
1055          {live.length > SHOW ? <Text dimColor>{`  +${live.length - SHOW} more running`}</Text> : null}
1056          {receiptLine ?? (tally.length || loopsLine ? <Text dimColor wrap="truncate-end">{[tally.join(' · '), loopsLine.replace('⏺ ', '')].filter(Boolean).join(' · ')}</Text> : null)}
1057          {shown.length ? null : <Text dimColor>No agents yet.</Text>}
1058        </Box>
1059      )
1060    }
1061    const agentBlock = (a: Agent, depth: number) => {
1062      const pad = '    '.repeat(depth)
1063      const l = look(a.status)
1064      const doing = act[a.id]
1065      const used = tok[a.id]
1066      const t = elapsed(a, now)
1067      const model = runsOn(a)
1068      const stopCols = isLive(a.status) ? (armed === a.id ? CONFIRM_COLS : STOP_COLS) : 0
1069      const lines: RenderChildren[] = [
1070        <Box key={`row-${a.id}`} width={W} justifyContent="space-between">
1071          <Box>
1072            <Text color={l.color} dimColor={l.dim}>{`${pad}⏺ `}</Text>
1073            <Button key={`agent-${a.id}`} label={fit(nameOf(a, W), W - cols(pad) - 2 - cols(mark(a)) - stopCols)} plain hover={{ color: 'claude', underline: true }} onPress={() => goTo(a.id)} />
1074            <Text color="claude">{mark(a)}</Text>
1075          </Box>
1076          {isLive(a.status) ? stopButton(a) : null}
1077        </Box>,
1078      ]
1079      if (isLive(a.status)) {
1080        if (doing) {
1081          lines.push(<Text dimColor wrap="truncate-end">{`${pad}  ⎿  ${fit(doing.text, W)}`}</Text>)
1082          if (doing.tools > 1) lines.push(<Text dimColor>{`${pad}     +${doing.tools - 1} more tool use${doing.tools === 2 ? '' : 's'}`}</Text>)
1083        }
1084        lines.push(liveLine(a, pad, [model, used ? `${fmtTokens(used.input)} in` : '', used ? `${fmtTokens(used.output)} out` : ''].filter(Boolean).join(' · ')))
1085      } else {
1086        const detail = [doing ? uses(doing.tools) : '', used ? `${fmtTokens(used.input + used.output)} tokens` : '', model, t].filter(Boolean).join(' · ')
1087        lines.push(
1088          <Text wrap="truncate-end">
1089            <Text color={a.status === 'failed' ? 'error' : undefined} dimColor={a.status !== 'failed'}>{`${pad}  ⎿  ${l.word}${detail ? ` (${detail})` : ''}`}</Text>
1090            {alertOf(a) ? <Text color="error">{` · ${alertOf(a)}`}</Text> : null}
1091          </Text>,
1092        )
1093      }
1094      return lines
1095    }
1096    const group = ({ agent: a, kids }: { agent: Agent; kids: { agent: Agent; depth: number }[] }) => (
1097      <Box flexDirection="column" marginTop={1}>
1098        {agentBlock(a, 0)}
1099        {kids.flatMap(k => agentBlock(k.agent, k.depth))}
1100      </Box>
1101    )
1102    return withHandle(
1103      <Box flexDirection="column" height={rows} justifyContent="space-between">
1104        <Box flexDirection="column" flexShrink={1} overflow="hidden">
1105          {header(
1106            <Text>
1107              <Text color="claude">✻ </Text>
1108              <Text bold>Agents</Text>
1109            </Text>,
1110            <Box>
1111              {viewed ? <Button key="main" label="◂ Main" dimColor onPress={() => viewIn($).then(ok => void (ok || $.ui.toast('The main view stayed where it is')))} /> : null}
1112              {viewed ? <Text>  </Text> : null}
1113              {counts}
1114            </Box>,
1115          )}
1116          {shown.length ? null : <Text dimColor>No agents yet. They show here while they run.</Text>}
1117          {running.map(group)}
1118          {finished.map(group)}
1119          {loopsLine ? (
1120            <Box marginTop={1}>
1121              <Text dimColor wrap="truncate-end">{loopsLine}</Text>
1122            </Box>
1123          ) : null}
1124        </Box>
1125        <Box flexDirection="column" flexShrink={0}>
1126          {axis}
1127          {hint(shown.length ? `click an agent to view it${doneCount ? ' · click "done" to hide finished ones' : ''}` : '')}
1128        </Box>
1129      </Box>,
1130    )
1131  })
1132
1133  // Folded: a tab at the right edge above the prompt, with the agents' counts, brings the pane back.
1134  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1135    isFullscreen = e.viewport?.isFullscreen ?? isFullscreen
1136    if (e.props.hasSurvey || e.surface === 'desktop') return next(e)
1137    const { Box, Button } = $.ui.resolve(e)
1138    // What the plugins beneath drew stays. Never hand the band itself back: it would not be drawn again
1139    // when the tab comes or goes.
1140    const below = await next(e).catch(() => null)
1141    if (!(await read($, tab))) return <Box flexDirection="column">{below}</Box>
1142    const all = await read($, agents)
1143    const count = (s: string) => all.filter(a => a.status === s).length
1144    const running = all.filter(a => isLive(a.status)).length
1145    const label = [
1146      '◂ Agents',
1147      running ? `${look('running').mark} ${running}` : '',
1148      ...['completed', 'failed', 'killed'].map(s => (count(s) ? `${look(s).mark} ${count(s)}` : '')),
1149    ].filter(Boolean).join(' ')
1150    return (
1151      <Box flexDirection="column">
1152        {below}
1153        <Box justifyContent="flex-end" paddingRight={BAND_RIGHT_PAD}>
1154          <Button key="agents-tab" label={label} dimColor onPress={() => unfold($)} />
1155        </Box>
1156      </Box>
1157    )
1158  })
1159}
1160
hooks/time.ts 25 lines
1// Time as the pane draws it, pure: shared by the hooks module and the surface modules.
2
3// As Claude Code's own status lines read a duration: "8s", "1m 13s", "1h 2m".
4export const fmtDuration = (ms: number) => {
5  const s = Math.max(0, Math.floor(ms / 1000)), m = Math.floor(s / 60), h = Math.floor(m / 60)
6  return h ? `${h}h ${m % 60}m` : m ? `${m}m ${s % 60}s` : `${s}s`
7}
8
9// One agent on the time axis: when it started, and when it ended (null while it runs).
10export type Lane = { name: string; mark: string; color: string; dim: boolean; from: number; to: number | null }
11
12// Each lane's bar on one axis `width` cells wide, from the first start to now (or, all ended, to the last
13// end): the cells before it, of it (at least one) and after it; and how long it ran.
14export const laneRows = (lanes: readonly Lane[], now: number, width: number) => {
15  if (!lanes.length) return []
16  const start = Math.min(...lanes.map(l => l.from))
17  const end = lanes.some(l => l.to === null) ? now : Math.max(...lanes.map(l => l.to ?? now))
18  const at = (t: number) => Math.round(((t - start) / Math.max(1, end - start)) * width)
19  return lanes.map(l => {
20    const from = Math.min(width - 1, Math.max(0, at(l.from)))
21    const to = Math.min(width, Math.max(from + 1, at(l.to ?? end)))
22    return { before: from, bar: to - from, after: width - to, ms: (l.to ?? end) - l.from }
23  })
24}
25
hooks/live.tsx 60 lines
1// A live agent's line, drawn on the surface's own frame clock so only this region redraws, not the
2// pane: its status mark (Claude Code's spinner while it runs), a shimmer across "Running…" (its word otherwise), and a clock. `since` and `now` come from
3// the hooks module's clock; between its redraws the clock counts on from them. `clockOnly` draws the clock
4// alone. Surfaces with no Client (VS Code, mobile) get the hooks module's static line instead.
5import type { ClientModule } from 'claude-code'
6
7import { fmtDuration } from './time'
8
9type Props = {
10  since: number; now: number; pad: string; detail: string; alert: string
11  /** "Running…", "Waiting…": the status as the line says it, in the status's mark and color. */
12  word: string; mark: string; color?: string; dim: boolean
13  motion: boolean; clockOnly: boolean
14}
15type Ref = { base: number; lastNow: number; ms: number; step: number }
16type State = { ref: Ref }
17
18const STEP_MS = 120 // a frame of the shimmer; the spinner turns every other frame
19const SPIN = ['·', '✢', '✳', '✶', '✻', '✽', '✻', '✶', '✳', '✢']
20
21const Live: ClientModule<Props, State> = (props, surface) => {
22  const { Text } = surface.elements
23  const ref = surface.state?.ref ?? { base: 0, lastNow: -1, ms: 0, step: 0 }
24  if (props.now !== ref.lastNow) {
25    // A fresh reading from the hooks module: count on from it.
26    ref.lastNow = props.now
27    ref.base = props.now - props.since
28    ref.ms = 0
29  }
30  if (surface.state === undefined) {
31    const step = props.motion && !props.clockOnly ? STEP_MS : 1000
32    surface.setState({ ref })
33    surface.every(step, () => {
34      ref.ms += step
35      ref.step += 1
36      surface.setState({ ref })
37    })
38  }
39  const time = fmtDuration(ref.base + ref.ms)
40  if (props.clockOnly) return <Text dimColor>{time}</Text>
41
42  const glyph = props.motion ? (SPIN[Math.floor(ref.step / 2) % SPIN.length] ?? props.mark) : props.mark
43  const chars = [...props.word]
44  const at = props.motion ? (ref.step % (chars.length + 6)) - 3 : -9
45  const lit = (i: number) => Math.abs(i - at) <= 1
46  return (
47    <Text wrap="truncate-end">
48      <Text color={props.color} dimColor={props.dim}>{`${props.pad}  ${glyph} `}</Text>
49      {chars.map((ch, i) => (
50        <Text color={lit(i) ? 'claudeShimmer' : props.color} dimColor={props.dim}>{ch}</Text>
51      ))}
52      <Text dimColor>{` (${[time, props.detail].filter(Boolean).join(' · ')}`}</Text>
53      {props.alert ? <Text color="error">{` · ${props.alert}`}</Text> : null}
54      <Text dimColor>)</Text>
55    </Text>
56  )
57}
58
59export default Live
60
hooks/lanes.tsx 52 lines
1// The agents on one time axis, a row each: its bar from when it started to when it ended, and how long it
2// ran. Drawn on the surface's own clock, so a running agent's bar grows and its clock counts without the
3// pane redrawing. Surfaces with no Client (VS Code, mobile) get the hooks module's still copy instead.
4import type { ClientModule } from 'claude-code'
5
6import { fmtDuration, laneRows } from './time'
7import type { Lane } from './time'
8
9type Props = { lanes: Lane[]; now: number; bar: number }
10type Ref = { lastNow: number; ms: number; live: boolean }
11type State = { ref: Ref }
12
13const STEP_MS = 1000
14
15const Lanes: ClientModule<Props, State> = (props, surface) => {
16  const { Box, Text } = surface.elements
17  const ref = surface.state?.ref ?? { lastNow: -1, ms: 0, live: false }
18  if (props.now !== ref.lastNow) {
19    // A fresh reading from the hooks module: count on from it.
20    ref.lastNow = props.now
21    ref.ms = 0
22  }
23  ref.live = props.lanes.some(l => l.to === null)
24  if (surface.state === undefined) {
25    surface.setState({ ref })
26    surface.every(STEP_MS, () => {
27      if (!ref.live) return // all ended: the axis stands still
28      ref.ms += STEP_MS
29      surface.setState({ ref })
30    })
31  }
32  const geo = laneRows(props.lanes, props.now + ref.ms, props.bar)
33  return (
34    <Box flexDirection="column">
35      {props.lanes.map((l, i) => {
36        const g = geo[i]!
37        return (
38          <Text wrap="truncate-end">
39            <Text color={l.color || undefined} dimColor={l.dim}>{`${l.mark} `}</Text>
40            <Text>{l.name}</Text>
41            <Text dimColor>{` ${'·'.repeat(g.before)}`}</Text>
42            <Text color={l.color || undefined} dimColor={l.dim}>{'━'.repeat(g.bar)}</Text>
43            <Text dimColor>{`${'·'.repeat(g.after)}${fmtDuration(g.ms).padStart(8)}`}</Text>
44          </Text>
45        )
46      })}
47    </Box>
48  )
49}
50
51export default Lanes
52
types/index.d.ts 68 lines
1/** An agent as the pane lists it: `$.agent.list()`'s row, with when the pane first saw it and when it ended. */
2export type AgentpaneAgent = {
3  id: string
4  description: string
5  type: string
6  /** `running`, `completed`, `failed`, `killed`, or another of the engine's task statuses. */
7  status: string
8  name?: string
9  parentId?: string
10  /** When the pane first listed it. */
11  firstSeen: number
12  /** Whether the pane saw it running, so `firstSeen` is when it started (to within a second). */
13  seenRunning: boolean
14  /** When the pane first saw it done; absent while it runs, or when it was done before the pane saw it. */
15  endedAt?: number
16  /** The model it runs on: its spawn's report, then the model each of its requests names; absent until either is seen. */
17  model?: string
18  /** How hard its requests ask it to think ('low' … 'max', or a budget number); absent until a request names one. */
19  effort?: string | number
20}
21
22/** The tokens an agent's responses used, summed as the API reported them. */
23export type AgentpaneTokens = {
24  /** Input over all its requests: uncached, cache-read and cache-written together. */
25  input: number
26  /** The part of `input` the prompt cache served. */
27  cached: number
28  output: number
29  /** Its latest request's input and output: how full its context is. */
30  context: number
31  requests: number
32  /** Responses cut off at the output limit (`max_tokens`). */
33  truncated?: number
34}
35
36/** A model loop no listed agent claims: a workflow's agent, a compaction or memory fork. */
37export type AgentpaneLoop = { firstSeen: number; lastSeen: number; requests: number }
38
39/** What an agent is doing: its latest tool call, and how many it has made. */
40export type AgentpaneActivity = { text: string; tools: number }
41
42declare module 'claude-code' {
43  interface PluginState {
44    agentpane: {
45      agents: AgentpaneAgent[]
46      activity: Record<string, AgentpaneActivity>
47      tokens: Record<string, AgentpaneTokens>
48      loops: Record<string, AgentpaneLoop>
49      /** The agent whose conversation the pane shows; null for the list. */
50      viewing: string | null
51      /** The block scrolled back to, drawn at the top; null follows the conversation live. */
52      scrollTop: number | null
53      /** Bumped when the conversation in view grows, so the pane draws it again. */
54      rev: number
55      /** The agent whose Stop was pressed once: the next press stops it. */
56      confirmStop: string | null
57      /** The list shows running agents only. */
58      hideDone: boolean
59      /** The tool-call groups opened in the conversation in view, by their first call's id. */
60      expanded: string[]
61      /** Folded away by its handle: the pane is closed and a tab above the prompt reopens it. */
62      folded: boolean
63      /** Whether that tab shows: folded, with agents running or just finished. */
64      tab: boolean
65    }
66  }
67}
68