Side panel with the current session's usage, tool calls, changes, activity, scratch files and stats

A side panel for browsing everything Claude Code knows about the current session: context and rate limits, every tool call with its full input and result, edited files with diffs, background activity with each subagent's own tool calls, the session's scratch directory, files saved by tools and usage statistics.
Open it with /session-panel.
Requires Claude Code with function-hook plugin support. Validated and tested with Claude Code 2.1.295.
Run in Claude Code:
/plugin install session-panel --marketplace mlopian/claude-plugins
For installation from a local clone, see the repository README. Start a new Claude Code session after installing.
| Key | Tab | Shows |
|---|---|---|
u | Usage | Session facts (title, ID, model, effort, permission mode, versions, branch, cost), rate limits, context fill with the /context grid, categories, memory files and tokens left before auto-compact, session paths, session-env contents |
t | Tool calls | One card per tool call, newest first: tool, status, start time, duration, description or file and the first three lines of input. Enter opens the call in full with syntax colouring |
c | Changes | git status of the session's repository with line counts, and the files Claude edited in this session with their backup versions. Enter opens a coloured diff |
a | Activity | Subagents and teammates with their status (Enter shows an agent's own tool calls), and background task output files |
f | Files | Browser of the session's scratch directory, plus files saved by tools (e.g. MCP screenshots) and pasted images |
s | Stats | Token totals, cache hit rate, turn durations, tool usage and the heaviest requests |
h | ? | All keyboard shortcuts |
| Key | Action |
|---|---|
ctrl+x tab | Move the keyboard from the prompt to the panel (Claude Code) |
esc | Give the keyboard back to the prompt (Claude Code) |
ctrl+x x | Close the panel (Claude Code) |
enter | Open the focused tool call, diff, file or folder |
b | Back from a tool call or diff to its list, or to the parent folder in Files |
j / k | Scroll the tool call list by half a page of cards |
e | Tool calls: show only failed calls, or all of them |
r | Tool calls: refresh |
The tool call list keeps the tab bar pinned and scrolls card by card. The other tabs and the full views scroll with the arrows, page keys and mouse wheel.
~/.claude/projects/<project>/<session>.jsonl, the edit backups from ~/.claude/file-history/<session>/, session-env from ~/.claude/session-env/<session>/ and the scratch directory from /tmp/claude-<uid>/<project>/<session>/.r. Usage, Activity and Files refresh every 2 seconds while the panel is shown. Changes reruns git status every 2 seconds while it is shown, and redraws only when the result changed.summary), so it sends no token-count requests.enter on a file opens it in $VISUAL or $EDITOR in a new herdr pane, or a new tmux window. Outside herdr and tmux the path is copied to the clipboard instead. PNG files open in the system viewer with open./session-panel is unknown, check /plugin to confirm session-panel is installed and enabled, then start a new session.$EDITOR is set and that the session runs inside herdr or tmux.open for PNG files is macOS only.Run from the repository root:
claude plugin validate session-panel
claude plugin test session-panel
Tests cover transcript parsing, tool call descriptions and timing, session metadata, file history, git status parsing, diff counts and formatting.
hooks/register.tsx 1073 lines1import { atom, read, update } from 'claude-code'
2import type { Color, EngineInterface, FsEntry, Register, RenderChildren } from 'claude-code'
3
4import type { SessionDiff, SessionGit, SessionPaths, SessionTab } from '../types'
5import {
6 cacheHitRate,
7 diffCounts,
8 formatCount,
9 formatDuration,
10 formatSize,
11 formatTime,
12 meter,
13 parseGitStatus,
14 parseTranscript,
15 previewLines,
16} from './format'
17import type { FileVersion, ToolCall } from './format'
18
19const PANE = 'session-panel'
20const tab = atom({ plugin: 'session-panel', key: 'tab' } as const, 'usage' as SessionTab)
21const dir = atom({ plugin: 'session-panel', key: 'dir' } as const, '')
22const tick = atom({ plugin: 'session-panel', key: 'tick' } as const, 0)
23const offset = atom({ plugin: 'session-panel', key: 'offset' } as const, 0)
24const isErrorsOnly = atom({ plugin: 'session-panel', key: 'isErrorsOnly' } as const, false)
25const selectedTool = atom({ plugin: 'session-panel', key: 'selectedTool' } as const, null as string | null)
26const listOffset = atom({ plugin: 'session-panel', key: 'listOffset' } as const, 0)
27const diff = atom({ plugin: 'session-panel', key: 'diff' } as const, null as SessionDiff | null)
28const git = atom({ plugin: 'session-panel', key: 'git' } as const, null as SessionGit | null)
29const pathsAtom = atom({ plugin: 'session-panel', key: 'paths' } as const, null as SessionPaths | null)
30const agentView = atom({ plugin: 'session-panel', key: 'agentView' } as const, null as { id: string; label: string } | null)
31
32const TABS: { id: SessionTab; label: string; hotkey: string }[] = [
33 { id: 'usage', label: 'Usage', hotkey: 'u' },
34 { id: 'tools', label: 'Tool calls', hotkey: 't' },
35 { id: 'changes', label: 'Changes', hotkey: 'c' },
36 { id: 'activity', label: 'Activity', hotkey: 'a' },
37 { id: 'files', label: 'Files', hotkey: 'f' },
38 { id: 'stats', label: 'Stats', hotkey: 's' },
39 { id: 'help', label: '?', hotkey: 'h' },
40]
41
42const LIVE_TABS = new Set<SessionTab>(['usage', 'activity', 'files'])
43const LIVE_REFRESH_MS = 2000
44const HEADER_ROWS = 3
45const CARD_ROWS = 6
46const PREVIEW_LINES = CARD_ROWS - 3
47
48const FILE_COLORS: Record<string, Color> = {
49 ts: 'ide',
50 tsx: 'ide',
51 js: 'warning',
52 json: 'merged',
53 jsonl: 'merged',
54 md: 'suggestion',
55 sh: 'success',
56 py: 'autoAccept',
57 html: 'claude',
58 css: 'planMode',
59}
60
61const GIT_COLORS: Record<string, Color> = {
62 M: 'warning',
63 A: 'success',
64 '??': 'success',
65 D: 'error',
66 R: 'merged',
67}
68
69function toolColor(name: string): Color {
70 if (name === 'Bash') return 'bashBorder'
71 if (name === 'Edit' || name === 'Write') return 'permission'
72 if (name === 'Read') return 'ide'
73 if (name.startsWith('mcp__')) return 'merged'
74
75 return 'suggestion'
76}
77
78function statusOf(call: ToolCall): { mark: string; color: Color } {
79 if (call.isError === null) return { mark: '…', color: 'warning' }
80
81 return call.isError ? { mark: '✗', color: 'error' } : { mark: '✓', color: 'success' }
82}
83
84const AGENT_COLORS: Record<string, Color> = {
85 running: 'warning',
86 pending: 'inactive',
87 waiting: 'permission',
88 idle: 'suggestion',
89 completed: 'success',
90 failed: 'error',
91 killed: 'error',
92}
93
94async function sessionPaths($: EngineInterface): Promise<SessionPaths> {
95 const [id, cwd, home, uid] = await Promise.all([
96 $.session.id(),
97 $.session.cwd(),
98 $.env.get('HOME'),
99 $.process.run(['id', '-u']),
100 ])
101 const found = await $.process.run(['sh', '-c', 'ls -d "$1"/.claude/projects/*/"$2".jsonl 2>/dev/null | head -1', 'sh', home, id])
102 const transcript = found.stdout.trim() || `${home}/.claude/projects/${cwd.replace(/[^a-zA-Z0-9]/g, '-')}/${id}.jsonl`
103 const projectKey = transcript.split('/').at(-2)
104
105 return {
106 id,
107 cwd,
108 transcript,
109 env: `${home}/.claude/session-env/${id}`,
110 tmp: `/tmp/claude-${uid.stdout.trim()}/${projectKey}/${id}`,
111 fileHistory: `${home}/.claude/file-history/${id}`,
112 }
113}
114
115function shellQuote(text: string): string {
116 return `'${text.replace(/'/g, `'\\''`)}'`
117}
118
119async function openInEditor($: EngineInterface, path: string): Promise<void> {
120 const editor = (await $.env.get('VISUAL')) ?? (await $.env.get('EDITOR')) ?? 'vi'
121 const command = `exec ${editor} ${shellQuote(path)}`
122 try {
123 const herdrPane = await $.env.get('HERDR_PANE_ID')
124 if (herdrPane) {
125 const split = await $.process.run(['herdr', 'pane', 'split', '--pane', herdrPane, '--direction', 'right', '--focus'])
126 const pane: string = JSON.parse(split.stdout).result.pane.pane_id
127 await $.process.run(['herdr', 'pane', 'run', pane, command])
128 return
129 }
130 if (await $.env.get('TMUX')) {
131 await $.process.run(['tmux', 'new-window', command])
132 return
133 }
134 await $.ui.copy({ text: path })
135 $.ui.toast(`No herdr or tmux, path copied: ${path}`)
136 } catch (error) {
137 $.ui.toast(`Could not open the editor: ${String(error)}`)
138 }
139}
140
141async function showDiff($: EngineInterface, paths: SessionPaths, file: string, versions: FileVersion[]): Promise<void> {
142 const first = versions.find(version => version.backupFileName)
143 const before = first ? `${paths.fileHistory}/${first.backupFileName}` : '/dev/null'
144 const after = (await $.fs.exists(file)) ? file : '/dev/null'
145 const run = await $.process.run(['diff', '-u', '-L', `before (v${first?.version ?? 0})`, '-L', 'now', before, after])
146 await update($, diff, () => ({ path: file, text: run.stdout, against: `first backup (v${first?.version ?? 0})` }))
147 await update($, offset, () => 0)
148}
149
150async function refreshGit($: EngineInterface): Promise<void> {
151 const repo = await $.session.repo()
152 if (!repo) {
153 await update($, git, () => null)
154 return
155 }
156 const [status, numstat] = await Promise.all([
157 $.process.run(['git', 'status', '--porcelain=v1', '--branch', '--untracked-files=all'], { cwd: repo.root }),
158 $.process.run(['git', 'diff', '--numstat', 'HEAD'], { cwd: repo.root }),
159 ])
160 const next = parseGitStatus(repo.root, status.stdout, numstat.stdout)
161 const previous = await read($, git)
162 if (JSON.stringify(previous) !== JSON.stringify(next)) await update($, git, () => next)
163}
164
165async function showGitDiff($: EngineInterface, status: SessionGit, file: SessionGit['files'][number]): Promise<void> {
166 const argv =
167 file.code === '??'
168 ? ['git', 'diff', '--no-index', '--', '/dev/null', file.path]
169 : ['git', 'diff', 'HEAD', '--', file.path]
170 const run = await $.process.run(argv, { cwd: status.root })
171 await update($, diff, () => ({ path: `${status.root}/${file.path}`, text: run.stdout, against: file.code === '??' ? 'untracked, whole file' : 'git HEAD' }))
172 await update($, offset, () => 0)
173}
174
175const CHUNK_BYTES = 4 * 1024 * 1024
176
177const transcriptCache = new Map<string, { size: number; text: string; parsed: ReturnType<typeof parseTranscript> }>()
178
179// $.fs.read rejects and $.process.run truncates anything over 4 MiB, so long transcripts are read in slices
180async function readFrom($: EngineInterface, path: string, from: number, to: number): Promise<string> {
181 let text = ''
182 for (let offset = from; offset < to; offset += CHUNK_BYTES) {
183 const slice = await $.process.run(['sh', '-c', 'tail -c +"$1" "$2" | head -c "$3"', 'sh', String(offset + 1), path, String(CHUNK_BYTES)])
184 text += slice.stdout
185 }
186
187 return text
188}
189
190// ponytail: re-parses the whole text on every growth; parse incrementally if mid-turn redraws lag
191async function loadTranscript($: EngineInterface, path: string): Promise<ReturnType<typeof parseTranscript>> {
192 const size = (await $.fs.exists(path)) ? (await $.fs.stat(path)).size : 0
193 const previous = transcriptCache.get(path)
194 const cached = previous && previous.size <= size ? previous : null
195 if (cached?.size === size) return cached.parsed
196
197 const text = (cached?.text ?? '') + (await readFrom($, path, cached?.size ?? 0, size))
198 const parsed = parseTranscript(text)
199 transcriptCache.set(path, { size, text, parsed })
200
201 return parsed
202}
203
204async function listOr($: EngineInterface, path: string): Promise<FsEntry[]> {
205 return (await $.fs.exists(path)) ? $.fs.list(path) : []
206}
207
208function sortEntries(entries: FsEntry[]): FsEntry[] {
209 return [...entries].sort((a, b) =>
210 (a.kind === 'dir') === (b.kind === 'dir') ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1,
211 )
212}
213
214function loadColor(percent: number): Color {
215 if (percent >= 80) return 'error'
216 if (percent >= 50) return 'warning'
217
218 return 'success'
219}
220
221function fileColor(name: string): Color {
222 return FILE_COLORS[name.split('.').pop() ?? ''] ?? 'text'
223}
224
225function shortTime(ms: number): string {
226 return new Date(ms).toLocaleString('en-GB', { hour12: false, day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })
227}
228
229function shortPath(path: string, cwd: string): string {
230 return path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path
231}
232
233let maxOffset = 0
234let isListMode = false
235
236async function refreshLiveTab($: EngineInterface): Promise<void> {
237 const paths = await read($, pathsAtom)
238 if (paths && paths.id !== (await $.session.id())) {
239 const fresh = await sessionPaths($)
240 await update($, pathsAtom, () => fresh)
241 }
242 const [current, panes] = await Promise.all([read($, tab), $.ui.panes()])
243 if (!panes.some(pane => pane.id === PANE && pane.isShown)) return
244 if (current === 'changes') await refreshGit($)
245 else if (LIVE_TABS.has(current)) await update($, tick, n => n + 1)
246}
247
248function scrollBy($: EngineInterface, rows: number): Promise<unknown> {
249 return update($, offset, current => Math.max(0, Math.min(maxOffset, current + rows)))
250}
251
252export const register: Register = on => {
253 on('session.start', async ($, e, next) => {
254 await $.command.register({
255 name: 'session-panel',
256 immediate: true,
257 description: 'Show the current session transcript, changes, activity, stats, environment, scratch directory and tool result files in a side pane',
258 })
259 const paths = await sessionPaths($)
260 await update($, pathsAtom, () => paths)
261 $.clock.every(LIVE_REFRESH_MS, () => void refreshLiveTab($))
262
263 return next(e)
264 })
265
266 on('command.run', { command: 'session-panel' }, async $ => {
267 await $.ui.open({ id: PANE, title: 'Session', focus: true })
268 await $.ui.scroll({ to: 'start', in: PANE })
269
270 return { text: 'Session panel opened.' }
271 })
272
273 on('turn.complete', async ($, e, next) => {
274 const result = await next(e)
275 await update($, tick, n => n + 1)
276 await refreshGit($)
277
278 return result
279 })
280
281 on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
282 if (!isListMode) return next(e)
283 if (e.origin.kind === 'person') await scrollBy($, Math.sign(e.by))
284
285 return next({ ...e, offset: 0 })
286 })
287
288 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
289 const { Box, Text, Button, Code } = $.ui.resolve(e)
290 const [current, relative, paths, scrolled, errorsOnly, selectedId, savedListOffset, currentDiff, gitStatus, viewedAgent] = await Promise.all([
291 read($, tab),
292 read($, dir),
293 read($, pathsAtom),
294 read($, offset),
295 read($, isErrorsOnly),
296 read($, selectedTool),
297 read($, listOffset),
298 read($, diff),
299 read($, git),
300 read($, agentView),
301 read($, tick),
302 ])
303 if (!paths) return <Text dimColor>Loading session paths...</Text>
304
305 const columns = e.props.bodyColumns
306 const bodyRows = e.props.scroll.bodyRows
307 const windowRows = Math.max(CARD_ROWS, bodyRows - HEADER_ROWS)
308 const visibleCount = Math.max(1, Math.floor(windowRows / CARD_ROWS))
309 const page = Math.max(1, Math.floor(visibleCount / 2))
310 isListMode = false
311
312 const section = (title: string, color: Color, children: RenderChildren) => (
313 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
314 <Text bold color={color}>
315 {title}
316 </Text>
317 {children}
318 </Box>
319 )
320
321 const fact = (label: string, value: string, color: Color = 'text') => (
322 <Box flexDirection="row" columnGap={1}>
323 <Box width={14} flexShrink={0}>
324 <Text dimColor>{label}</Text>
325 </Box>
326 <Text color={color} wrap="wrap">
327 {value}
328 </Text>
329 </Box>
330 )
331
332 const gauge = (label: string, percent: number, detail: string) => (
333 <Box flexDirection="row" columnGap={1}>
334 <Box width={14} flexShrink={0}>
335 <Text dimColor>{label}</Text>
336 </Box>
337 <Text color={loadColor(percent)}>{meter(percent)}</Text>
338 <Text bold color={loadColor(percent)}>
339 {`${Math.round(percent)}%`}
340 </Text>
341 <Text dimColor>{detail}</Text>
342 </Box>
343 )
344
345 const bar = (label: string, value: number, max: number, detail: string, color: Color) => (
346 <Box flexDirection="row" columnGap={1}>
347 <Box width={14} flexShrink={0}>
348 <Text dimColor wrap="truncate-end">
349 {label}
350 </Text>
351 </Box>
352 <Text color={color}>{'█'.repeat(Math.max(1, Math.round((value / Math.max(1, max)) * 30)))}</Text>
353 <Text dimColor>{detail}</Text>
354 </Box>
355 )
356
357 const actions = (extra: RenderChildren) => (
358 <Box flexDirection="row" columnGap={1} height={1} flexShrink={0} overflow="hidden">
359 {extra}
360 </Box>
361 )
362
363 const tabRow = (
364 <Box flexDirection="row" columnGap={1} height={1} flexShrink={0} overflow="hidden">
365 {TABS.map(one => (
366 <Button
367 key={`tab-${one.id}`}
368 label={one.label}
369 hotkey={one.hotkey}
370 variant={one.id === current ? 'primary' : 'secondary'}
371 onPress={async () => {
372 await update($, tab, () => one.id)
373 await update($, offset, () => 0)
374 await update($, agentView, () => null)
375 if (one.id === 'changes') await refreshGit($)
376 }}
377 />
378 ))}
379 </Box>
380 )
381
382 const separator = (label: string) => (
383 <Box flexDirection="row" columnGap={1} height={1} flexShrink={0}>
384 <Text color="inactive">{'─'.repeat(Math.max(0, columns - label.length - 2))}</Text>
385 <Text color="suggestion">{label}</Text>
386 </Box>
387 )
388
389 const frame = (toolbar: RenderChildren, body: RenderChildren) => (
390 <Box flexDirection="column">
391 {tabRow}
392 {toolbar}
393 {separator('')}
394 {body}
395 </Box>
396 )
397
398 if (current === 'help') {
399 const shortcut = (keys: string, action: string) => (
400 <Box flexDirection="row" columnGap={1}>
401 <Box width={14} flexShrink={0}>
402 <Text bold color="suggestion">
403 {keys}
404 </Text>
405 </Box>
406 <Text>{action}</Text>
407 </Box>
408 )
409
410 return frame(
411 actions(null),
412 <Box flexDirection="column" rowGap={1}>
413 {section(
414 '⌨ Claude Code',
415 'claude',
416 <Box flexDirection="column">
417 {shortcut('ctrl+x tab', 'move the keyboard from the prompt to this panel')}
418 {shortcut('esc', 'give the keyboard back to the prompt')}
419 {shortcut('ctrl+x x', 'close the panel')}
420 {shortcut('tab / arrows', 'walk the buttons while the panel has the keyboard')}
421 {shortcut('enter', 'press the focused button')}
422 {shortcut('/session-panel', 'open the panel with the keyboard in it')}
423 </Box>,
424 )}
425 {section(
426 '▦ Tabs',
427 'suggestion',
428 <Box flexDirection="column">
429 {TABS.map(one => shortcut(one.hotkey, one.id === 'help' ? 'this help' : one.label))}
430 </Box>,
431 )}
432 {section(
433 '↕ Everywhere',
434 'ide',
435 <Box flexDirection="column">
436 {shortcut('j / k', 'tool call list: scroll down / up by half a page of cards')}
437 {shortcut('mouse wheel', 'scroll, one card at a time in the tool call list')}
438 {shortcut('arrows / pgup / pgdn', 'scroll the other tabs and a tool call in full')}
439 </Box>,
440 )}
441 {section(
442 '⏺ Tool calls',
443 'bashBorder',
444 <Box flexDirection="column">
445 {shortcut('enter', 'open the focused tool call in full, with syntax colouring')}
446 {shortcut('b', 'back from a tool call to the list')}
447 {shortcut('e', 'show only failed tool calls, or all of them')}
448 {shortcut('r', 'refresh (it also refreshes after every turn)')}
449 </Box>,
450 )}
451 {section(
452 '± Changes',
453 'permission',
454 <Box flexDirection="column">
455 {shortcut('enter', 'open a diff: a git file against HEAD, a session file against its first backup')}
456 {shortcut('b', 'back from a diff to the list')}
457 </Box>,
458 )}
459 {section(
460 '▣ Files',
461 'ide',
462 <Box flexDirection="column">
463 {shortcut('enter', 'open a file in $EDITOR, a PNG in the system viewer, or enter a folder')}
464 {shortcut('b', 'go back to the parent folder')}
465 </Box>,
466 )}
467 <Text color="inactive" italic>
468 Usage, Activity and Files refresh by themselves every 2 seconds.
469 </Text>
470 </Box>,
471 )
472 }
473
474 const transcript = await loadTranscript($, paths.transcript)
475 const { meta } = transcript
476
477 if (current === 'tools') {
478 const shown = viewedAgent
479 ? await loadTranscript($, `${paths.transcript.replace(/\.jsonl$/, '')}/subagents/agent-${viewedAgent.id}.jsonl`)
480 : transcript
481 const selected = selectedId ? shown.toolCalls.find(call => call.id === selectedId) : undefined
482
483 if (selected) {
484 const status = statusOf(selected)
485 const color = toolColor(selected.name)
486
487 return frame(
488 actions(
489 <Button
490 key="back"
491 label="↰ Back"
492 hotkey="b"
493 onPress={async () => {
494 await update($, selectedTool, () => null)
495 await update($, offset, () => savedListOffset)
496 }}
497 />,
498 ),
499 <Box flexDirection="column" rowGap={1}>
500 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
501 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
502 <Text bold color={color}>{`⏺ ${selected.name}`}</Text>
503 <Text bold color={status.color}>{`${status.mark} ${selected.isError === null ? 'running' : selected.isError ? 'failed' : 'ok'}`}</Text>
504 <Text color="inactive">{formatDuration(selected.durationMs)}</Text>
505 </Box>
506 <Text dimColor>{`started ${selected.startedAt ? new Date(selected.startedAt).toLocaleString('en-GB', { hour12: false }) : 'unknown'}`}</Text>
507 {selected.summary && <Text color="suggestion">{selected.summary}</Text>}
508 </Box>
509 {section(
510 '▸ Input',
511 color,
512 <Code source={selected.source || ' '} language={selected.language || undefined} format={selected.format} />,
513 )}
514 {section(
515 selected.isError ? '✗ Result' : '◂ Result',
516 selected.isError ? 'error' : 'success',
517 selected.result ? <Code source={selected.result} /> : <Text dimColor italic>No result yet.</Text>,
518 )}
519 </Box>,
520 )
521 }
522
523 const calls = shown.toolCalls.filter(call => !errorsOnly || call.isError).reverse()
524 const errorCount = shown.toolCalls.filter(call => call.isError).length
525 isListMode = true
526 maxOffset = Math.max(0, calls.length - visibleCount)
527 const first = Math.min(scrolled, maxOffset)
528 const visibleCalls = calls.slice(first, first + visibleCount)
529 const range = calls.length === 0 ? '' : `${first + 1}-${first + visibleCalls.length} of ${calls.length}`
530 const position = viewedAgent ? `${viewedAgent.label} ${range}` : range
531
532 return (
533 <Box flexDirection="column" height={bodyRows}>
534 {tabRow}
535 {actions(
536 <>
537 {viewedAgent && (
538 <Button
539 key="session"
540 label="↰ Session"
541 hotkey="b"
542 onPress={async () => {
543 await update($, agentView, () => null)
544 await update($, tab, () => 'activity' as const)
545 await update($, offset, () => 0)
546 }}
547 />
548 )}
549 <Button key="up" label="▲" hotkey="k" onPress={() => scrollBy($, -page)} />
550 <Button key="down" label="▼" hotkey="j" onPress={() => scrollBy($, page)} />
551 <Button key="refresh" label="Refresh" hotkey="r" onPress={() => update($, tick, n => n + 1)} />
552 <Button
553 key="errors-only"
554 label={errorsOnly ? 'Show all' : `Errors only (${errorCount})`}
555 hotkey="e"
556 onPress={async () => {
557 await update($, isErrorsOnly, value => !value)
558 await update($, offset, () => 0)
559 }}
560 />
561 </>,
562 )}
563 {separator(position)}
564 <Box flexDirection="column" height={windowRows} flexShrink={0} overflow="hidden">
565 {calls.length === 0 && <Text dimColor italic>{errorsOnly ? 'No failed tool calls.' : 'No tool calls yet.'}</Text>}
566 {visibleCalls.map(call => {
567 const color = toolColor(call.name)
568 const status = statusOf(call)
569
570 return (
571 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} height={CARD_ROWS} flexShrink={0}>
572 <Box flexDirection="row" columnGap={1} height={1} overflow="hidden">
573 <Button
574 key={`tool-${call.id}`}
575 plain
576 label={`⏺ ${call.name}`}
577 onPress={async () => {
578 await update($, listOffset, () => first)
579 await update($, selectedTool, () => call.id)
580 await update($, offset, () => 0)
581 }}
582 />
583 <Box flexShrink={0}>
584 <Text color={status.color}>{status.mark}</Text>
585 </Box>
586 <Box flexShrink={0}>
587 <Text dimColor>{formatTime(call.startedAt)}</Text>
588 </Box>
589 <Box flexShrink={0}>
590 <Text color="inactive">{formatDuration(call.durationMs)}</Text>
591 </Box>
592 <Text color="suggestion" wrap="truncate-end">
593 {call.summary}
594 </Text>
595 </Box>
596 <Code
597 source={previewLines(call.format === 'diff' ? call.source.split('\n').slice(3).join('\n') : call.source, PREVIEW_LINES).join('\n')}
598 language={call.language || undefined}
599 wrap="truncate-end"
600 />
601 </Box>
602 )
603 })}
604 </Box>
605 </Box>
606 )
607 }
608
609 if (current === 'changes') {
610 const files = Object.entries(transcript.fileVersions).sort(
611 ([, a], [, b]) => Date.parse(b.at(-1)?.time ?? '') - Date.parse(a.at(-1)?.time ?? ''),
612 )
613
614
615 if (currentDiff) {
616 const counts = diffCounts(currentDiff.text)
617
618 return frame(
619 actions(<Button key="back" label="↰ Back" hotkey="b" onPress={() => update($, diff, () => null)} />),
620 <Box flexDirection="column" rowGap={1}>
621 <Box flexDirection="column" borderStyle="round" borderColor={fileColor(currentDiff.path)} paddingX={1}>
622 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
623 <Text bold color={fileColor(currentDiff.path)}>{`± ${shortPath(currentDiff.path, paths.cwd)}`}</Text>
624 <Text color="diffAdded">{`+${counts.added}`}</Text>
625 <Text color="diffRemoved">{`-${counts.removed}`}</Text>
626 </Box>
627 <Text dimColor>{`against ${currentDiff.against}`}</Text>
628 </Box>
629 {section(
630 '▸ Diff',
631 'diffAdded',
632 currentDiff.text ? (
633 <Code source={currentDiff.text} format="diff" path={currentDiff.path} />
634 ) : (
635 <Text dimColor italic>No changes.</Text>
636 ),
637 )}
638 </Box>,
639 )
640 }
641
642 return frame(
643 actions(null),
644 <Box flexDirection="column" rowGap={1}>
645 {section(
646 gitStatus ? `⎇ git: ${gitStatus.branch || 'detached'}` : '⎇ git',
647 'ide',
648 !gitStatus ? (
649 <Text dimColor italic>
650 The working directory is not a git repository.
651 </Text>
652 ) : gitStatus.files.length === 0 ? (
653 <Text color="success">Working tree clean.</Text>
654 ) : (
655 <Box flexDirection="column">
656 {gitStatus.files.map(file => (
657 <Box flexDirection="row" columnGap={1}>
658 <Box width={3} flexShrink={0}>
659 <Text bold color={GIT_COLORS[file.code] ?? 'warning'}>
660 {file.code}
661 </Text>
662 </Box>
663 <Button key={`git-${file.path}`} plain label={file.path} onPress={() => showGitDiff($, gitStatus, file)} />
664 {file.added > 0 && <Text color="diffAdded">{`+${file.added}`}</Text>}
665 {file.removed > 0 && <Text color="diffRemoved">{`-${file.removed}`}</Text>}
666 </Box>
667 ))}
668 </Box>
669 ),
670 )}
671 {section(
672 `✎ Files edited in this session (${files.length})`,
673 'permission',
674 files.length === 0 ? (
675 <Text dimColor italic>
676 Claude has not edited any files yet.
677 </Text>
678 ) : (
679 <Box flexDirection="column">
680 {files.map(([file, versions]) => (
681 <Box flexDirection="column">
682 <Box flexDirection="row" columnGap={1}>
683 <Text color={fileColor(file)}>●</Text>
684 <Button key={`diff-${file}`} plain label={shortPath(file, paths.cwd)} onPress={() => showDiff($, paths, file, versions)} />
685 </Box>
686 <Box flexDirection="row" columnGap={1} paddingLeft={2}>
687 <Text color="suggestion">{`${versions.length} versions`}</Text>
688 <Text dimColor>{`last ${shortTime(Date.parse(versions.at(-1)?.time ?? ''))}`}</Text>
689 <Button key={`edit-${file}`} plain label="edit" onPress={() => openInEditor($, file)} />
690 </Box>
691 </Box>
692 ))}
693 </Box>
694 ),
695 )}
696 <Text color="inactive" italic>
697 Enter shows a diff: git files against HEAD, session files against the first backup Claude took.
698 </Text>
699 </Box>,
700 )
701 }
702
703 if (current === 'activity') {
704 const [agents, tasks] = await Promise.all([$.agent.list(), listOr($, `${paths.tmp}/tasks`)])
705 const taskFiles = tasks.filter(task => task.kind === 'file').sort((a, b) => b.mtimeMs - a.mtimeMs)
706
707 return frame(
708 actions(null),
709 <Box flexDirection="column" rowGap={1}>
710 {section(
711 `⚙ Agents (${agents.length})`,
712 'autoAccept',
713 agents.length === 0 ? (
714 <Text dimColor italic>
715 No subagents or teammates in this session.
716 </Text>
717 ) : (
718 <Box flexDirection="column">
719 {agents.map(agent => (
720 <Box flexDirection="column">
721 <Button key={`agent-${agent.id}`} plain onPress={async () => {
722 await update($, agentView, () => ({ id: agent.id, label: `${agent.type}: ${agent.description}` }))
723 await update($, selectedTool, () => null)
724 await update($, tab, () => 'tools' as const)
725 await update($, offset, () => 0)
726 }}>
727 <Text bold color={AGENT_COLORS[agent.status] ?? 'text'}>{`● ${agent.status}`}</Text>{' '}
728 <Text color="merged">{agent.type}</Text>
729 {agent.name && <Text color="suggestion">{` ${agent.name}`}</Text>}
730 </Button>
731 <Box paddingLeft={2}>
732 <Text dimColor wrap="truncate-end">
733 {agent.description}
734 </Text>
735 </Box>
736 </Box>
737 ))}
738 </Box>
739 ),
740 )}
741 {section(
742 `▶ Background task output (${taskFiles.length})`,
743 'bashBorder',
744 taskFiles.length === 0 ? (
745 <Text dimColor italic>
746 No background task output yet.
747 </Text>
748 ) : (
749 <Box flexDirection="column">
750 {taskFiles.map(task => (
751 <Box flexDirection="row" columnGap={1}>
752 <Text color="bashBorder">▸</Text>
753 <Button key={`task-${task.name}`} plain label={task.name} onPress={() => openInEditor($, `${paths.tmp}/tasks/${task.name}`)} />
754 <Text color="inactive">{formatSize(task.size)}</Text>
755 <Text dimColor>{shortTime(task.mtimeMs)}</Text>
756 </Box>
757 ))}
758 </Box>
759 ),
760 )}
761 </Box>,
762 )
763 }
764
765 if (current === 'stats') {
766 const turns = transcript.turnSeconds.map((seconds, index) => ({ index: index + 1, seconds })).slice(-15)
767 const longestTurn = Math.max(0, ...transcript.turnSeconds)
768 const totalSeconds = transcript.turnSeconds.reduce((sum, seconds) => sum + seconds, 0)
769 const tools = Object.entries(transcript.toolCounts).sort(([, a], [, b]) => b - a)
770 const topTool = tools[0]?.[1] ?? 0
771 const heaviest = [...transcript.requests].sort((a, b) => b.output - a.output).slice(0, 5)
772 const sum = (pick: (one: (typeof transcript.requests)[number]) => number) => transcript.requests.reduce((total, one) => total + pick(one), 0)
773 const hitRate = cacheHitRate(transcript.requests)
774
775 return frame(
776 actions(null),
777 <Box flexDirection="column" rowGap={1}>
778 {section(
779 'Σ Totals',
780 'claude',
781 <Box flexDirection="column">
782 {fact('Requests', String(transcript.requests.length), 'suggestion')}
783 {fact('Turns', `${transcript.turnSeconds.length}, ${(totalSeconds / 60).toFixed(1)} min of work`, 'suggestion')}
784 {fact('Input', formatCount(sum(one => one.input)), 'ide')}
785 {fact('Output', formatCount(sum(one => one.output)), 'success')}
786 {fact('Cache read', formatCount(sum(one => one.cacheRead)), 'merged')}
787 {fact('Cache write', formatCount(sum(one => one.cacheWrite)), 'merged')}
788 {gauge('Cache hits', hitRate, 'of input served from cache')}
789 </Box>,
790 )}
791 {section(
792 `⏱ Turn durations (last ${turns.length})`,
793 'warning',
794 <Box flexDirection="column">
795 {turns.map(turn =>
796 bar(`#${turn.index}`, turn.seconds, longestTurn, `${turn.seconds.toFixed(1)}s`, turn.seconds === longestTurn ? 'error' : 'warning'),
797 )}
798 </Box>,
799 )}
800 {section(
801 '⚒ Tools used',
802 'permission',
803 <Box flexDirection="column">
804 {tools.map(([name, count]) => bar(name, count, topTool, String(count), name === 'Bash' ? 'bashBorder' : 'permission'))}
805 </Box>,
806 )}
807 {section(
808 '⇡ Heaviest requests',
809 'success',
810 <Box flexDirection="column">
811 {heaviest.map(one => (
812 <Box flexDirection="row" columnGap={1}>
813 <Text dimColor>{one.time}</Text>
814 <Text color="success">{`out ${formatCount(one.output)}`}</Text>
815 <Text color="merged">{`cache ${formatCount(one.cacheRead)}`}</Text>
816 <Text color="inactive">{one.model}</Text>
817 </Box>
818 ))}
819 </Box>,
820 )}
821 </Box>,
822 )
823 }
824
825 if (current === 'usage') {
826 const [model, version, turns, repo, usage, envFiles] = await Promise.all([
827 $.session.model(),
828 $.session.version(),
829 $.session.turns(),
830 $.session.repo(),
831 $.session.usage({ breakdown: 'summary', columns }),
832 listOr($, paths.env),
833 ])
834 const envContents = await Promise.all(
835 envFiles
836 .filter(entry => entry.kind === 'file')
837 .map(async entry => ({ name: entry.name, text: await $.fs.read(`${paths.env}/${entry.name}`) })),
838 )
839 const { context } = usage
840 const breakdown = context.breakdown
841 const categories = (breakdown?.categories ?? []).filter(category => category.kind !== 'deferred' && category.tokens > 0)
842
843 return frame(
844 actions(null),
845 <Box flexDirection="column" rowGap={1}>
846 {section(
847 '◆ Session',
848 'claude',
849 <Box flexDirection="column">
850 {meta.title && fact('Title', meta.title, 'claude')}
851 {fact('ID', paths.id, 'merged')}
852 {fact('Model', model, 'claude')}
853 {fact('Effort', meta.effort || 'n/a', 'planMode')}
854 {fact('Mode', meta.permissionMode || 'n/a', 'autoAccept')}
855 {fact('Claude Code', meta.versions.length > 1 ? meta.versions.join(' → ') : version.version)}
856 {fact('Started', shortTime(usage.startedAt))}
857 {fact('Turns', String(turns), 'suggestion')}
858 {fact('Cost', usage.cost ? `$${usage.cost.usd.toFixed(2)}` : 'n/a', 'success')}
859 {fact('Working dir', paths.cwd, 'ide')}
860 {fact('Repository', repo ? `${repo.name ?? repo.root}${repo.remote ? ` (${repo.remote})` : ''}` : 'none', 'ide')}
861 {meta.branch && fact('Branch', meta.branch, 'ide')}
862 </Box>,
863 )}
864 {usage.rateLimits.length > 0 &&
865 section(
866 '◔ Rate limits',
867 'error',
868 <Box flexDirection="column">
869 {usage.rateLimits.map(limit =>
870 gauge(limit.kind, limit.percentUsed, limit.resetsAt ? `resets ${shortTime(Date.parse(limit.resetsAt))}` : ''),
871 )}
872 </Box>,
873 )}
874 {section(
875 '▤ Context',
876 'warning',
877 <Box flexDirection="column">
878 {context.percent === undefined
879 ? fact('Context', 'not measured yet')
880 : gauge('Context', context.percent, `${formatCount(context.tokens ?? 0)} / ${formatCount(context.window)}`)}
881 {breakdown?.isAutoCompactEnabled && breakdown.autoCompactThreshold !== undefined && (
882 <Box>
883 {fact(
884 'Auto-compact',
885 `at ${formatCount(breakdown.autoCompactThreshold)}, ${formatCount(Math.max(0, breakdown.autoCompactThreshold - breakdown.totalTokens))} tokens left`,
886 'warning',
887 )}
888 </Box>
889 )}
890 {breakdown && (
891 <Box flexDirection="column" marginTop={1}>
892 {breakdown.gridRows.map(row => (
893 <Text>
894 {row.map(square => (
895 <Text color={square.color}>{square.isFilled ? '■ ' : '□ '}</Text>
896 ))}
897 </Text>
898 ))}
899 </Box>
900 )}
901 {categories.map(category => (
902 <Box flexDirection="row" columnGap={1}>
903 <Text color={category.color}>■</Text>
904 <Box width={22} flexShrink={0}>
905 <Text wrap="truncate-end">{category.name}</Text>
906 </Box>
907 <Text color={category.color}>{formatCount(category.tokens)}</Text>
908 <Text dimColor>{`${((category.tokens / Math.max(1, breakdown?.maxTokens ?? 1)) * 100).toFixed(1)}%`}</Text>
909 </Box>
910 ))}
911 {breakdown && breakdown.memoryFiles.length > 0 && (
912 <Box flexDirection="column" marginTop={1}>
913 <Text bold color="suggestion">
914 Memory files
915 </Text>
916 {breakdown.memoryFiles.map(file => (
917 <Box flexDirection="row" columnGap={1}>
918 <Text color="merged">{formatCount(file.tokens)}</Text>
919 <Text dimColor wrap="truncate-start">
920 {file.path}
921 </Text>
922 </Box>
923 ))}
924 </Box>
925 )}
926 </Box>,
927 )}
928 {section(
929 '⌂ Paths',
930 'suggestion',
931 <Box flexDirection="column">
932 {fact('Transcript', paths.transcript, 'merged')}
933 {fact('session-env', paths.env, 'merged')}
934 {fact('File history', paths.fileHistory, 'merged')}
935 {fact('Scratch dir', paths.tmp, 'merged')}
936 <Box flexDirection="row" columnGap={1} marginTop={1}>
937 <Button key="env-open-transcript" label="Edit transcript" onPress={() => openInEditor($, paths.transcript)} />
938 <Button key="env-open-scratch" label="Browse scratch dir" onPress={() => update($, tab, () => 'files' as const)} />
939 </Box>
940 </Box>,
941 )}
942 {section(
943 '$ session-env',
944 'success',
945 envContents.length === 0 ? (
946 <Text dimColor italic>
947 Empty, the session has not exported any variables yet.
948 </Text>
949 ) : (
950 <Box flexDirection="column">
951 {envContents.map(file => (
952 <Box flexDirection="column">
953 <Text color="success">{file.name}</Text>
954 <Code source={file.text} language="sh" />
955 </Box>
956 ))}
957 </Box>
958 ),
959 )}
960 </Box>,
961 )
962 }
963
964 const here = relative ? `${paths.tmp}/${relative}` : paths.tmp
965 const toolResultsDir = `${paths.transcript.replace(/\.jsonl$/, '')}/tool-results`
966 const imagesDir = `${paths.tmp}/images`
967 const newestFiles = (list: FsEntry[]) => list.filter(entry => entry.kind !== 'dir').sort((a, b) => b.mtimeMs - a.mtimeMs)
968 const [entries, toolResults, images] = await Promise.all([
969 listOr($, here).then(sortEntries),
970 listOr($, toolResultsDir).then(newestFiles),
971 listOr($, imagesDir).then(newestFiles),
972 ])
973 const fileRow = (folder: string, entry: FsEntry) => (
974 <Box flexDirection="row" columnGap={1}>
975 <Text color={fileColor(entry.name)}>●</Text>
976 <Button
977 key={`file-${folder}/${entry.name}`}
978 plain
979 label={entry.name}
980 onPress={async () => {
981 const path = `${folder}/${entry.name}`
982 if (entry.name.toLowerCase().endsWith('.png')) await $.process.run(['open', path])
983 else await openInEditor($, path)
984 }}
985 />
986 <Text color="inactive">{formatSize(entry.size)}</Text>
987 <Text dimColor>{shortTime(entry.mtimeMs)}</Text>
988 </Box>
989 )
990 const crumbs = ['scratchpad root', ...(relative ? relative.split('/') : [])]
991
992 return frame(
993 actions(
994 relative && (
995 <Button key="parent" label="↰ Up" hotkey="b" onPress={() => update($, dir, d => d.split('/').slice(0, -1).join('/'))} />
996 ),
997 ),
998 <Box flexDirection="column" rowGap={1}>
999 {section(
1000 '▣ Scratch directory',
1001 'ide',
1002 <Box flexDirection="column">
1003 <Button key="open-scratch" plain onPress={() => $.process.run(['open', here])}>
1004 <Text color="inactive" wrap="truncate-start">
1005 {paths.tmp}
1006 </Text>
1007 </Button>
1008 <Text>
1009 {crumbs.map((crumb, index) => (
1010 <Text color={index === crumbs.length - 1 ? 'suggestion' : 'inactive'} bold={index === crumbs.length - 1}>
1011 {index === 0 ? crumb : ` › ${crumb}`}
1012 </Text>
1013 ))}
1014 </Text>
1015 </Box>,
1016 )}
1017 <Box flexDirection="column">
1018 {entries.length === 0 && (
1019 <Text dimColor italic>
1020 Empty directory.
1021 </Text>
1022 )}
1023 {entries.map(entry =>
1024 entry.kind === 'dir' ? (
1025 <Box flexDirection="row" columnGap={1}>
1026 <Text color="suggestion">▸</Text>
1027 <Button
1028 key={`dir-${entry.name}`}
1029 plain
1030 label={`${entry.name}/`}
1031 onPress={async () => {
1032 await update($, dir, d => (d ? `${d}/${entry.name}` : entry.name))
1033 await update($, offset, () => 0)
1034 }}
1035 />
1036 </Box>
1037 ) : (
1038 fileRow(here, entry)
1039 ),
1040 )}
1041 </Box>
1042 {
1043 [
1044 ['⧉ Tool results', toolResultsDir, toolResults, 'Tools have not saved any files yet.'] as const,
1045 ['◩ Pasted images', imagesDir, images, 'No images pasted yet.'] as const,
1046 ].map(([title, path, list, empty]) =>
1047 section(
1048 `${title} (${list.length})`,
1049 'ide',
1050 <Box flexDirection="column">
1051 <Button key={`open-${path}`} plain onPress={() => $.process.run(['open', path])}>
1052 <Text color="inactive" wrap="truncate-start">
1053 {path}
1054 </Text>
1055 </Button>
1056 {list.length === 0 ? (
1057 <Text dimColor italic>
1058 {empty}
1059 </Text>
1060 ) : (
1061 list.map(entry => fileRow(path, entry))
1062 )}
1063 </Box>,
1064 ),
1065 )}
1066 <Text color="inactive" italic>
1067 Enter opens a file in $EDITOR in a new herdr pane, a PNG in the system viewer.
1068 </Text>
1069 </Box>,
1070 )
1071 })
1072}
1073hooks/format.ts 302 lines1type Block = {
2 type: string
3 name?: string
4 id?: string
5 input?: Record<string, unknown>
6 tool_use_id?: string
7 content?: unknown
8 is_error?: boolean
9}
10
11type Usage = {
12 input_tokens?: number
13 output_tokens?: number
14 cache_read_input_tokens?: number
15 cache_creation_input_tokens?: number
16}
17
18type Backup = { backupFileName: string | null; version: number; backupTime: string }
19
20type Row = {
21 type: string
22 subtype?: string
23 timestamp?: string
24 requestId?: string
25 durationMs?: number
26 gitBranch?: string
27 effort?: string
28 version?: string
29 aiTitle?: string
30 permissionMode?: string
31 snapshot?: { trackedFileBackups?: Record<string, Backup> }
32 trackingPath?: string
33 backup?: Backup
34 message?: { model?: string; content?: string | Block[]; usage?: Usage }
35}
36
37export type ToolCall = {
38 id: string
39 name: string
40 startedAt: string
41 durationMs: number | null
42 summary: string
43 source: string
44 language: string
45 format: 'source' | 'diff'
46 result: string
47 isError: boolean | null
48}
49
50export type RequestStats = { time: string; model: string; input: number; output: number; cacheRead: number; cacheWrite: number }
51
52export type FileVersion = { backupFileName: string | null; version: number; time: string }
53
54export type SessionMeta = {
55 title: string
56 branch: string
57 permissionMode: string
58 effort: string
59 versions: string[]
60}
61
62export type Transcript = {
63 rows: number
64 prompts: number
65 outputTokens: number
66 meta: SessionMeta
67 toolCalls: ToolCall[]
68 turnSeconds: number[]
69 requests: RequestStats[]
70 toolCounts: Record<string, number>
71 fileVersions: Record<string, FileVersion[]>
72}
73
74const MAX_TEXT = 20_000
75
76const LANGUAGES: Record<string, string> = {
77 ts: 'typescript',
78 tsx: 'tsx',
79 js: 'javascript',
80 mjs: 'javascript',
81 json: 'json',
82 md: 'markdown',
83 py: 'python',
84 sh: 'sh',
85 java: 'java',
86 kt: 'kotlin',
87 vue: 'vue',
88 css: 'css',
89 html: 'html',
90 yml: 'yaml',
91 yaml: 'yaml',
92 sql: 'sql',
93}
94
95export function clip(text: string, max = MAX_TEXT): string {
96 return text.length > max ? `${text.slice(0, max)}\n... (+${text.length - max} chars)` : text
97}
98
99export function formatSize(bytes: number): string {
100 if (bytes < 1024) return `${bytes} B`
101 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
102
103 return `${(bytes / 1024 / 1024).toFixed(1)} MB`
104}
105
106export function formatTime(iso?: string): string {
107 return iso ? new Date(iso).toLocaleTimeString('en-GB', { hour12: false }) : ''
108}
109
110export function formatDuration(ms: number | null): string {
111 if (ms === null) return 'running'
112 if (ms < 1000) return `${ms} ms`
113 if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`
114
115 return `${Math.floor(ms / 60_000)} m ${Math.round((ms % 60_000) / 1000)} s`
116}
117
118export function formatCount(count: number): string {
119 return count >= 1000 ? `${(count / 1000).toFixed(1)}k` : String(count)
120}
121
122export function meter(percent: number, width = 20): string {
123 const filled = Math.round((Math.min(100, Math.max(0, percent)) / 100) * width)
124
125 return '█'.repeat(filled) + '░'.repeat(width - filled)
126}
127
128export function previewLines(text: string, count: number): string[] {
129 const lines = text.split('\n').filter(line => line.trim() !== '')
130
131 return Array.from({ length: count }, (_, index) => lines[index] ?? '')
132}
133
134export function languageOf(path: string): string {
135 return LANGUAGES[path.split('.').pop()?.toLowerCase() ?? ''] ?? ''
136}
137
138function textOf(content: unknown): string {
139 if (typeof content === 'string') return content
140 if (Array.isArray(content)) {
141 return content.map(part => (typeof part === 'object' && part && 'text' in part ? String(part.text) : '')).join('\n')
142 }
143
144 return content === undefined ? '' : JSON.stringify(content)
145}
146
147function editDiff(path: string, before: string, after: string): string {
148 const removed = before.split('\n').map(line => `-${line}`)
149 const added = after.split('\n').map(line => `+${line}`)
150
151 return [`--- ${path}`, `+++ ${path}`, `@@ -1,${removed.length} +1,${added.length} @@`, ...removed, ...added].join('\n')
152}
153
154export function describeTool(name: string, input: Record<string, unknown>): Pick<ToolCall, 'summary' | 'source' | 'language' | 'format'> {
155 const text = (key: string) => (typeof input[key] === 'string' ? (input[key] as string) : '')
156 const path = text('file_path')
157
158 if (name === 'Bash') return { summary: text('description'), source: clip(text('command')), language: 'sh', format: 'source' }
159 if (name === 'Edit' && path) {
160 return { summary: path, source: clip(editDiff(path, text('old_string'), text('new_string'))), language: languageOf(path), format: 'diff' }
161 }
162 if (name === 'Write' && path) return { summary: path, source: clip(text('content')), language: languageOf(path), format: 'source' }
163 if (name === 'Read' && path) return { summary: path, source: path, language: '', format: 'source' }
164
165 return { summary: '', source: clip(JSON.stringify(input, null, 2)), language: 'json', format: 'source' }
166}
167
168function addFileVersion(versions: Record<string, FileVersion[]>, path: string, backup: Backup) {
169 const list = (versions[path] ??= [])
170 if (list.some(one => one.version === backup.version)) return
171 list.push({ backupFileName: backup.backupFileName, version: backup.version, time: backup.backupTime })
172 list.sort((a, b) => a.version - b.version)
173}
174
175export function parseTranscript(jsonl: string): Transcript {
176 const rows: Row[] = jsonl
177 .split('\n')
178 .filter(Boolean)
179 .flatMap(line => {
180 try {
181 return [JSON.parse(line) as Row]
182 } catch {
183 return []
184 }
185 })
186
187 const seenRequests = new Set<string>()
188 const meta: SessionMeta = { title: '', branch: '', permissionMode: '', effort: '', versions: [] }
189 const toolCalls = new Map<string, ToolCall>()
190 const turnSeconds: number[] = []
191 const requests: RequestStats[] = []
192 const toolCounts: Record<string, number> = {}
193 const fileVersions: Record<string, FileVersion[]> = {}
194 let prompts = 0
195 let outputTokens = 0
196
197 for (const row of rows) {
198 const content = row.message?.content
199 if (row.aiTitle) meta.title = row.aiTitle
200 if (row.permissionMode) meta.permissionMode = row.permissionMode
201 if (row.gitBranch) meta.branch = row.gitBranch
202 if (row.effort) meta.effort = row.effort
203 if (row.version && meta.versions.at(-1) !== row.version) meta.versions.push(row.version)
204
205 if (row.type === 'file-history-snapshot') {
206 for (const [path, backup] of Object.entries(row.snapshot?.trackedFileBackups ?? {})) addFileVersion(fileVersions, path, backup)
207 } else if (row.type === 'file-history-delta' && row.trackingPath && row.backup) {
208 addFileVersion(fileVersions, row.trackingPath, row.backup)
209 } else if (row.type === 'user' && typeof content === 'string') {
210 prompts++
211 } else if (row.type === 'user' && Array.isArray(content)) {
212 for (const block of content) {
213 const call = block.type === 'tool_result' ? toolCalls.get(block.tool_use_id ?? '') : undefined
214 if (!call) continue
215 call.result = clip(textOf(block.content))
216 call.isError = block.is_error === true
217 call.durationMs = row.timestamp && call.startedAt ? Math.max(0, Date.parse(row.timestamp) - Date.parse(call.startedAt)) : null
218 }
219 } else if (row.type === 'assistant' && Array.isArray(content)) {
220 if (!row.requestId || !seenRequests.has(row.requestId)) {
221 if (row.requestId) seenRequests.add(row.requestId)
222 const usage = row.message?.usage
223 outputTokens += usage?.output_tokens ?? 0
224 requests.push({
225 time: formatTime(row.timestamp),
226 model: row.message?.model ?? '',
227 input: usage?.input_tokens ?? 0,
228 output: usage?.output_tokens ?? 0,
229 cacheRead: usage?.cache_read_input_tokens ?? 0,
230 cacheWrite: usage?.cache_creation_input_tokens ?? 0,
231 })
232 }
233 for (const block of content) {
234 if (block.type !== 'tool_use' || !block.id) continue
235 const name = block.name ?? 'tool'
236 toolCounts[name] = (toolCounts[name] ?? 0) + 1
237 toolCalls.set(block.id, {
238 id: block.id,
239 name,
240 startedAt: row.timestamp ?? '',
241 durationMs: null,
242 result: '',
243 isError: null,
244 ...describeTool(name, block.input ?? {}),
245 })
246 }
247 } else if (row.type === 'system' && row.subtype === 'turn_duration' && row.durationMs !== undefined) {
248 turnSeconds.push(row.durationMs / 1000)
249 }
250 }
251
252 return {
253 rows: rows.length,
254 prompts,
255 outputTokens,
256 meta,
257 toolCalls: [...toolCalls.values()],
258 turnSeconds,
259 requests,
260 toolCounts,
261 fileVersions,
262 }
263}
264
265export function cacheHitRate(requests: RequestStats[]): number {
266 const read = requests.reduce((sum, one) => sum + one.cacheRead, 0)
267 const total = requests.reduce((sum, one) => sum + one.input + one.cacheRead + one.cacheWrite, 0)
268
269 return total === 0 ? 0 : (read / total) * 100
270}
271
272export type GitFile = { code: string; path: string; added: number; removed: number }
273
274export type GitStatus = { root: string; branch: string; files: GitFile[] }
275
276export function parseGitStatus(root: string, porcelain: string, numstat: string): GitStatus {
277 const counts = new Map<string, { added: number; removed: number }>()
278 for (const line of numstat.split('\n').filter(Boolean)) {
279 const [added = '0', removed = '0', path = ''] = line.split('\t')
280 counts.set(path, { added: Number(added) || 0, removed: Number(removed) || 0 })
281 }
282 const lines = porcelain.split('\n').filter(Boolean)
283 const branch = lines[0]?.startsWith('## ') ? lines.shift()!.slice(3) : ''
284 const files = lines.map(line => {
285 const code = line.slice(0, 2).trim() || '?'
286 const path = line.slice(3).split(' -> ').pop() ?? ''
287
288 return { code, path, ...(counts.get(path) ?? { added: 0, removed: 0 }) }
289 })
290
291 return { root, branch, files }
292}
293
294export function diffCounts(diff: string): { added: number; removed: number } {
295 const lines = diff.split('\n').filter(line => !line.startsWith('+++') && !line.startsWith('---'))
296
297 return {
298 added: lines.filter(line => line.startsWith('+')).length,
299 removed: lines.filter(line => line.startsWith('-')).length,
300 }
301}
302types/index.d.ts 37 lines1export type SessionTab = 'usage' | 'tools' | 'changes' | 'activity' | 'files' | 'stats' | 'help'
2
3export type SessionPaths = {
4 id: string
5 cwd: string
6 transcript: string
7 env: string
8 tmp: string
9 fileHistory: string
10}
11
12export type SessionDiff = { path: string; text: string; against: string }
13
14export type SessionGit = {
15 root: string
16 branch: string
17 files: { code: string; path: string; added: number; removed: number }[]
18}
19
20declare module 'claude-code' {
21 interface PluginState {
22 'session-panel': {
23 tab: SessionTab
24 dir: string
25 tick: number
26 offset: number
27 isErrorsOnly: boolean
28 selectedTool: string | null
29 listOffset: number
30 diff: SessionDiff | null
31 git: SessionGit | null
32 paths: SessionPaths | null
33 agentView: { id: string; label: string } | null
34 }
35 }
36}
37