SLOPSHOPPER

tool-log

A side panel with a live tool log grouped by prompt, changed files with diffs and subagents; folds tool calls in the chat and replaces the spinner with a…

panebandspinnerrowsguardcommand
v1.13.0no licenseupdated 2026-10-23Tvrtk0/claude-code-mods/tool-log
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tool-log
│ ┃ Panel ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ 1: tab-log 2: Files 3: Agents ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ❯ fix the failing auth test and add an aud… │ ┃ ✓ Read auth.ts ◆ log │ ┃ ✓ Grep src ⏺ Bash(bun test) │ ┃ ✓ Edit auth.ts ⎿ 3 pass, 1 fail │ ┃ ✓ Write audit.ts │ ┃ ✓ Write cache.ts ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ✗ Run the test suite │ ┃ bun test ✻ Worked for 42s · done 4:20 PM │ ┃ ✓ Show working tree status │ ┃ ✓ Clean build output and push › /panel │ ┃ ✓ Show environment file │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ⠋ 0s · Thinking │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ log-toggle panel-key │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭─────────────────────────────────────────────────────────────────────────────────────────────────╮ │ log-toggle panel-key │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────╯
Pane · Panel
1: tab-log 2: Files 3: Agents ❯ fix the failing auth test and add an aud… 08:53 · 9 ✓ Read auth.ts ✓ Grep src ✓ Edit auth.ts ✓ Write audit.ts ✓ Write cache.ts ✗ Run the test suite bun test ✓ Show working tree status ✓ Clean build output and push ✓ Show environment file
Spinner
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ⠋ 0s · Thinking │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Tool row
◆ log
README

local-mods

Personal Claude Code mods for a calmer, more readable terminal.

ModWhat it does
readable-widthDraws each piece of a reply in a grey rounded card, as wide as its longest line and wrapped at 80 columns; tables and code blocks that name a language keep the full width; an unlabelled or text block wraps like prose. Your prompts are bold and accent-colored, in a rounded accent-colored bubble as wide as their longest line, with a blank line above each message.
usage-metersThe bottom of the band above the prompt, under the other mods' buttons: ctx, 5h and 7d meters in one rounded frame. Each bar runs teal to green to yellow to red along its length, so a fuller bar reaches warmer colors; 5h and 7d also show the time left until they reset (2h 16m, 3d 4h). The pointer on a meter shows a card over the buttons: the context's tokens and the session's cost, or when a limit resets (today 18:00, Fri 16:00).
tool-logFolds tool calls and their results in the chat into a ◆ N tools line, one per run of calls with no text between them, and keeps them in a side log grouped by prompt. Toggle it with the framed ☰ panel button, /panel or a key bound to app:toggleDiffPreSession (ctrl+t in ~/.claude/keybindings.json, see below; this replaces the built-in todo list toggle); a click on a chat line opens it on that prompt's steps, until the next prompt or ✕ returns it to live. The chat line also sums file changes and failures (◆ 6 tools · 2 files changed +14 −3 · 1 failed). A turn longer than 30 s ends with a desktop notification. Successful Bash rows expand to show their command, and Edit/Write rows to show their diff. Inside a git repo a framed ± diff button opens the built-in /diff panel. The panel has three tabs: Log, Files (every file changed this session with its diff, new files included) and Agents (subagents with status, time, tool count and their latest step); ☰ panel reopens it on the tab last in view. The active tab is orange, a tab with something new since you last looked is bright, the rest are dim. Replaces the spinner with a minimal one that names the current step, e.g. ⠋ 12s · Reading register.tsx or ⠙ 3s · Thinking.
turn-detailsReplaces the Brewed for 34s · done 1:09 PM line with ◆ details ▸, which folds the turn's duration, finish time, tool calls and model open in place.
ask-modeA read-only mode for when you want an answer, not changes. Beside the panel button, a framed quick │ ask │ deep switch: a click picks a level, a click on the active one turns it off; /quick, /ask and /deep do the same, /ask off leaves any. While on, the frame and the level are yellow beside a 🔒, every prompt carries a brief to answer and report, and every call that may change something is refused, in subagents too: Edit, Write, Bash commands off a read-only list (ls, cat, rg, git log/diff/status/show, gh pr view…; redirects and command substitution included), MCP tools whose name does not read (send, create, update…). quick answers briefly on Haiku 5.5 at low effort, ask investigates on your model, deep analyzes at max effort on Opus. It stays on until you turn it off; a new session starts with it off.

Install

From GitHub:

claude plugin marketplace add Tvrtk0/claude-code-mods
claude plugin install readable-width@local-mods
claude plugin install usage-meters@local-mods
claude plugin install tool-log@local-mods
claude plugin install turn-details@local-mods
claude plugin install ask-mode@local-mods

From a local clone (edits apply after /reload-plugins, no reinstall):

claude plugin marketplace add ~/.claude/mods
claude plugin install readable-width@local-mods
claude plugin install usage-meters@local-mods
claude plugin install tool-log@local-mods
claude plugin install turn-details@local-mods
claude plugin install ask-mode@local-mods

Installed from a local clone, plugins are read straight from the folder.

Develop

claude plugin validate ~/.claude/mods/<mod>
claude plugin test ~/.claude/mods/<mod>

Keyboard shortcut for the panel

A mod cannot add a key of its own, so the ⌃T hint beside ☰ panel borrows an engine action that only the /diff panel handles. Bind any key to it:

{
  "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
  "bindings": [
    { "context": "Global", "bindings": { "ctrl+t": "app:toggleDiffPreSession" } }
  ]
}

ctrl+t hands the panel the keyboard (opening it if needed) and closes it when it already has it. Inside: h/l or 1–3 switch tabs, j/k move between rows (starting from the newest), enter opens one, d/u scroll half a window, g/b jump to the first or last row, esc returns to the prompt and leaves the panel open. The panel scrolls itself, so its tabs and keys stay at the top; Bottom is b, not G: a button hotkey cannot tell shift+g from g.

Source 2 files
hooks/register.tsx 1213 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, RenderInput, RenderNode, Timer } from 'claude-code'
3
4import type { AgentRow, LogEntry, LogGroup, Tab } from '../types'
5
6const PANE = 'tool-log'
7const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
8const FRAME_MS = 120
9const NOTIFY_AFTER_MS = 30_000
10
11// The log's own background, a dark plum in place of the engine's grey.
12const PANE_BG = '#2a2133'
13
14// The spinner card's frame sweeps along the meters' gradient, teal to red and
15// back, once every SWEEP_MS.
16const SWEEP_MS = 4_000
17const STOPS: [number, number, number][] = [
18  [0x4f, 0xd1, 0xc5],
19  [0x98, 0xc3, 0x79],
20  [0xe5, 0xc0, 0x7b],
21  [0xd1, 0x9a, 0x66],
22  [0xe0, 0x6c, 0x75],
23]
24
25function gradient(at: number) {
26  const x = Math.min(1, Math.max(0, at)) * (STOPS.length - 1)
27  const i = Math.min(STOPS.length - 2, Math.floor(x))
28  const from = STOPS[i] ?? STOPS[0]!
29  const to = STOPS[i + 1] ?? from
30  const mix = (k: 0 | 1 | 2) => Math.round(from[k] + (to[k] - from[k]) * (x - i))
31  const hex = (n: number) => n.toString(16).padStart(2, '0')
32
33  return `#${hex(mix(0))}${hex(mix(1))}${hex(mix(2))}`
34}
35
36// The band's framed buttons and the chat's tool cards: the meters' grey frame, lighter under the
37// pointer, a grey label and a dimmer key hint.
38const FRAME = '#5a5a5a'
39const FRAME_HOVER = '#9a9a9a'
40const LABEL = '#c8c8c8'
41const KEY = '#8a8a8a'
42
43const groups = atom({ plugin: 'tool-log', key: 'groups' } as const, [])
44const MAX_GROUPS = 50
45const expanded = atom({ plugin: 'tool-log', key: 'expanded' } as const, [])
46const isRepo = atom({ plugin: 'tool-log', key: 'isRepo' } as const, false)
47// The prompt group a chat line opened the log on; null follows the newest.
48const focus = atom({ plugin: 'tool-log', key: 'focus' } as const, null)
49
50// The most patch text kept per call; whole hunks only, so the diff still parses.
51const PATCH_LIMIT = 20_000
52const tick = atom({ plugin: 'tool-log', key: 'tick' } as const, {
53  frame: 0,
54  elapsedMs: 0,
55  now: 0,
56})
57const tabAtom = atom({ plugin: 'tool-log', key: 'tab' } as const, 'log')
58const agents = atom({ plugin: 'tool-log', key: 'agents' } as const, [])
59// Each tab's content signature when it was last in view: a tab whose
60// signature has moved on since shows as unread.
61const seen = atom({ plugin: 'tool-log', key: 'seen' } as const, {})
62// The panel scrolls itself so its tabs stay put: rows scrolled off the top,
63// per tab; null keeps the log pinned to its newest line.
64const scrollTop = atom({ plugin: 'tool-log', key: 'scrollTop' } as const, {})
65
66const TABS: Tab[] = ['log', 'files', 'agents']
67const TAB_TITLES: Record<Tab, string> = {
68  log: 'Log',
69  files: 'Files',
70  agents: 'Agents',
71}
72const ENDED = new Set<AgentRow['status']>(['completed', 'failed', 'killed'])
73
74const pad = (n: number) => String(n).padStart(2, '0')
75
76const clockTime = (ms: number) => {
77  const d = new Date(ms)
78
79  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
80}
81
82const elapsed = (ms: number) => {
83  const s = Math.floor(ms / 1000)
84
85  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${pad(s % 60)}s`
86}
87
88const countLabel = (n: number) => `${n} ${n === 1 ? 'tool' : 'tools'}`
89
90const basename = (path: string) => path.split('/').pop() ?? path
91
92const dirOf = (path: string) => path.slice(0, path.lastIndexOf('/')) || '/'
93
94const home = (text: string) => text.replace(/\/Users\/[^/\s]+/g, '~')
95
96const firstLine = (text: string) => text.split('\n')[0] ?? ''
97
98const quoted = (text: string) => `"${text}"`
99
100const hostOf = (url: string) => url.replace(/^\w+:\/\//, '').split('/')[0] ?? url
101
102// What a call did, in words: a Bash call's own description, else the file,
103// pattern or task it worked on. The raw command rides along for failures,
104// and `activity` is the verb-and-object line the spinner shows while it runs.
105function describe(
106  tool: string,
107  input: unknown,
108): { label: string; command?: string; activity: string } {
109  const fields = (input ?? {}) as Record<string, unknown>
110  const pick = (key: string) =>
111    typeof fields[key] === 'string' ? (fields[key] as string) : undefined
112
113  const command = pick('command')
114  if (command !== undefined) {
115    const description = pick('description')
116    const first = home(firstLine(command))
117
118    return {
119      label: description ?? first,
120      command: home(command),
121      activity: description ?? `Running ${first.split(' ')[0] ?? first}`,
122    }
123  }
124
125  const path = pick('file_path') ?? pick('notebook_path') ?? pick('path')
126  const pattern = pick('pattern')
127  const url = pick('url')
128  const task = pick('description') ?? pick('prompt')
129
130  const activity =
131    tool === 'Read' && path !== undefined
132      ? `Reading ${basename(path)}`
133      : (tool === 'Edit' || tool === 'NotebookEdit') && path !== undefined
134        ? `Editing ${basename(path)}`
135        : tool === 'Write' && path !== undefined
136          ? `Writing ${basename(path)}`
137          : tool === 'Grep' && pattern !== undefined
138            ? `Searching ${quoted(pattern)}`
139            : tool === 'Glob' && pattern !== undefined
140              ? `Finding ${pattern}`
141              : tool === 'WebFetch' && url !== undefined
142                ? `Fetching ${hostOf(url)}`
143                : tool === 'WebSearch'
144                  ? 'Searching the web'
145                  : (tool === 'Agent' || tool === 'Task') && task !== undefined
146                    ? `Delegating ${firstLine(task)}`
147                    : `Running ${tool}`
148
149  if (path !== undefined) return { label: basename(path), activity }
150
151  return {
152    label: home(firstLine(task ?? pattern ?? url ?? pick('query') ?? '')),
153    activity,
154  }
155}
156
157type Hunk = {
158  oldStart: number
159  oldLines: number
160  newStart: number
161  newLines: number
162  lines: string[]
163}
164
165// An Edit or Write result's hunks as unified-diff text, with the lines each
166// side gained and lost; undefined for any other result.
167function patchOf(
168  result: unknown,
169): { path?: string; patch: string; added: number; removed: number } | undefined {
170  const fields = (result ?? {}) as Record<string, unknown>
171  // A Write that creates a file reports no hunks: its content is one hunk of
172  // added lines.
173  const created =
174    fields.type === 'create' && typeof fields.content === 'string'
175      ? fields.content.replace(/\n$/, '').split('\n')
176      : undefined
177  const hunks =
178    created !== undefined && (!Array.isArray(fields.structuredPatch) || fields.structuredPatch.length === 0)
179      ? [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: created.length, lines: created.map(l => `+${l}`) }]
180      : fields.structuredPatch
181
182  if (!Array.isArray(hunks) || hunks.length === 0) return undefined
183
184  let patch = ''
185  let added = 0
186  let removed = 0
187
188  for (const hunk of hunks as Hunk[]) {
189    for (const line of hunk.lines) {
190      if (line.startsWith('+')) added += 1
191      else if (line.startsWith('-')) removed += 1
192    }
193
194    const text = `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@\n${hunk.lines.join('\n')}\n`
195    if (patch.length + text.length <= PATCH_LIMIT) patch += text
196  }
197
198  const path = typeof fields.filePath === 'string' ? fields.filePath : undefined
199
200  return { path, patch, added, removed }
201}
202
203// `2 files changed +14 −3` for the calls of one chat row, from the log.
204function changesOf(all: LogGroup[], ids: readonly (string | undefined)[]) {
205  const wanted = new Set(ids)
206  const files = new Set<string>()
207  let added = 0
208  let removed = 0
209
210  for (const g of all) {
211    for (const x of g.entries) {
212      if (!wanted.has(x.id) || x.patch === undefined) continue
213      files.add(x.path ?? x.id)
214      added += x.added ?? 0
215      removed += x.removed ?? 0
216    }
217  }
218
219  if (files.size === 0) return ''
220
221  return ` · ${files.size} ${files.size === 1 ? 'file' : 'files'} changed +${added} −${removed}`
222}
223
224type FileChange = {
225  path: string
226  added: number
227  removed: number
228  edits: number
229  patch: string
230}
231
232// Every file the session's calls changed, newest first, its hunks joined.
233function filesOf(all: LogGroup[]): FileChange[] {
234  const byPath = new Map<string, FileChange>()
235
236  for (const g of all) {
237    for (const x of g.entries) {
238      if (x.patch === undefined || x.path === undefined) continue
239      const prev = byPath.get(x.path)
240      byPath.delete(x.path)
241      const patch = (prev?.patch ?? '') + x.patch
242      byPath.set(x.path, {
243        path: x.path,
244        added: (prev?.added ?? 0) + (x.added ?? 0),
245        removed: (prev?.removed ?? 0) + (x.removed ?? 0),
246        edits: (prev?.edits ?? 0) + 1,
247        patch: patch.length > PATCH_LIMIT * 3 ? (prev?.patch ?? x.patch) : patch,
248      })
249    }
250  }
251
252  return [...byPath.values()].reverse()
253}
254
255// Brings each subagent's status up to date from the engine's roster.
256async function refreshAgents($: EngineInterface) {
257  if ((await read($, agents)).length === 0) return
258
259  const live = new Map((await $.agent.list()).map(a => [a.id, a.status]))
260  const now = await $.clock.now()
261
262  await update($, agents, list =>
263    (list ?? []).map(row => {
264      const status = live.get(row.id) ?? row.status
265
266      return { ...row, status, endedAt: ENDED.has(status) ? (row.endedAt ?? now) : undefined }
267    }),
268  )
269  await update($, tick, prev => ({ frame: prev?.frame ?? 0, elapsedMs: prev?.elapsedMs ?? 0, now }))
270}
271
272function signatures(all: LogGroup[], crew: AgentRow[]): Record<Tab, string> {
273  return {
274    log: String(all.reduce((n, g) => n + g.entries.length, 0)),
275    files: filesOf(all).map(f => f.path + f.edits).join(','),
276    agents: crew.map(a => a.id + a.status).join(','),
277  }
278}
279
280async function markSeen($: EngineInterface, tabs: readonly Tab[]) {
281  const now = signatures(await read($, groups), await read($, agents))
282  await update($, seen, prev => {
283    const next = { ...(prev ?? {}) }
284    for (const t of tabs) next[t] = now[t]
285    return next
286  })
287}
288
289// The pane's pressable rows in drawing order, as the last drawing laid them
290// out, and the one j and k last moved to; a reload starts both over.
291let rowKeys: string[] = []
292let cursorKey: string | null = null
293
294// Keeps the focus ring on a row and that row in view.
295// What the last drawing laid out: each pressable row's first line, the
296// content's height, the window's height and how far it was scrolled.
297let layout = { tab: 'log' as Tab, rowLine: new Map<string, number>(), content: 0, view: 1, offset: 0 }
298
299const maxOffset = () => Math.max(0, layout.content - layout.view)
300
301async function setOffset($: EngineInterface, offset: number) {
302  const tab = layout.tab
303  const clamped = Math.max(0, Math.min(maxOffset(), Math.round(offset)))
304  // Remembered at once, so the next key counts from here, not from the
305  // last drawing.
306  layout = { ...layout, offset: clamped }
307  // The log at its bottom stays pinned there as new rows arrive.
308  const value = tab === 'log' && clamped >= maxOffset() ? null : clamped
309  await update($, scrollTop, prev => ({ ...(prev ?? {}), [tab]: value }))
310}
311
312async function scrollBy($: EngineInterface, rows: number) {
313  await setOffset($, layout.offset + rows)
314}
315
316// Keeps the focus ring on a row and scrolls the window to show it.
317async function focusRow($: EngineInterface, key: string) {
318  cursorKey = key
319  try {
320    await $.ui.focus({ requestId: PANE, key })
321  } catch {}
322  const line = layout.rowLine.get(key)
323  if (line === undefined) return
324  // Like vim's scrolloff: keep a margin of rows around the selected one, so a
325  // row height the layout guessed a little wrong still leaves it in view.
326  const margin = Math.max(1, Math.min(5, Math.floor(layout.view / 4)))
327  if (line < layout.offset + margin) await setOffset($, line - margin)
328  else if (line > layout.offset + layout.view - 1 - margin) await setOffset($, line - layout.view + 1 + margin)
329}
330
331// j and k: the first press lands on the newest row, at the bottom.
332async function moveCursor($: EngineInterface, by: number) {
333  if (rowKeys.length === 0) return
334  const at = cursorKey === null ? -1 : rowKeys.indexOf(cursorKey)
335  const next = at === -1 ? rowKeys.length - 1 : Math.min(rowKeys.length - 1, Math.max(0, at + by))
336  const key = rowKeys[next]
337  if (key !== undefined) await focusRow($, key)
338}
339
340// g and b: the top or the bottom, with the focus on the first or last row.
341async function jumpTo($: EngineInterface, end: 'first' | 'last') {
342  const key = end === 'first' ? rowKeys[0] : rowKeys[rowKeys.length - 1]
343  await setOffset($, end === 'first' ? 0 : Number.MAX_SAFE_INTEGER)
344  if (key === undefined) return
345  cursorKey = key
346  try {
347    await $.ui.focus({ requestId: PANE, key })
348  } catch {}
349}
350
351async function toggleExpanded($: EngineInterface, key: string) {
352  // Hold the window where it is, so the row does not move under the eye.
353  await setOffset($, layout.offset)
354  if (layout.tab === 'log' && layout.offset >= maxOffset()) {
355    const tab = layout.tab
356    await update($, scrollTop, prev => ({ ...(prev ?? {}), [tab]: layout.offset }))
357  }
358  await update($, expanded, ids =>
359    (ids ?? []).includes(key)
360      ? (ids ?? []).filter(x => x !== key)
361      : [...(ids ?? []), key].slice(-100),
362  )
363  // The row grew or shrank under the focus: put it back on the same row.
364  await focusRow($, key)
365}
366
367// What the turn is doing when no tool runs, by the spinner's own mode.
368const MODE_ACTIVITY: Record<string, string> = {
369  requesting: 'Waiting for model',
370  thinking: 'Thinking',
371  responding: 'Writing reply',
372  'tool-input': 'Preparing a tool call',
373  'tool-use': 'Using tools',
374}
375
376// Applies fn to the newest group, opening one first when there is none.
377function onLatest(list: LogGroup[] | undefined, at: number, fn: (g: LogGroup) => LogGroup) {
378  const all = list ?? []
379  const last = all[all.length - 1]
380  const latest = last ?? { id: `g${at}`, prompt: '', startedAt: at, entries: [] }
381
382  return [...all.slice(0, last ? -1 : undefined), fn(latest)]
383}
384
385const isLogOpen = async ($: EngineInterface) =>
386  (await $.ui.panes()).some(pane => pane.id === PANE)
387
388const openPane = ($: EngineInterface, focus?: true) =>
389  $.ui.open({ id: PANE, title: 'Panel', columns: 56, ...(focus ? { focus } : {}) })
390
391// The panel chip and /panel: open the panel on the tab last in view, or close it.
392async function toggle($: EngineInterface) {
393  await update($, focus, () => null)
394
395  const tab = await read($, tabAtom)
396  await markSeen($, [tab])
397
398  if (await isLogOpen($)) {
399    await $.ui.close({ id: PANE })
400  } else {
401    if (tab === 'agents') await refreshAgents($)
402    await openPane($)
403  }
404}
405
406// ctrl+t: hand the panel the keyboard, opening it if it is closed; when it
407// already holds the keyboard, close it. Esc alone gives the keys back.
408async function focusPanel($: EngineInterface) {
409  const pane = (await $.ui.panes()).find(x => x.id === PANE)
410  const tab = await read($, tabAtom)
411  await markSeen($, [tab])
412
413  if (pane?.isFocused) {
414    await update($, focus, () => null)
415    await $.ui.close({ id: PANE })
416    return
417  }
418
419  if (pane === undefined && tab === 'agents') await refreshAgents($)
420  await openPane($, true)
421}
422
423// A chat line: open the log on its own prompt's group; pressed again while
424// that group is in view, close the log.
425async function focusOn($: EngineInterface, ids: readonly (string | undefined)[]) {
426  const wanted = new Set(ids)
427  const group = (await read($, groups)).find(g => g.entries.some(x => wanted.has(x.id)))
428  const isOpen = await isLogOpen($)
429  const prevTab = await read($, tabAtom)
430  const isOnLog = prevTab === 'log'
431  await markSeen($, [prevTab, 'log'])
432  await update($, tabAtom, () => 'log')
433
434  if (group === undefined) {
435    if (!isOpen) await openPane($)
436    return
437  }
438
439  if (isOpen && isOnLog && (await read($, focus)) === group.id) {
440    await update($, focus, () => null)
441    await $.ui.close({ id: PANE })
442    return
443  }
444
445  await update($, focus, () => group.id)
446  if (!isOpen) await openPane($)
447}
448
449// The run the next tool calls join. A model response with text in it starts
450// a new run; responses that only call tools keep adding to the current one,
451// so the chat can show the whole run as one line.
452// A reload starts the module over, so the ids carry a prefix of its own:
453// a new run never takes the id of one the log kept from before.
454const RUN_PREFIX = `r${Math.floor(Math.random() * 1e9).toString(36)}-`
455let runSeq = 0
456let currentRun = `${RUN_PREFIX}0`
457
458function newRun() {
459  runSeq += 1
460  currentRun = `${RUN_PREFIX}${runSeq}`
461}
462
463// The calls sharing a run with any of `ids`, oldest first.
464function runOf(all: LogGroup[], ids: readonly (string | undefined)[]): LogEntry[] {
465  const wanted = new Set(ids)
466  const entries = all.flatMap(g => g.entries)
467  const run = entries.find(x => wanted.has(x.id))?.run
468  if (run === undefined) return entries.filter(x => wanted.has(x.id))
469  return entries.filter(x => x.run === run)
470}
471
472// The running turn's start and its animation timer; a reload starts over.
473let startedAt: number | null = null
474let timer: Timer | null = null
475
476async function start($: EngineInterface) {
477  if (timer !== null) return
478
479  startedAt = await $.clock.now()
480  timer = $.clock.every(FRAME_MS, async () => {
481    const now = await $.clock.now()
482    let frame = 0
483    await update($, tick, prev => {
484      frame = ((prev?.frame ?? 0) + 1) % FRAMES.length
485
486      return { frame, elapsedMs: now - (startedAt ?? now), now }
487    })
488
489    // About once a second, the subagents' status too.
490    if (frame === 0) {
491      try {
492        await refreshAgents($)
493      } catch {}
494    }
495  })
496}
497
498function stop() {
499  timer?.cancel()
500  timer = null
501  startedAt = null
502}
503
504// One chat line for a run of tool calls, marked by an accent diamond: the
505// run's last row carries the count, changes and failures of the whole run;
506// earlier rows draw nothing.
507async function runRow(
508  $: EngineInterface,
509  e: RenderInput,
510  ids: readonly (string | undefined)[],
511  own: number,
512  ownFailed: number,
513): Promise<RenderElement> {
514  const { Box, Button, Text } = $.ui.resolve(e)
515  const all = await read($, groups)
516  const run = runOf(all, ids)
517  const mine = new Set(ids)
518  const last = run.at(-1)
519
520  if (run.length > 0 && last !== undefined && !mine.has(last.id)) {
521    return <Box />
522  }
523
524  const count = Math.max(own, run.length)
525  const runIds = run.length > 0 ? run.map(x => x.id) : ids
526  const changes = changesOf(all, runIds)
527  const failed = run.length > 0 ? run.filter(x => x.status === 'error').length : ownFailed
528
529  return (
530    <Box key="log-card" marginTop={1}>
531      <Text color="claude">◆ </Text>
532      <Button key="log" plain onPress={() => focusOn($, runIds)} hover={{ color: 'white' }}>
533        <Text color={LABEL}>{`${countLabel(count)}${changes}`}</Text>
534        {failed > 0 && <Text color="error">{` · ${failed} failed`}</Text>}
535      </Button>
536    </Box>
537  )
538}
539
540export const register: Register = on => {
541  on('session.start', async ($, e, next) => {
542    await $.command.register({
543      name: 'panel',
544      description: 'Toggle the side panel: log, files, agents',
545    })
546    const started = await next(e)
547
548    // The diff chip opens the engine's git diff panel, so it shows only
549    // inside a work tree.
550    try {
551      const git = await $.process.run(['git', 'rev-parse', '--is-inside-work-tree'], {
552        cwd: started.cwd,
553        timeoutMs: 5000,
554      })
555      await update($, isRepo, () => git.exitCode === 0 && git.stdout.trim() === 'true')
556    } catch {
557      await update($, isRepo, () => false)
558    }
559
560    return started
561  })
562
563  on('command.run', { command: 'panel' }, async $ => {
564    await toggle($)
565
566    return { text: '' }
567  })
568
569  on('prompt.submit', async ($, e, next) => {
570    try {
571      await start($)
572
573      if (e.origin.kind === 'composer') {
574        newRun()
575        const at = await $.clock.now()
576        const group: LogGroup = {
577          id: `g${at}`,
578          prompt: firstLine(e.text),
579          startedAt: at,
580          entries: [],
581        }
582        await update($, groups, list => [...(list ?? []), group].slice(-MAX_GROUPS))
583        // A new prompt takes the log back to what is happening now.
584        await update($, focus, () => null)
585      }
586
587      // A task notification often means a background subagent ended.
588      await refreshAgents($)
589    } catch {}
590
591    return next(e)
592  })
593
594  // Text in a response starts a new run; a subagent's steps are its own.
595  on('turn.step', async function* ($, e, next) {
596    const response = yield* next(e)
597    if (e.agentId === undefined && response.answer.trim() !== '') newRun()
598    return response
599  })
600
601  on('turn.start', async ($, e, next) => {
602    newRun()
603    await start($)
604
605    return next(e)
606  })
607
608  on('turn.complete', async ($, e, next) => {
609    stop()
610
611    try {
612      await refreshAgents($)
613    } catch {}
614
615    // A long turn ends with a desktop notification, for when you looked away.
616    try {
617      if (!e.isAborted && e.durationMs >= NOTIFY_AFTER_MS) {
618        const prompt = (await read($, groups)).at(-1)?.prompt ?? ''
619        const gist = prompt.length > 60 ? `${prompt.slice(0, 59)}…` : prompt
620        await $.ui.notify(gist === '' ? 'Done' : `Done: ${gist}`, { title: 'Claude Code' })
621      }
622    } catch {}
623
624    return next(e)
625  })
626
627  on('agent.spawn', async ($, e, next) => {
628    const spawned = await next(e)
629
630    try {
631      if (spawned.deny === undefined && spawned.agentId !== undefined) {
632        const row: AgentRow = {
633          id: spawned.agentId,
634          description: e.description,
635          type: e.subagentType,
636          startedAt: await $.clock.now(),
637          status: 'running',
638          lastStep: '',
639          tools: 0,
640        }
641        await update($, agents, list => [...(list ?? []).filter(a => a.id !== row.id), row].slice(-30))
642      }
643    } catch {}
644
645    return spawned
646  })
647
648  // The log must never stand in a call's way: its own failures are swallowed
649  // and next(e) runs exactly once either way.
650  on('tool.call', async ($, e, next) => {
651    const id = e.tool_use_id
652
653    // A subagent's calls count toward its row in Agents, not the log.
654    if (e.agentId !== undefined) {
655      const agentId = e.agentId
656      try {
657        const step = describe(e.tool, e).activity
658        await update($, agents, list =>
659          (list ?? []).map(a => (a.id === agentId ? { ...a, tools: a.tools + 1, lastStep: step } : a)),
660        )
661      } catch {}
662
663      return next(e)
664    }
665
666    try {
667      const entry: LogEntry = {
668        id,
669        tool: e.tool,
670        ...describe(e.tool, e),
671        status: 'running',
672        run: currentRun,
673      }
674      const at = await $.clock.now()
675      await update($, groups, list =>
676        onLatest(list, at, g => ({ ...g, entries: [...g.entries, entry] })),
677      )
678    } catch {}
679
680    const ran = await next(e)
681
682    try {
683      const status = ran.deny !== undefined || ran.isError === true ? 'error' : 'ok'
684      const change = status === 'ok' ? patchOf(ran.result) : undefined
685      await update($, groups, list =>
686        (list ?? []).map(g => ({
687          ...g,
688          entries: g.entries.map(one =>
689            one.id === id ? { ...one, status, ...(change ?? {}) } : one,
690          ),
691        })),
692      )
693    } catch {}
694
695    return ran
696  })
697
698  // In the chat a run of tool calls is one dim, pressable line; the log holds
699  // the rest. Rows the engine draws apart (one per response) fold into the
700  // run's last row; the others draw nothing. An expanded group unfolds into
701  // ToolUse rows of its own.
702  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
703    if (e.surface !== 'terminal' || e.props.isExpanded) {
704      return next(e)
705    }
706
707    return runRow(
708      $,
709      e,
710      e.props.calls.map(call => call.tool_use_id),
711      e.props.calls.length,
712      e.props.calls.filter(call => call.isErrored).length,
713    )
714  })
715
716  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
717    if (e.surface !== 'terminal') {
718      return next(e)
719    }
720
721    return runRow($, e, [e.props.tool_use_id], 1, e.props.isErrored ? 1 : 0)
722  })
723
724  // A standalone call's result block draws apart from its row: it lives in
725  // the log too, so the chat drops it.
726  on('ui.render', { component: 'ToolResult' }, ($, e, next) => {
727    if (e.surface !== 'terminal') {
728      return next(e)
729    }
730
731    const { Box } = $.ui.resolve(e)
732
733    return <Box />
734  })
735
736  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
737    if (e.surface !== 'terminal') {
738      return next(e)
739    }
740
741    const { Box, Text } = $.ui.resolve(e)
742    const now = await read($, tick)
743    const latest = (await read($, groups)).at(-1)
744    const running = latest?.entries.filter(x => x.status === 'running').at(-1)
745    const activity = running?.activity ?? MODE_ACTIVITY[e.props.mode] ?? ''
746    const room = Math.max(10, (e.viewport?.columns ?? 80) - 18)
747
748    // A card in a rounded frame, a blank line above it. A border takes one
749    // color, so the gradient runs through time instead: the frame sweeps
750    // teal to red and back every few seconds while the turn runs.
751    const sweep = (now.elapsedMs % SWEEP_MS) / SWEEP_MS
752    const border = gradient(sweep < 0.5 ? sweep * 2 : 2 - sweep * 2)
753
754    return (
755      <Box marginTop={1} alignSelf="flex-start" borderStyle="round" borderColor={border} paddingX={1}>
756        <Text color="claude">{FRAMES[now.frame] ?? FRAMES[0]}</Text>
757        <Text dimColor> {elapsed(now.elapsedMs)}</Text>
758        {activity !== '' && (
759          <Text wrap="truncate-end">
760            <Text dimColor> · </Text>
761            {activity.length > room ? `${activity.slice(0, room - 1)}…` : activity}
762          </Text>
763        )}
764      </Box>
765    )
766  })
767
768  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
769    const below = await next(e)
770
771    if (e.surface !== 'terminal' || e.props.hasSurvey) {
772      return below
773    }
774
775    const { Box, Button, Text } = $.ui.resolve(e)
776    const hasDiff = await read($, isRepo)
777
778    // A framed button, in the meters' rounded frame; the frame and the label
779    // light under the pointer. It never shrinks, so a narrow band wraps none.
780    const framed = (key: string, children: RenderNode) => (
781      <Box
782        key={`${key}-box`}
783        flexShrink={0}
784        marginRight={1}
785        borderStyle="round"
786        borderColor={FRAME}
787        paddingX={1}
788        hover={{ borderColor: FRAME_HOVER }}
789      >
790        {children}
791      </Box>
792    )
793
794    // No sizing props here: the engine refuses its own node under a sized Box.
795    // The panel frame has two parts: a click on `panel` opens or closes it; ⌃T
796    // is the key that hands it the keyboard. The engine cannot tell a click
797    // from the key, so each part keeps its own press.
798    return (
799      <Box>
800        {framed(
801          'log-toggle',
802          <Box>
803            <Button key="log-toggle" plain onPress={() => toggle($)} hover={{ color: 'white' }}>
804              <Text color={LABEL}>☰ panel</Text>
805            </Button>
806            <Text>  </Text>
807            {/* ctrl+t in ~/.claude/keybindings.json is bound to an engine
808                action only the diff panel handles, free at the prompt. */}
809            <Button key="panel-key" plain action="app:toggleDiffPreSession" onPress={() => focusPanel($)}>
810              <Text color={KEY}>⌃T</Text>
811            </Button>
812          </Box>,
813        )}
814        {hasDiff &&
815          framed(
816            'diff-open',
817            <Button
818              key="diff-open"
819              plain
820              hover={{ color: 'white' }}
821              onPress={async () => {
822                await $.command.run({ command: 'diff' })
823              }}
824            >
825              <Text color={LABEL}>± diff</Text>
826            </Button>,
827          )}
828        {below}
829      </Box>
830    )
831  })
832
833  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
834    const { Box, Button, Code, Text } = $.ui.resolve(e)
835    const list = await read($, groups)
836    const now = await read($, tick)
837    const open = new Set(await read($, expanded))
838    const bodyRows = e.props.scroll.bodyRows
839    const columns = Math.max(20, e.props.bodyColumns - 2)
840    const clip = (text: string, width: number) =>
841      text.length > width ? `${text.slice(0, width - 1)}…` : text
842    const lines = (text: string, width: number) =>
843      text.split('\n').reduce((n, l) => n + Math.max(1, Math.ceil(l.length / Math.max(1, width))), 0)
844    const patchLines = (patch: string) => patch.replace(/\n$/, '').split('\n').length
845
846    // A stored tab the panel no longer has (Todo) falls back to the log.
847    const stored = await read($, tabAtom)
848    const tab = TABS.includes(stored) ? stored : 'log'
849    const frame = FRAMES[now.frame] ?? FRAMES[0]
850    const lastSeen = await read($, seen)
851    const current = signatures(list, await read($, agents))
852    // Active: orange. Something new since last viewed: bright. Else dim.
853    const isNew = (t: Tab) => t !== tab && current[t] !== '' && current[t] !== (lastSeen[t] ?? '')
854    const step = (by: number) => async () => {
855      const next = TABS[(TABS.indexOf(tab) + by + TABS.length) % TABS.length] ?? tab
856      cursorKey = null
857      await markSeen($, [tab, next])
858      await update($, tabAtom, () => next)
859    }
860    const key = (k: string, label: string, onPress: () => unknown) => (
861      <Box key={`hintbox-${k}`} marginRight={2}>
862        <Button key={`hint-${k}`} hotkey={k} label={label} plain onPress={onPress} />
863      </Box>
864    )
865
866    // The tabs and, while the panel holds the keyboard, its keys: drawn above
867    // the scrolled window, so they never scroll away.
868    const isFocused = e.props.isFocused
869    const header = (
870      <Box flexDirection="column">
871        <Box>
872          {TABS.map((t, i) => (
873            <Box key={`tabbox-${t}`} marginRight={2}>
874              <Button
875                key={`tab-${t}`}
876                hotkey={String(i + 1)}
877                plain
878                dimColor={t !== tab && !isNew(t)}
879                onPress={async () => {
880                  cursorKey = null
881                  await markSeen($, [tab, t])
882                  await update($, tabAtom, () => t)
883                }}
884              >
885                {t === tab ? (
886                  <Text bold color="claude">{TAB_TITLES[t]}</Text>
887                ) : isNew(t) ? (
888                  <Text bold>{TAB_TITLES[t]}</Text>
889                ) : (
890                  TAB_TITLES[t]
891                )}
892              </Button>
893            </Box>
894          ))}
895        </Box>
896        {isFocused && (
897          <Box flexDirection="column" marginTop={1}>
898            <Box>
899              {key('h', 'prev', step(-1))}
900              {key('l', 'next', step(1))}
901              {key('j', 'down', () => moveCursor($, 1))}
902              {key('k', 'up', () => moveCursor($, -1))}
903            </Box>
904            <Box>
905              {key('d', 'half down', () => scrollBy($, Math.max(1, Math.floor(layout.view / 2))))}
906              {key('u', 'half up', () => scrollBy($, -Math.max(1, Math.floor(layout.view / 2))))}
907              {key('g', 'top', () => jumpTo($, 'first'))}
908              {/* b for the bottom: a hotkey cannot tell shift+g from g */}
909              {key('b', 'bottom', () => jumpTo($, 'last'))}
910            </Box>
911          </Box>
912        )}
913      </Box>
914    )
915    const headerRows = isFocused ? 4 : 1
916    // Body rows less the padding, the header and the gap under it.
917    const view = Math.max(3, bodyRows - 2 - headerRows - 1)
918
919    // Lays the content out in a window of `view` rows, scrolled by this tab's
920    // offset, and records where each pressable row sits for j, k and focus.
921    const windowed = async (
922      content: RenderNode,
923      height: number,
924      rowLine: Map<string, number>,
925      keys: string[] = [],
926    ) => {
927      const stored = (await read($, scrollTop))[tab]
928      const max = Math.max(0, height - view)
929      const fallback = tab === 'log' ? max : 0
930      const offset = Math.max(0, Math.min(max, stored === null || stored === undefined ? fallback : stored))
931      // Both at once, after the last await: a key pressed mid-drawing never
932      // sees one without the other.
933      layout = { tab, rowLine, content: height, view, offset }
934      rowKeys = keys
935      const more = offset > 0 ? '↑ ' : ''
936      const less = offset < max ? ' ↓' : ''
937
938      return (
939        <Box
940          backgroundColor={PANE_BG}
941          width={e.props.bodyColumns}
942          height={e.props.placement === 'dock' ? bodyRows : undefined}
943          paddingX={1}
944          paddingY={1}
945          flexDirection="column"
946        >
947          {header}
948          <Box height={1}>
949            {(more !== '' || less !== '') && (
950              <Text dimColor>
951                {more}
952                {offset + 1}–{Math.min(height, offset + view)} of {height}
953                {less}
954              </Text>
955            )}
956          </Box>
957          <Box height={view} overflow="hidden" flexDirection="column">
958            <Box marginTop={-offset} flexDirection="column" flexShrink={0}>
959              {content}
960            </Box>
961          </Box>
962        </Box>
963      )
964    }
965
966    if (tab === 'files') {
967      const files = filesOf(list)
968      const fileKeys = files.map(f => `f:${f.path}`)
969
970      if (files.length === 0) {
971        return windowed(<Text dimColor>No files changed yet.</Text>, 1, new Map())
972      }
973
974      const rowLine = new Map<string, number>()
975      let y = 0
976      for (const f of files) {
977        const k = `f:${f.path}`
978        rowLine.set(k, y)
979        y += 2 + (open.has(k) ? patchLines(f.patch) : 0) + 1
980      }
981
982      return windowed(
983        <Box flexDirection="column">
984          {files.map(f => {
985            const k = `f:${f.path}`
986
987            return (
988              <Box key={`row-${k}`} flexDirection="column" marginBottom={1}>
989                <Button key={k} plain onPress={() => toggleExpanded($, k)}>
990                  <Text bold>{clip(basename(f.path), columns - 24)}</Text>{' '}
991                  <Text color="success">+{f.added}</Text>{' '}
992                  <Text color="error">−{f.removed}</Text>
993                  <Text dimColor> {open.has(k) ? '▾' : '▸'}</Text>
994                </Button>
995                <Box marginLeft={2}>
996                  <Text dimColor wrap="truncate-start">
997                    {home(dirOf(f.path))} · {f.edits} {f.edits === 1 ? 'edit' : 'edits'}
998                  </Text>
999                </Box>
1000                {open.has(k) && (
1001                  <Box marginLeft={2} width={columns - 2}>
1002                    <Code source={f.patch} format="diff" path={f.path} wrap="truncate-end" />
1003                  </Box>
1004                )}
1005              </Box>
1006            )
1007          })}
1008        </Box>,
1009        y,
1010        rowLine,
1011        fileKeys,
1012      )
1013    }
1014
1015    if (tab === 'agents') {
1016      const crew = await read($, agents)
1017
1018      if (crew.length === 0) {
1019        return windowed(<Text dimColor>No subagents in this session.</Text>, 1, new Map())
1020      }
1021
1022      const height = crew.reduce((n, a) => n + 3 + (!ENDED.has(a.status) && a.lastStep !== '' ? 1 : 0), 0)
1023
1024      return windowed(
1025        <Box flexDirection="column">
1026          {[...crew].reverse().map(a => {
1027            const isLive = !ENDED.has(a.status)
1028            const end = a.endedAt ?? Math.max(now.now, a.startedAt)
1029
1030            return (
1031              <Box key={a.id} flexDirection="column" marginBottom={1}>
1032                <Box>
1033                  <Box width={2} flexShrink={0}>
1034                    {a.status === 'running' || a.status === 'pending' ? (
1035                      <Text color="claude">{frame}</Text>
1036                    ) : a.status === 'completed' ? (
1037                      <Text color="success">✓</Text>
1038                    ) : a.status === 'failed' ? (
1039                      <Text color="error">✗</Text>
1040                    ) : a.status === 'killed' ? (
1041                      <Text color="warning">■</Text>
1042                    ) : (
1043                      <Text dimColor>◌</Text>
1044                    )}
1045                  </Box>
1046                  <Text bold={isLive} dimColor={!isLive} wrap="truncate-end">
1047                    {clip(a.description, columns - 4)}
1048                  </Text>
1049                </Box>
1050                <Box marginLeft={2}>
1051                  <Text dimColor wrap="truncate-end">
1052                    {a.type} · {elapsed(end - a.startedAt)} · {countLabel(a.tools)}
1053                    {a.status === 'idle' || a.status === 'waiting' ? ` · ${a.status}` : ''}
1054                  </Text>
1055                </Box>
1056                {isLive && a.lastStep !== '' && (
1057                  <Box marginLeft={2}>
1058                    <Text dimColor wrap="truncate-end">
1059                      › {clip(a.lastStep, columns - 6)}
1060                    </Text>
1061                  </Box>
1062                )}
1063              </Box>
1064            )
1065          })}
1066        </Box>,
1067        height,
1068        new Map(),
1069      )
1070    }
1071
1072    const focused = await read($, focus)
1073    const all = list.filter(g => g.entries.length > 0 || g === list[list.length - 1])
1074    const at = focused === null ? -1 : all.findIndex(g => g.id === focused)
1075    // Focused, the log ends at that group: it sits at the bottom, older above.
1076    const shown = (at === -1 ? all : all.slice(0, at + 1)).slice(-40)
1077    const target = at === -1 ? undefined : all[at]
1078
1079    if (shown.length === 0) {
1080      return windowed(<Text dimColor>No tool calls yet.</Text>, 1, new Map())
1081    }
1082
1083    const pressable = (x: LogEntry) => (x.command !== undefined || x.patch !== undefined) && x.status === 'ok'
1084    const logKeys = shown.flatMap(g => g.entries.filter(pressable).map(x => x.id))
1085
1086    // Where each row lands: a group is its header, a line per call, what an
1087    // open or failed call unfolds, and a blank line before the next group.
1088    const rowLine = new Map<string, number>()
1089    let y = target === undefined ? 0 : 2
1090    shown.forEach((g, gi) => {
1091      if (gi > 0) y += 1
1092      y += 1
1093      for (const x of g.entries) {
1094        rowLine.set(x.id, y)
1095        // The row's own line, longer when its label and counts wrap.
1096        const head = (x.patch !== undefined ? `${x.tool} ` : '') + x.label + (x.patch !== undefined ? ` +${x.added ?? 0} −${x.removed ?? 0}` : '') + ' ▸'
1097        y += lines(head, columns - 4)
1098        if (x.patch !== undefined && open.has(x.id)) y += patchLines(x.patch)
1099        if (x.command !== undefined && x.status === 'error') y += 1
1100        else if (x.command !== undefined && open.has(x.id)) y += lines(x.command, columns - 6)
1101      }
1102    })
1103
1104    const latest = list[list.length - 1]
1105
1106    return windowed(
1107      <Box flexDirection="column" gap={1}>
1108        {target !== undefined && (
1109          <Box>
1110            <Text dimColor wrap="truncate-end">
1111              viewing: {clip(target.prompt === '' ? '(no prompt)' : target.prompt, columns - 16)}
1112            </Text>
1113            <Text dimColor> · </Text>
1114            <Button
1115              key="unfocus"
1116              label="✕"
1117              plain
1118              dimColor
1119              onPress={() => update($, focus, () => null)}
1120            />
1121          </Box>
1122        )}
1123        {shown.map(g => {
1124          const isOld = target === undefined ? g !== latest : g !== target
1125          const meta = `${clockTime(g.startedAt).slice(0, 5)} · ${g.entries.length}`
1126          const promptWidth = Math.max(8, columns - meta.length - 4)
1127
1128          return (
1129            <Box key={g.id} flexDirection="column">
1130              <Box>
1131                <Text bold={!isOld} dimColor={isOld} color="claude">
1132                  ❯{' '}
1133                </Text>
1134                <Box width={promptWidth}>
1135                  <Text bold={!isOld} dimColor={isOld} wrap="truncate-end">
1136                    {g.prompt === '' ? '(no prompt)' : g.prompt}
1137                  </Text>
1138                </Box>
1139                <Text dimColor> {meta}</Text>
1140              </Box>
1141              {g.entries.map(entry => (
1142                <Box key={`row-${entry.id}`} flexDirection="column">
1143                  <Box>
1144                    <Box width={4} flexShrink={0}>
1145                      <Text>  </Text>
1146                      {entry.status === 'running' ? (
1147                        <Text color="claude">{frame}</Text>
1148                      ) : entry.status === 'ok' ? (
1149                        <Text color="success" dimColor={isOld}>✓</Text>
1150                      ) : (
1151                        <Text color="error">✗</Text>
1152                      )}
1153                    </Box>
1154                    {pressable(entry) ? (
1155                      <Button
1156                        key={entry.id}
1157                        plain
1158                        dimColor={isOld}
1159                        onPress={() => toggleExpanded($, entry.id)}
1160                      >
1161                        {entry.patch !== undefined && <Text bold>{entry.tool} </Text>}
1162                        {clip(entry.label, columns - 20)}
1163                        {entry.patch !== undefined && (
1164                          <Text>
1165                            {' '}
1166                            <Text color="success">+{entry.added ?? 0}</Text>{' '}
1167                            <Text color="error">−{entry.removed ?? 0}</Text>
1168                          </Text>
1169                        )}
1170                        <Text dimColor> {open.has(entry.id) ? '▾' : '▸'}</Text>
1171                      </Button>
1172                    ) : (
1173                      <Text dimColor={isOld} wrap="truncate-end">
1174                        {entry.command === undefined && (
1175                          <Text bold>{entry.tool} </Text>
1176                        )}
1177                        {clip(entry.label, columns - 6)}
1178                      </Text>
1179                    )}
1180                  </Box>
1181                  {entry.patch !== undefined && open.has(entry.id) && (
1182                    <Box marginLeft={4} width={columns - 4}>
1183                      <Code
1184                        source={entry.patch}
1185                        format="diff"
1186                        path={entry.path}
1187                        wrap="truncate-end"
1188                      />
1189                    </Box>
1190                  )}
1191                  {entry.command !== undefined &&
1192                    (entry.status === 'error' || open.has(entry.id)) && (
1193                      <Box marginLeft={6} width={columns - 6}>
1194                        <Text dimColor wrap="wrap">
1195                          {entry.status === 'error'
1196                            ? clip(firstLine(entry.command), columns - 8)
1197                            : entry.command}
1198                        </Text>
1199                      </Box>
1200                    )}
types/index.d.ts 53 lines
1export type LogEntry = {
2  id: string
3  tool: string
4  label: string
5  command?: string
6  activity: string
7  path?: string
8  patch?: string
9  added?: number
10  removed?: number
11  status: 'running' | 'ok' | 'error'
12  // The run of tool calls it belongs to: calls with no text between them.
13  run?: string
14}
15
16export type LogGroup = {
17  id: string
18  prompt: string
19  startedAt: number
20  entries: LogEntry[]
21}
22
23export type Tick = { frame: number; elapsedMs: number; now: number }
24
25export type Tab = 'log' | 'files' | 'agents'
26
27export type AgentRow = {
28  id: string
29  description: string
30  type: string
31  startedAt: number
32  endedAt?: number
33  status: 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
34  lastStep: string
35  tools: number
36}
37
38declare module 'claude-code' {
39  interface PluginState {
40    'tool-log': {
41      groups: LogGroup[]
42      tick: Tick
43      expanded: string[]
44      isRepo: boolean
45      focus: string | null
46      tab: Tab
47      agents: AgentRow[]
48      seen: Partial<Record<Tab, string>>
49      scrollTop: Partial<Record<Tab, number | null>>
50    }
51  }
52}
53