Review what each round changed: the files Claude touched, their diffs (shell commands included), and one key to open a change in VS Code.

See exactly what Claude changed, round by round, without leaving Claude Code.
Every file it touched, every diff (shell commands included), one key to open the change in VS Code.

Claude can change a dozen files in one reply, some with the Edit tool and some through a shell command like sed -i, git mv or a code generator. The transcript shows them as they scroll past, and git diff shows everything mixed together. Round Changes keeps each round (one prompt and Claude's reply) as its own change set, so you can review what that prompt did, step back to an earlier one, and jump straight to the line in your editor.
p and n.In Claude Code:
/plugin install round-changes --marketplace joaofatoretto/round-changes
Answer y to add the marketplace and choose a scope (user makes it available in every session). It starts working at once, with no restart and no configuration.
From a terminal:
claude plugin marketplace add joaofatoretto/round-changes
claude plugin install round-changes@round-changes --scope user
From a local clone, for one session:
git clone https://github.com/joaofatoretto/round-changes.git
claude --plugin-dir ./round-changes
Remove it with claude plugin uninstall round-changes@round-changes.
Work with Claude as usual. When a round changes files, three ways in appear:
| Where | What you see | What it opens |
|---|---|---|
| End of the round, on the "✻ Worked for…" line | 3 files +7 −6 [ view ] | That round |
| Prompt footer, right side | 3 files +7 −6 | The latest round |
| Anywhere | /changes | The latest round |

The viewer has two screens. The round lists every file it changed:
M, NEW or DEL, with green and red line counts.A file shows its diff, one section per edit:

Shell commands are diffed the same way, with the command that made the change shown above it:

The viewer takes the keyboard when it opens. Click it, or press ctrl+x then tab, to give it back the keys later.
| On the round | |
|---|---|
1–9 | Open that file's diff (or click its row) |
a | Audit the round in VS Code |
f | Open the project in File Explorer |
p / n | Older / newer round |
esc | Close |
| On a file | |
|---|---|
o | Open in VS Code at the changed line |
t | Find the change in the chat |
f | Show the file in File Explorer (its folder, if it was deleted) |
p / n | Previous / next file in the round |
g / e | Jump to the top / bottom of a long diff |
↑ ↓ | Scroll |
b or esc | Back to the round |

Claude Code docks panels on the right only in its fullscreen layout at 110 columns or more. A mod can't change that.
The Edit and Write tools report exactly what they changed. A shell command doesn't, so in a git repo Round Changes takes two snapshots of the work tree around each shell command and diffs them:
git add -A and git write-tree into a private index, .git/round-changes.index. It's seeded from your real index, so each snapshot only re-reads the files that changed, and it takes milliseconds.git diff between the two trees.Your files and git state are safe: your working files, staging area, branches and history are never touched.
What the snapshots see:
.gitignore..git/objects as unreferenced objects, which git gc removes in its normal cleanup.Outside a git repo, shell commands can't be diffed. The round says so in yellow ("no git"), so you know the list may be incomplete.
Round Changes makes no network requests and calls no model.
| When | Command |
|---|---|
| Shell commands, until a repo is found | git rev-parse to find the repo. cp seeds the private index, once. |
| Around each shell command | git add -A and git write-tree with the private index, then git diff between the two snapshots |
| When you press Open in VS Code | code -r -g <file>:<line> |
| When you press Audit in VS Code | code <project> -g <file>:<line> … (up to 25 files) |
| Once, at session start | uname -s, to pick the file manager (skipped on WSL, found from WSL_DISTRO_NAME) |
| When you press Open in File Explorer | WSL: wslpath -w, then explorer.exe /select,<file> or explorer.exe <project>. macOS: open -R <file> or open <project>. Linux: xdg-open <folder> |
Rounds live in the session's memory and end with it. When the mod loads in a session that's already running, it rebuilds earlier rounds from the transcript.
code command on your PATH, for Open in VS Code. In VS Code, run Shell Command: Install 'code' command in PATH. On WSL it works out of the box.xdg-open starts on Linux.o to see the rest in VS Code./changes still work.round-changes/
├── .claude-plugin/
│ ├── plugin.json # the mod's manifest
│ └── marketplace.json # makes this repo installable with /plugin install
├── hooks/
│ ├── hooks.json # points Claude Code at register.tsx
│ ├── register.tsx # the hooks: recording, snapshots, the chips and the viewer
│ ├── model.ts # pure logic: rounds, diff parsing, layout math
│ └── register.test.ts # tests, run inside Claude Code's own engine
├── types/index.d.ts # the mod's state, typed
└── screenshots/
claude plugin validate . # check the manifest and hooks the way Claude Code loads them
claude plugin test . # run the tests
claude --plugin-dir . # try your changes in a session
Claude Code writes the mod's TypeScript types to .claude-plugin/types/ when it loads the mod, so tsc -p . type-checks it from then on.
Issues and pull requests are welcome.
MIT © joaofatoretto
Built with Claude Code. Not an official Anthropic product. Visual Studio Code is a trademark of Microsoft Corporation, and Git is a trademark of Software Freedom Conservancy. Their names are used here only to describe what the mod works with.
hooks/register.tsx 969 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, ToolCallInput, ToolCallResult } from 'claude-code'
3
4import type { Change, Desktop, FileTouch, Live, Round, View } from '../types'
5import {
6 FILE_MANAGER,
7 auditCommand,
8 clock,
9 diffScreenRows,
10 diffSource,
11 displayPath,
12 duration,
13 fileRowLabel,
14 fileStats,
15 fitButtons,
16 fitFor,
17 fromToolRecord,
18 makeChange,
19 parseGitDiff,
20 keepStart,
21 promptLine,
22 recordChange,
23 revealCommand,
24 roundButtons,
25 roundForDuration,
26 countShell,
27 roundStats,
28 roundsFromTranscript,
29 shortDir,
30 shownFile,
31 shownRound,
32 sizeBar,
33 splitPath,
34 summaryText,
35 stepFile,
36 stepRound,
37 shellWarning,
38 viewKey,
39 wantedRows,
40 wrapLines,
41} from './model'
42
43const PANE = 'round-changes'
44const TITLE = 'Changes'
45const EDITOR = 'code'
46/** The docked viewer's width: room for a diff, most of the row left to the chat. */
47const DOCK_COLUMNS = 52
48
49const rounds = atom({ plugin: 'round-changes', key: 'rounds' } as const, [])
50const live = atom({ plugin: 'round-changes', key: 'live' } as const, null)
51const turns = atom({ plugin: 'round-changes', key: 'turns' } as const, 0)
52const view = atom({ plugin: 'round-changes', key: 'view' } as const, { roundId: null, file: null, screen: 'round' })
53const cwd = atom({ plugin: 'round-changes', key: 'cwd' } as const, '')
54const home = atom({ plugin: 'round-changes', key: 'home' } as const, '')
55const scroll = atom({ plugin: 'round-changes', key: 'scroll' } as const, null)
56const desktop = atom({ plugin: 'round-changes', key: 'desktop' } as const, null)
57
58/** Git's colors for added and removed lines, as GitHub draws them. */
59const ADDED = '#3fb950'
60const REMOVED = '#f85149'
61
62const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`
63
64// ── Recording ─────────────────────────────────────────────────────────
65
66/** The round a change lands in: the running turn, else background work after the last one. */
67async function currentRound($: EngineInterface): Promise<Live> {
68 const running = await read($, live)
69 if (running) return running
70 const turn = await read($, turns)
71 return {
72 id: `after-${turn}`,
73 turn,
74 prompt: `(background work after turn ${turn})`,
75 startedAt: await $.clock.now(),
76 shellCommands: 0,
77 }
78}
79
80async function record($: EngineInterface, path: string, kind: FileTouch['kind'], change: Change) {
81 const into = await currentRound($)
82 await update($, rounds, list => recordChange(list, into, path, kind, change))
83}
84
85/** With nothing recorded yet (a fresh load mid-session), rebuilds the rounds from the transcript. */
86async function backfill($: EngineInterface) {
87 if ((await read($, rounds)).length > 0) return
88 const found = roundsFromTranscript(await $.session.messages())
89 if (found.rounds.length === 0) return
90 await update($, rounds, list => (list.length > 0 ? list : found.rounds))
91 await update($, turns, n => Math.max(n, found.turns))
92}
93
94async function recordFileTool<E extends ToolCallInput, R extends ToolCallResult>(
95 $: EngineInterface,
96 e: E,
97 next: (e: E) => Promise<R>,
98): Promise<R> {
99 const ran = await next(e)
100 if (ran.deny !== undefined || ran.isError) return ran
101 const found = fromToolRecord(e.tool, e.tool_use_id, ran.result, e.agentId)
102 if (found) await record($, found.path, found.kind, found.change)
103 return ran
104}
105
106// ── Shell commands, through git ─────────────────────────────────────
107
108/**
109 * Snapshots of a git work tree, to see what a shell command changed: the tree
110 * before and after, each written with `git add -A` into a private index inside
111 * `.git` (never the person's staging area), then diffed.
112 */
113type Repo = { top: string; index: string }
114
115const QUICK = { timeoutMs: 10_000 }
116
117/** The repo the session works in, or null outside one. */
118async function findRepo($: EngineInterface, cwd: string): Promise<Repo | null> {
119 const found = await $.process.run(['git', 'rev-parse', '--show-toplevel', '--absolute-git-dir'], { cwd, ...QUICK })
120 if (found.exitCode !== 0) return null
121 const [top, gitDir] = found.stdout.trim().split('\n')
122 if (!top || !gitDir) return null
123 const index = `${gitDir}/round-changes.index`
124 // Seeded from the real index, so its stat cache is warm and the first snapshot is quick.
125 await $.process.run(['sh', '-c', '[ -f "$1" ] || cp "$2/index" "$1" 2>/dev/null || true', 'sh', index, gitDir], QUICK)
126 return { top, index }
127}
128
129/** The work tree as a tree id, untracked files included, ignored ones not. */
130async function snapshot($: EngineInterface, repo: Repo): Promise<string | undefined> {
131 const ran = await $.process.run(['sh', '-c', 'git add -A . >/dev/null 2>&1; git write-tree'], {
132 cwd: repo.top,
133 env: { GIT_INDEX_FILE: repo.index },
134 ...QUICK,
135 })
136 const tree = ran.stdout.trim()
137 return ran.exitCode === 0 && /^[0-9a-f]{40,64}$/.test(tree) ? tree : undefined
138}
139
140/** The unified diff between two snapshots. */
141async function diffTrees($: EngineInterface, repo: Repo, before: string, after: string): Promise<string> {
142 const ran = await $.process.run(
143 ['git', '-c', 'core.quotepath=false', 'diff', '--no-color', '--no-ext-diff', '--no-renames', '-U3', before, after],
144 { cwd: repo.top, ...QUICK },
145 )
146 return ran.exitCode === 0 ? ran.stdout : ''
147}
148
149// Repos found, by the folder the session ran in. A miss is not kept, so a `git init`
150// or a move into a repo mid-session is seen at the next command; snapshots run one at
151// a time, as they share an index.
152const repos = new Map<string, Repo>()
153let queue: Promise<unknown> = Promise.resolve()
154
155async function repoFor($: EngineInterface): Promise<Repo | null> {
156 try {
157 const dir = await $.session.cwd()
158 const known = repos.get(dir)
159 if (known) return known
160 const found = await findRepo($, dir)
161 if (found) repos.set(dir, found)
162 return found
163 } catch {
164 return null
165 }
166}
167
168/** Drops a repo whose snapshot failed (moved, renamed, removed), so the next command looks again. */
169function forgetRepo(repo: Repo) {
170 for (const [dir, known] of repos) if (known === repo) repos.delete(dir)
171}
172
173function oneAtATime<T>(work: () => Promise<T>): Promise<T> {
174 const run = queue.then(work, work)
175 queue = run.catch(() => undefined)
176 return run
177}
178
179/** Records what a shell command changed in the repo, file by file. */
180async function recordShell($: EngineInterface, repo: Repo, before: string, e: { tool_use_id: string; agentId?: string; command: string }) {
181 const after = await oneAtATime(() => snapshot($, repo))
182 if (!after || after === before) return
183 const files = parseGitDiff(await diffTrees($, repo, before, after))
184 for (const f of files) {
185 const note = f.isBinary ? 'Binary file: no text diff to show.' : f.hunks.length === 0 ? 'Mode or empty-file change.' : undefined
186 const change = makeChange(
187 { toolUseId: e.tool_use_id, tool: 'Bash', agentId: e.agentId, command: e.command.slice(0, 300), note },
188 f.hunks,
189 )
190 await record($, `${repo.top}/${f.path}`, f.kind, change)
191 }
192}
193
194/** The tool.call hooks only watch: if one fails, the call's own result stands. */
195function passThrough<E, R>($: unknown, e: E, next: (e: E) => R): R {
196 return next(e)
197}
198
199// ── The viewer ────────────────────────────────────────────────────────
200
201/** Opens the viewer on `next`, or moves it there, as tall as what it shows needs. */
202async function show($: EngineInterface, next: View) {
203 await update($, view, () => next)
204 const list = await read($, rounds)
205 const round = shownRound(list, next)
206 const rows = Math.min(40, Math.max(6, wantedRows(round, shownFile(round, next), next.screen, undefined, await desktopFor($))))
207 // Docked (fullscreen, 110+ columns) it takes a slim column on the right; inline, the rows it needs.
208 return $.ui.open({ id: PANE, title: TITLE, focus: true, closeOnEscape: true, rows, columns: DOCK_COLUMNS })
209}
210
211/** Opens a round: straight to the diff when it touched one file, else its overview. */
212async function showRound($: EngineInterface, roundId: string | null) {
213 const list = await read($, rounds)
214 const round = shownRound(list, { roundId, file: null, screen: 'round' })
215 const only = round?.files.length === 1 ? round.files[0] : undefined
216 return show($, { roundId, file: only?.path ?? null, screen: only ? 'file' : 'round' })
217}
218
219async function move($: EngineInterface, to: (list: readonly Round[], v: View) => View) {
220 const list = await read($, rounds)
221 await show($, to(list, await read($, view)))
222 try {
223 await $.ui.scroll({ in: PANE, to: 'start' })
224 } catch {}
225}
226
227async function scrollPane($: EngineInterface, to: 'start' | 'end') {
228 try {
229 await $.ui.scroll({ in: PANE, to })
230 } catch {}
231}
232
233async function openInEditor($: EngineInterface, path: string, line: number) {
234 const name = splitPath(path).name
235 try {
236 const ran = await $.process.run([EDITOR, '-r', '-g', `${path}:${line}`], { timeoutMs: 20_000 })
237 if (ran.exitCode === 0) $.ui.toast(`Opened ${name}:${line} in VS Code`, { timeoutMs: 2500 })
238 else {
239 const why = (ran.stderr || ran.stdout).trim().split('\n')[0] || `exit code ${ran.exitCode}`
240 $.ui.toast(`VS Code did not open ${name}: ${why}`)
241 }
242 } catch {
243 $.ui.toast(`Could not run \`${EDITOR}\`. Is the VS Code CLI on your PATH?`)
244 }
245}
246
247/** The project a round belongs to: the repo's top, else the folder the session runs in. */
248async function projectFolder($: EngineInterface) {
249 return (await repoFor($))?.top ?? (await $.session.cwd())
250}
251
252/** Opens the project in VS Code with the round's files, where the gutter marks what git sees changed. */
253async function auditInEditor($: EngineInterface, round: Round) {
254 const folder = await projectFolder($)
255 const { argv, opened, left } = auditCommand(EDITOR, folder, round.files)
256 try {
257 const ran = await $.process.run(argv, { timeoutMs: 20_000 })
258 if (ran.exitCode === 0) {
259 const more = left > 0 ? `; ${left} more in Source Control` : ''
260 $.ui.toast(`Opened ${splitPath(folder).name} with ${plural(opened, 'file')} in VS Code${more}`, { timeoutMs: 3000 })
261 } else {
262 const why = (ran.stderr || ran.stdout).trim().split('\n')[0] || `exit code ${ran.exitCode}`
263 $.ui.toast(`VS Code did not open the project: ${why}`)
264 }
265 } catch {
266 $.ui.toast(`Could not run \`${EDITOR}\`. Is the VS Code CLI on your PATH?`)
267 }
268}
269
270/** Where the session runs, found once: it picks the file manager and how paths reach it. */
271async function desktopFor($: EngineInterface): Promise<Desktop> {
272 const known = await read($, desktop)
273 if (known) return known
274 let found: Desktop
275 try {
276 const wsl = await $.env.get('WSL_DISTRO_NAME')
277 found = wsl ? 'wsl' : (await $.process.run(['uname', '-s'], QUICK)).stdout.trim() === 'Darwin' ? 'mac' : 'linux'
278 } catch {
279 // No `uname`: Windows itself.
280 found = 'windows'
281 }
282 await update($, desktop, () => found)
283 return found
284}
285
286/** Shows `path` in the file manager: a folder opened, a file selected in its folder. */
287async function openInFiles($: EngineInterface, path: string, isFolder: boolean) {
288 const where = await desktopFor($)
289 const fm = FILE_MANAGER[where]
290 const name = splitPath(path).name || path
291 try {
292 // File Explorer takes Windows paths: `\\wsl.localhost\…` for a file inside WSL.
293 const target = where === 'wsl' ? (await $.process.run(['wslpath', '-w', path], QUICK)).stdout.trim() : path
294 if (!target) {
295 $.ui.toast(`Could not find ${name} as a Windows path`)
296 return
297 }
298 const ran = await $.process.run(revealCommand(where, target, isFolder), { timeoutMs: 20_000 })
299 // File Explorer exits with 1 even when it opened.
300 if (ran.exitCode === 0 || fm.short === 'Explorer') $.ui.toast(`Opened ${name} in ${fm.name}`, { timeoutMs: 2500 })
301 else {
302 const why = (ran.stderr || ran.stdout).trim().split('\n')[0] || `exit code ${ran.exitCode}`
303 $.ui.toast(`The ${fm.name} did not open ${name}: ${why}`)
304 }
305 } catch {
306 $.ui.toast(`Could not open the ${fm.name}.`)
307 }
308}
309
310async function revealInChat($: EngineInterface, change: Change) {
311 if (change.agentId) {
312 $.ui.toast('A subagent made this change: it is in that agent’s transcript, not the main one.')
313 return
314 }
315 try {
316 const moved = await $.ui.scroll({ to: { requestId: change.toolUseId }, block: 'center' })
317 if (moved.deny) $.ui.toast(`Could not scroll the chat there: ${moved.deny}`)
318 } catch {
319 $.ui.toast('That change is no longer in the chat.')
320 }
321}
322
323export const register: Register = on => {
324 on('session.start', async ($, e, next) => {
325 const result = await next(e)
326 await $.command.register({
327 name: 'changes',
328 description: 'Review what the last round changed: files, diffs, open in VS Code or the file manager',
329 })
330 const root = await $.session.cwd()
331 await update($, cwd, () => root)
332 const homeDir = (await $.env.get('HOME')) ?? ''
333 await update($, home, () => homeDir)
334 await desktopFor($)
335 // The first version pinned a status line; the chips replace it.
336 $.ui.status(undefined)
337 await backfill($)
338 return result
339 })
340
341 on('command.run', { command: 'changes' }, async $ => {
342 const root = await $.session.cwd()
343 await update($, cwd, () => root)
344 await backfill($)
345 const opened = await showRound($, null)
346 if (!opened.isPlaced) return { text: `The changes viewer could not open: ${opened.reason}` }
347 return {}
348 })
349
350 // The window's moves, measured: the pills at its foot need the tree's true height.
351 on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
352 const moved = await next(e)
353 if (moved.deny !== undefined) return moved
354 const key = viewKey(await read($, rounds), await read($, view))
355 await update($, scroll, () => ({ key, contentRows: e.contentRows }))
356 return moved
357 })
358
359 // Esc on a file's diff steps back to the round; on the round it closes.
360 on('ui.close', async ($, e, next) => {
361 if (e.id !== PANE || e.origin.kind !== 'person') return next(e)
362 const v = await read($, view)
363 if (v.screen !== 'file') return next(e)
364 await show($, { ...v, screen: 'round' })
365 return { value: undefined }
366 })
367
368 on('turn.start', async ($, e, next) => {
369 const at = await $.clock.now()
370 const n = (await read($, turns)) + 1
371 await update($, turns, () => n)
372 await update($, live, () => ({ id: e.turnId, turn: n, prompt: e.text.slice(0, 400), startedAt: at, shellCommands: 0 }))
373 return next(e)
374 })
375
376 on('turn.complete', async ($, e, next) => {
377 if (e.agentId !== undefined) return next(e)
378 const at = await $.clock.now()
379 const ended = await read($, live)
380 if (ended)
381 await update($, rounds, list =>
382 list.map(r =>
383 r.id === ended.id ? { ...r, endedAt: at, durationMs: e.durationMs } : r,
384 ),
385 )
386 await update($, live, () => null)
387 return next(e)
388 })
389
390 on('tool.call', { tool: 'Edit' }, recordFileTool).catch(passThrough)
391 on('tool.call', { tool: 'Write' }, recordFileTool).catch(passThrough)
392 on('tool.call', { tool: 'NotebookEdit' }, recordFileTool).catch(passThrough)
393
394 // Shell commands: the work tree before and after, diffed. Outside a git repo they are only counted.
395 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
396 if (e.tool !== 'Bash') return next(e)
397 const repo = await repoFor($)
398 const before = repo ? await oneAtATime(() => snapshot($, repo)) : undefined
399 const ran = await next(e)
400 if (ran.deny !== undefined || ran.isReadOnly) return ran
401 if (repo && before) {
402 await recordShell($, repo, before, e)
403 return ran
404 }
405 // No snapshot: the round still shows, with a warning that files may have changed unseen.
406 if (repo) forgetRepo(repo)
407 const into = await currentRound($)
408 await update($, live, l => (l && l.id === into.id ? { ...l, shellCommands: l.shellCommands + 1 } : l))
409 await update($, rounds, list => countShell(list, into, repo === null))
410 return ran
411 }).catch(passThrough)
412
413 // ── Entry point 1: a chip on each round's "✻ Baked for 48s" line ──────
414 // The line is drawn whole here, the engine's words kept, so the chip never wraps it.
415 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
416 const round = roundForDuration(await read($, rounds), e.props.durationMs)
417 if (!round) return next(e)
418 const { Box, Text, Button } = $.ui.resolve(e)
419 const s = roundStats(round)
420 const columns = e.viewport?.columns ?? 80
421 const said = `✻ ${e.props.word} for ${duration(e.props.durationMs)}`
422 const counts = columns >= said.length + 34
423 return (
424 <Box flexDirection="row" gap={2}>
425 <Text key="said" dimColor>
426 {said}
427 </Text>
428 <Box key="chip" flexDirection="row" gap={1} flexShrink={0}>
429 {round.shellCommands > 0 && (
430 <Text key="warn" color="yellow">
431 {round.isOutsideRepo
432 ? s.files === 0 && counts ? 'no git: shell changes not tracked' : 'no git'
433 : s.files === 0 && counts ? 'shell changes not tracked' : 'untracked'}
434 </Text>
435 )}
436 {counts && s.files > 0 && <Text key="files">{plural(s.files, 'file')}</Text>}
437 {counts && s.added > 0 && <Text key="a" color={ADDED}>{`+${s.added}`}</Text>}
438 {counts && s.removed > 0 && <Text key="r" color={REMOVED}>{`−${s.removed}`}</Text>}
439 <Button key={`view:${round.id}`} onPress={() => showRound($, round.id)}>
440 {counts || s.files === 0 ? 'view' : `${s.files} · view`}
441 </Button>
442 </Box>
443 </Box>
444 )
445 })
446
447 // ── Entry point 2: the newest round in the prompt footer, one click from the viewer ──
448 // Drawn in the footer's mode slot at the right of the hint row: no row of its own.
449 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
450 const list = await read($, rounds)
451 const newest = list[list.length - 1]
452 if (!newest) return next(e)
453 const s = roundStats(newest)
454 const files = s.files > 0 ? plural(s.files, 'file') : 'shell changes'
455 const counts = [s.added > 0 && `+${s.added}`, s.removed > 0 && `−${s.removed}`].filter(Boolean).join(' ')
456 const noGit = newest.shellCommands > 0 ? (newest.isOutsideRepo ? 'no git ' : 'untracked ') : ''
457 // The engine moves this slot to a row of its own when the hint leaves it no room, so
458 // it drops the counts, then steps aside: the hint is about 52 columns, 71 while a turn runs.
459 const columns = e.viewport?.columns ?? 0
460 const modes = e.props.modes.length > 0 ? e.props.modes.join(' & ').length + 2 : 0
461 const free = columns - ((await read($, live)) ? 71 : 52) - modes - 4
462 const full = `${noGit}${files} ${counts}`.trim()
463 const short = `${noGit}${files}`.trim()
464 if (free < short.length) return next(e)
465 const withCounts = free >= full.length && counts !== ''
466 const { Box, Text, Button } = $.ui.resolve(e)
467 return (
468 <Box flexDirection="row" gap={2}>
469 {e.props.modes.length > 0 && (
470 <Text key="modes" dimColor>
471 {e.props.modes.join(' & ')}
472 </Text>
473 )}
474 <Box key="changes" flexDirection="row" gap={1}>
475 {noGit !== '' && (
476 <Text key="nogit" color="yellow">
477 {noGit.trim()}
478 </Text>
479 )}
480 {/* One Button for the whole of it, counts included: a label holds no colors, but every cell presses. */}
481 <Button key="footer-changes" plain dimColor onPress={() => showRound($, newest.id)}>
482 {withCounts ? `${files} ${counts}` : files}
483 </Button>
484 </Box>
485 </Box>
486 )
487 })
488
489 // ── The viewer itself ─────────────────────────────────────────────────
490 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
491 const { Box, Text, Button, Code } = $.ui.resolve(e)
492 const list = await read($, rounds)
493 const running = await read($, live)
494 const v = await read($, view)
495 const root = await read($, cwd)
496 const homeDir = await read($, home)
497 const where = (path: string) => displayPath(path, root, homeDir)
498 const width = Math.max(24, e.props.bodyColumns)
499 // The body is padded by one column at each side: what is drawn fits `room`.
500 const room = width - 2
501 const fit = fitFor(width)
502 const round = shownRound(list, v)
503 // Found at session start and before the viewer opens: drawing can't store it.
504 const desk = (await read($, desktop)) ?? 'linux'
505 const fm = FILE_MANAGER[desk]
506
507 /** A file's kind as a 3-cell chip: A added, M modified, D deleted. */
508 const kindBadge = (kind: FileTouch['kind']) => (
509 <Text key="badge" bold color="inverseText" backgroundColor={kind === 'deleted' ? 'error' : kind === 'added' ? 'success' : 'warning'}>
510 {kind === 'deleted' ? ' D ' : kind === 'added' ? ' A ' : ' M '}
511 </Text>
512 )
513
514 /**
515 * Pills at the window's foot, as the chat's own: to the top once scrolled down, to the
516 * bottom while there is more below. `estimate` stands in for the tree's height until
517 * the window has moved on this screen and the engine has said it.
518 */
519 const measured = await read($, scroll)
520 const here = viewKey(list, v)
521 const known = measured?.key === here ? measured : undefined
522 const treeRows = (estimate: number) => known?.contentRows ?? estimate
523 const pills = (estimate: number) => {
524 const { bodyRows } = e.props.scroll
525 const total = treeRows(estimate)
526 const { offset } = e.props.scroll
527 const canTop = offset > 0
528 const canBottom = offset + bodyRows < total
529 if (!canTop && !canBottom) return null
530 const short = fit === 'narrow'
531 return (
532 <Box key="pills" position="absolute" top={offset + bodyRows - 1} right={1} flexDirection="row" gap={1}>
533 {canTop && (
534 <Button key="top" hotkey="g" variant="primary" onPress={() => scrollPane($, 'start')}>
535 {short ? '⤒' : '⤒ top'}
536 </Button>
537 )}
538 {canBottom && (
539 <Button key="bottom" hotkey="e" variant="primary" onPress={() => scrollPane($, 'end')}>
540 {short ? '⤓' : '⤓ bottom'}
541 </Button>
542 )}
543 </Box>
544 )
545 }
546 // A tree taller than its window ends in a blank row, under the pills at its foot.
547 const scrolls = (estimate: number) => treeRows(estimate) > e.props.scroll.bodyRows
548
549 /** The key hints at the foot: key in the accent, what it does dim, wrapping instead of cutting. */
550 const hints = (pairs: readonly (readonly [string, string])[]) => (
551 <Box key="hints" flexDirection="row" flexWrap="wrap" columnGap={2} marginTop={1} width={room}>
552 {pairs.map(([key, label]) => (
553 <Box key={`hint:${key}`} flexDirection="row" gap={1}>
554 <Text key="key" bold color="claude">
555 {key}
556 </Text>
557 <Text key="label" dimColor>
558 {label}
559 </Text>
560 </Box>
561 ))}
562 </Box>
563 )
564
565 if (!round) {
566 return (
567 <Box flexDirection="column" paddingX={1} paddingY={1} width={width}>
568 <Text key="title" bold>
569 No changes yet
570 </Text>
571 <Box key="about" marginTop={1}>
572 <Text key="hint" dimColor wrap="wrap">
573 When Claude edits, creates or deletes files, each round appears here with its diffs.
574 </Text>
575 </Box>
576 {running && (
577 <Box key="running" marginTop={1}>
578 <Text key="live" color="claude">
579 {`● Turn ${running.turn} is running`}
580 </Text>
581 </Box>
582 )}
583 </Box>
584 )
585 }
586
587 const index = list.indexOf(round)
588 const isLive = running?.id === round.id
589 const stats = roundStats(round)
590 const file = v.screen === 'file' ? shownFile(round, v) : undefined
591
592 // ── Screen 2: one file's diff ───────────────────────────────────
593 if (file) {
594 const at = round.files.indexOf(file)
595 const { dir, name } = splitPath(where(file.path))
596 const fs = fileStats(file)
597 const isNew = file.kind === 'added'
598 const isGone = file.kind === 'deleted'
599 const canReveal = file.changes.some(c => !c.agentId)
600 const many = round.files.length > 1
601
602 // Row 1: back at the left, the walk between the round's files at the right.
603 const nav = (
604 <Box key="nav" flexDirection="row" justifyContent="space-between" width={room}>
605 <Button key="back" plain hotkey="b" dimColor onPress={() => move($, (_, w) => ({ ...w, screen: 'round' }))}>
606 ◀ Back
607 </Button>
608 {many && (
609 <Box key="files-nav" flexDirection="row" gap={1} flexShrink={0}>
610 <Button key="prev-file" plain hotkey="p" dimColor onPress={() => move($, (l, w) => stepFile(l, w, -1))}>
611 ◀
612 </Button>
613 <Text key="pos" dimColor>{`${at + 1}/${round.files.length}`}</Text>
614 <Button key="next-file" plain hotkey="n" dimColor onPress={() => move($, (l, w) => stepFile(l, w, 1))}>
615 ▶
616 </Button>
617 </Box>
618 )}
619 </Box>
620 )
621
622 // What the file is, how much changed, and where it lives.
623 const title = (
624 <Box key="title" flexDirection="column" marginTop={1} width={room}>
625 <Box key="what" flexDirection="row" justifyContent="space-between" gap={1} width={room}>
626 <Box key="who" flexDirection="row" gap={1} flexShrink={1} overflow="hidden">
627 {kindBadge(file.kind)}
628 <Text key="name" bold wrap="truncate-end">
629 {name}
630 </Text>
631 </Box>
632 <Box key="counts" flexDirection="row" gap={1} flexShrink={0}>
633 {fs.added > 0 && <Text key="a" color={ADDED}>{`+${fs.added}`}</Text>}
634 {fs.removed > 0 && <Text key="r" color={REMOVED}>{`−${fs.removed}`}</Text>}
635 </Box>
636 </Box>
637 {dir !== '' && (
638 <Box key="where" paddingLeft={4}>
639 <Text key="dir" dimColor wrap="truncate-start">
640 {shortDir(dir, room - 4)}
641 </Text>
642 </Box>
643 )}
644 </Box>
645 )
646
647 // The things to do with the file. A deleted one shows its folder in the file manager.
648 const labels = fitButtons(room, {
649 ...(isGone ? {} : { open: ['Open in VS Code', 'VS Code'] as const }),
650 ...(canReveal ? { chat: ['Find in chat', 'chat'] as const } : {}),
651 files: [`Open in ${fm.name}`, fm.short],
652 })
653 const actions = (
654 <Box key="actions" flexDirection="row" gap={2} marginTop={1} width={room}>
655 {!isGone && (
656 <Button key="open" hotkey="o" variant="primary" onPress={() => openInEditor($, file.path, file.changes[0]?.line ?? 1)}>
657 {labels.open}
658 </Button>
659 )}
660 {canReveal && (
661 <Button
662 key="reveal"
663 hotkey="t"
664 onPress={() => {
665 const first = file.changes.find(c => !c.agentId)
666 if (first) void revealInChat($, first)
667 }}
668 >
669 {labels.chat}
670 </Button>
671 )}
672 <Button
673 key="files"
674 hotkey="f"
675 onPress={() => (isGone ? openInFiles($, splitPath(file.path).dir, true) : openInFiles($, file.path, false))}
676 >
677 {labels.files}
678 </Button>
679 </Box>
680 )
681
682 const edits = file.changes.map((c, ci) => {
683 const what =
684 c.tool === 'Bash'
685 ? 'Shell'
686 : c.tool === 'Write'
687 ? isNew && ci === 0
688 ? 'Created'
689 : 'Rewritten'
690 : 'Edit'
691 const several = file.changes.length > 1
692 const label = several ? `${what} ${ci + 1} of ${file.changes.length}` : what
693 const line = `· line ${c.line}`
694 const agent = fit !== 'narrow' && c.agentId ? '· subagent' : ''
695 const hasOpen = several && !isGone
696 const hasChat = several && !c.agentId && fit !== 'narrow'
697 const buttonsWidth = (hasOpen ? 6 : 0) + (hasChat ? 6 : 0) + (hasOpen && hasChat ? 2 : 0)
698 // The rule runs from the label to the buttons (or the edge), one space between each part.
699 const parts = [2, label.length, line.length, ...(agent ? [agent.length] : []), ...(buttonsWidth > 0 ? [buttonsWidth] : [])]
700 // One cell spare: a rule that fills the row exactly is cut with an ellipsis.
701 const fill = room - parts.reduce((n, p) => n + p, 0) - parts.length - 1
702 return (
703 <Box key={`edit:${ci}`} flexDirection="column" marginTop={1} width={room}>
704 <Box key="head" flexDirection="row" gap={1} width={room}>
705 <Text key="lead" dimColor>
706 ──
707 </Text>
708 <Text key="label" bold>
709 {label}
710 </Text>
711 <Text key="line" dimColor>
712 {line}
713 </Text>
714 {agent !== '' && (
715 <Text key="agent" dimColor>
716 {agent}
717 </Text>
718 )}
719 {fill > 0 && (
720 <Box key="rule" flexGrow={1} flexShrink={1} overflow="hidden">
721 <Text key="dashes" dimColor wrap="truncate-end">
722 {'─'.repeat(fill)}
723 </Text>
724 </Box>
725 )}
726 {buttonsWidth > 0 && (
727 <Box key="go" flexDirection="row" gap={2} flexShrink={0}>
728 {hasOpen && (
729 <Button key={`open:${ci}`} plain dimColor onPress={() => openInEditor($, file.path, c.line)}>
730 ↗ open
731 </Button>
732 )}
733 {hasChat && (
734 <Button key={`reveal:${ci}`} plain dimColor onPress={() => revealInChat($, c)}>
735 ⌖ chat
736 </Button>
737 )}
738 </Box>
739 )}
740 </Box>
741 {!!c.command && (
742 <Text key="cmd" dimColor wrap="truncate-end">
743 {` $ ${c.command.replace(/\s+/g, ' ')}`}
744 </Text>
745 )}
746 {c.hunks.length > 0 && (
747 <Code key="diff" format="diff" source={diffSource(c.hunks)} path={file.path} language={c.language} />
748 )}
749 {!!c.note && (
750 <Text key="note" dimColor italic>
751 {c.note}
752 </Text>
753 )}
754 {c.isTruncated && (
755 <Text key="cut" dimColor italic>
756 … longer than shown: press o to see it all in VS Code
757 </Text>
758 )}
759 </Box>
760 )
761 })
762
763 const estimate = diffScreenRows(file, width, dir !== '')
764
765 return (
766 <Box flexDirection="column" paddingX={1} paddingBottom={scrolls(estimate) ? 1 : 0} width={width}>
767 {nav}
768 {title}
769 {actions}
770 {edits}
771 {hints([
772 ...(!isGone ? [['o', 'open'] as const] : []),
773 ...(canReveal ? [['t', 'chat'] as const] : []),
774 ['f', 'files'],
775 ...(many ? [['p/n', 'file'] as const] : []),
776 ...(scrolls(estimate) ? [['g/e', 'top/end'] as const] : []),
777 ['esc', 'back'],
778 ])}
779 {pills(estimate)}
780 </Box>
781 )
782 }
783
784 // ── Screen 1: the round's overview ──────────────────────────────
785 // Row 1: older ◀ which round ▶ newer.
786 const isLatest = index === list.length - 1
787 const nav = (
788 <Box key="nav" flexDirection="row" justifyContent="space-between" width={room}>
789 {index > 0 ? (
790 <Button key="older" plain hotkey="p" onPress={() => move($, (l, w) => stepRound(l, w, -1))}>
791 ◀
792 </Button>
793 ) : (
794 <Text key="older-off" dimColor>
795 {' ◀'}
796 </Text>
797 )}
798 <Box key="where" flexDirection="row" gap={1}>
799 <Text key="round" bold color="claude">
800 {`Round ${index + 1} of ${list.length}`}
801 </Text>
802 {isLive ? (
803 <Text key="tag" color="claude">
804 ● working
805 </Text>
806 ) : (
807 isLatest && (
808 <Text key="tag" dimColor>
809 latest
810 </Text>
811 )
812 )}
813 </Box>
814 {index < list.length - 1 ? (
815 <Button key="newer" plain hotkey="n" onPress={() => move($, (l, w) => stepRound(l, w, 1))}>
816 ▶
817 </Button>
818 ) : (
819 <Text key="newer-off" dimColor>
820 {'▶ '}
821 </Text>
822 )}
823 </Box>
824 )
825
826 // The prompt, up to two lines behind an accent bar; under it, which turn, how long, when.
827 const meta = [
828 `turn ${round.turn}`,
829 round.durationMs ? duration(round.durationMs) : '',
830 round.startedAt > 0 ? clock(round.startedAt) : 'earlier',
831 ]
832 .filter(Boolean)
833 .join(' · ')
834 const prompt = (
835 <Box key="prompt" flexDirection="column" marginTop={1} width={room}>
836 {wrapLines(promptLine(round.prompt), room - 2, 2).map((line, i) => (
837 <Box key={`prompt:${i}`} flexDirection="row" gap={1}>
838 <Text key="bar" color="claude">
839 ▎
840 </Text>
841 <Text key="text" italic wrap="truncate-end">
842 {line}
843 </Text>
844 </Box>
845 ))}
846 {fit !== 'narrow' && (
847 <Box key="meta" paddingLeft={2}>
848 <Text key="text" dimColor>
849 {meta}
850 </Text>
851 </Box>
852 )}
853 </Box>
854 )
855
856 // The round as a whole, in the editor (every file it left in place, beside git's markers)
857 // and the project in the file manager. At the right end of the summary line, or under it.
858 const buttons = roundButtons(round, width, desk)
859 const canAudit = buttons.audit !== undefined
860 const projectButtons = (
861 <Box key="buttons" flexDirection="row" gap={2} flexShrink={0}>
862 {canAudit && (
863 <Button key="audit" hotkey="a" variant="primary" onPress={() => auditInEditor($, round)}>
864 {buttons.audit}
865 </Button>
866 )}
867 <Button key="project-files" hotkey="f" onPress={async () => openInFiles($, await projectFolder($), true)}>
868 {buttons.files}
869 </Button>
870 </Box>
871 )
872 const summary = (
873 <Box key="summary" flexDirection="row" justifyContent="space-between" marginTop={1} width={room}>
874 <Box key="totals" flexDirection="row" gap={1}>
875 <Text key="count" bold>
876 {summaryText(stats.files)}
877 </Text>
878 {stats.added > 0 && <Text key="a" color={ADDED}>{`+${stats.added}`}</Text>}
879 {stats.removed > 0 && <Text key="r" color={REMOVED}>{`−${stats.removed}`}</Text>}
880 </Box>
881 {buttons.isBeside && projectButtons}
882 </Box>
883 )
884 const actions = !buttons.isBeside && (
885 <Box key="actions" flexDirection="row" marginTop={1} width={room}>
886 {projectButtons}
887 </Box>
888 )
889
890 const shell = round.shellCommands
891 const warning = shell > 0 && (
892 <Box key="warning" marginTop={1} width={room}>
893 <Text key="text" color="warning" wrap={fit === 'narrow' ? 'truncate-end' : 'wrap'}>
894 {shellWarning(shell, round.isOutsideRepo === true, fit === 'narrow')}
895 </Text>
896 </Box>
897 )
898
899 // One row per file: its kind, then one Button from the number to the counts, so a
900 // click anywhere on the row opens it (a label holds no colors; the badge and the
901 // size bar after it keep theirs).
902 const largest = Math.max(1, ...round.files.map(f => fileStats(f).added + fileStats(f).removed))
903 const badgeWidth = 3
904 const barWidth = fit === 'narrow' ? 0 : 5
905 const labelRoom = room - badgeWidth - 1 - 3 - (barWidth > 0 ? barWidth + 1 : 0)
906 const rows = round.files.map((f, i) => {
907 const { dir, name } = splitPath(where(f.path))
908 const s = fileStats(f)
909 const bar = sizeBar(s.added, s.removed, largest, barWidth)
910 const counts = s.added + s.removed === 0 ? '±0' : [s.added > 0 && `+${s.added}`, s.removed > 0 && `−${s.removed}`].filter(Boolean).join(' ')
911 const hotkey = i < 9 ? String(i + 1) : undefined
912 // A row past the ninth has no `n: ` before it: three spaces keep it in line.
913 const label = `${hotkey ? '' : ' '}${fileRowLabel(name, fit === 'narrow' ? '' : dir, counts, labelRoom)}`
914 return (
915 <Box key={`row:${i}`} flexDirection="row" gap={1} width={room}>
916 {kindBadge(f.kind)}
917 <Button
918 key={`file:${i}`}
919 plain
920 hotkey={hotkey}
921 onPress={() => move($, (_, w) => ({ roundId: w.roundId, file: f.path, screen: 'file' }))}
922 >
923 {label}
924 </Button>
925 {barWidth > 0 && (
926 <Box key="bar" width={barWidth} flexShrink={0}>
927 <Text key="p" color={ADDED}>
928 {'■'.repeat(bar.plus)}
929 </Text>
930 <Text key="m" color={REMOVED}>
931 {'■'.repeat(bar.minus)}
932 </Text>
933 <Text key="x" dimColor>
934 {'·'.repeat(bar.rest)}
935 </Text>
936 </Box>
937 )}
938 </Box>
939 )
940 })
941
942 const n = round.files.length
943 const estimate = wantedRows(round, undefined, 'round', width)
944 return (
945 <Box flexDirection="column" paddingX={1} paddingBottom={scrolls(estimate) ? 1 : 0} width={width}>
946 {nav}
947 {prompt}
948 {summary}
949 {actions}
950 {n > 0 && (
951 <Box key="files" flexDirection="column" marginTop={1} width={room}>
952 {rows}
953 </Box>
954 )}
955 {warning}
956 {hints([
957 ...(n > 0 ? [[n === 1 ? '1' : `1-${Math.min(9, n)}`, 'open'] as const] : []),
958 ...(canAudit ? [['a', 'audit'] as const] : []),
959 ['f', 'files'],
960 ['p/n', 'round'],
961 ...(scrolls(estimate) ? [['g/e', 'top/end'] as const] : []),
962 ['esc', 'close'],
963 ])}
964 {pills(estimate)}
965 </Box>
966 )
967 })
968}
969hooks/model.ts 598 lines1import type { Change, Desktop, FileTouch, Hunk, Live, Round, View } from '../types'
2
3/** Diff lines kept per change; past this the diff is cut and says so. */
4export const MAX_LINES = 400
5/** Rounds kept; the oldest go first. */
6export const MAX_ROUNDS = 60
7
8const isChanged = (line: string) => line.startsWith('+') || line.startsWith('-')
9
10export const countLines = (hunks: readonly Hunk[]) => {
11 let added = 0
12 let removed = 0
13 for (const hunk of hunks)
14 for (const line of hunk.lines) {
15 if (line.startsWith('+')) added++
16 else if (line.startsWith('-')) removed++
17 }
18 return { added, removed }
19}
20
21/** The first changed line, numbered in the file as it is after the change. */
22export const firstChangedLine = (hunks: readonly Hunk[]): number => {
23 const hunk = hunks[0]
24 if (!hunk) return 1
25 let line = hunk.newStart
26 for (const text of hunk.lines) {
27 if (isChanged(text)) return Math.max(1, line)
28 if (!text.startsWith('\\')) line++
29 }
30 return Math.max(1, hunk.newStart)
31}
32
33/** Keeps the first `max` diff lines, recounting a cut hunk so it still parses. */
34export const capHunks = (hunks: readonly Hunk[], max = MAX_LINES): { hunks: Hunk[]; isTruncated: boolean } => {
35 const kept: Hunk[] = []
36 let room = max
37 for (const hunk of hunks) {
38 if (room <= 0) return { hunks: kept, isTruncated: true }
39 if (hunk.lines.length <= room) {
40 kept.push({ ...hunk, lines: [...hunk.lines] })
41 room -= hunk.lines.length
42 continue
43 }
44 const lines = hunk.lines.slice(0, room)
45 const oldLines = lines.filter(l => l.startsWith(' ') || l.startsWith('-')).length
46 const newLines = lines.filter(l => l.startsWith(' ') || l.startsWith('+')).length
47 kept.push({ ...hunk, oldLines, newLines, lines })
48 return { hunks: kept, isTruncated: true }
49 }
50 return { hunks: kept, isTruncated: false }
51}
52
53/** Every line of `text` as an added hunk: a new file. */
54export const addedHunk = (text: string): Hunk[] => {
55 if (text === '') return []
56 const lines = text.replace(/\n$/, '').split('\n')
57 return [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: lines.length, lines: lines.map(l => `+${l}`) }]
58}
59
60/** `before` replaced by `after` as one hunk: a notebook cell. */
61export const replacedHunk = (before: string, after: string): Hunk[] => {
62 const old = before === '' ? [] : before.split('\n')
63 const now = after === '' ? [] : after.split('\n')
64 if (old.length === 0 && now.length === 0) return []
65 return [
66 {
67 oldStart: old.length ? 1 : 0,
68 oldLines: old.length,
69 newStart: now.length ? 1 : 0,
70 newLines: now.length,
71 lines: [...old.map(l => `-${l}`), ...now.map(l => `+${l}`)],
72 },
73 ]
74}
75
76/** A Change from the hunks a tool reported, capped and counted. */
77export const makeChange = (
78 base: Pick<Change, 'toolUseId' | 'tool' | 'agentId' | 'note' | 'language' | 'command'>,
79 hunks: readonly Hunk[],
80): Change => {
81 const { added, removed } = countLines(hunks)
82 const capped = capHunks(hunks)
83 return {
84 ...base,
85 hunks: capped.hunks,
86 isTruncated: capped.isTruncated,
87 added,
88 removed,
89 line: firstChangedLine(hunks),
90 }
91}
92
93/** The diff text `Code format="diff"` draws for a change. */
94export const diffSource = (hunks: readonly Hunk[]): string =>
95 hunks
96 .map(h => [`@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@`, ...h.lines].join('\n'))
97 .join('\n')
98
99/** What a file is after a second change in one round: created then deleted reads deleted, and so on. */
100export const mergeKind = (was: FileTouch['kind'], now: FileTouch['kind']): FileTouch['kind'] =>
101 now === 'deleted' ? 'deleted' : was === 'deleted' ? 'modified' : was
102
103/** Adds `change` to the round `live` names, opening that round on its first change. */
104export const recordChange = (
105 rounds: readonly Round[],
106 live: Live,
107 path: string,
108 kind: FileTouch['kind'],
109 change: Change,
110): Round[] => {
111 const existing = rounds.find(r => r.id === live.id)
112 const round: Round = existing ?? {
113 id: live.id,
114 turn: live.turn,
115 prompt: live.prompt,
116 startedAt: live.startedAt,
117 files: [],
118 shellCommands: 0,
119 }
120 const touched = round.files.find(f => f.path === path)
121 const files = touched
122 ? round.files.map(f => (f === touched ? { ...f, kind: mergeKind(f.kind, kind), changes: [...f.changes, change] } : f))
123 : [...round.files, { path, kind, changes: [change] }]
124 const next = { ...round, files }
125 return existing
126 ? rounds.map(r => (r === existing ? next : r))
127 : [...rounds, next].slice(-MAX_ROUNDS)
128}
129
130/**
131 * Counts one shell command whose changes could not be captured, opening the round
132 * if it has none yet; `outsideRepo` when the folder was in no git repo at the time.
133 */
134export const countShell = (rounds: readonly Round[], live: Live, outsideRepo = false): Round[] => {
135 const existing = rounds.find(r => r.id === live.id)
136 const mark = outsideRepo ? { isOutsideRepo: true } : {}
137 if (existing) return rounds.map(r => (r === existing ? { ...r, ...mark, shellCommands: r.shellCommands + 1 } : r))
138 const round: Round = {
139 id: live.id,
140 turn: live.turn,
141 prompt: live.prompt,
142 startedAt: live.startedAt,
143 files: [],
144 shellCommands: 1,
145 ...mark,
146 }
147 return [...rounds, round].slice(-MAX_ROUNDS)
148}
149
150export const fileStats = (file: FileTouch) => ({
151 added: file.changes.reduce((n, c) => n + c.added, 0),
152 removed: file.changes.reduce((n, c) => n + c.removed, 0),
153})
154
155export const roundStats = (round: Round) => {
156 let added = 0
157 let removed = 0
158 for (const file of round.files) {
159 const s = fileStats(file)
160 added += s.added
161 removed += s.removed
162 }
163 return { added, removed, files: round.files.length }
164}
165
166/** The round the view shows: the one it names, else the newest. */
167export const shownRound = (rounds: readonly Round[], view: View): Round | undefined =>
168 (view.roundId !== null && rounds.find(r => r.id === view.roundId)) || rounds[rounds.length - 1]
169
170/** The file the view shows in `round`: the one it names, else the first. */
171export const shownFile = (round: Round | undefined, view: View): FileTouch | undefined =>
172 round && ((view.file !== null && round.files.find(f => f.path === view.file)) || round.files[0])
173
174/** Names what the viewer shows (round, screen, file), so a measure of one screen is not read on another. */
175export const viewKey = (rounds: readonly Round[], view: View): string => {
176 const round = shownRound(rounds, view)
177 const file = view.screen === 'file' ? shownFile(round, view) : undefined
178 return `${round?.id ?? ''}:${view.screen}:${file?.path ?? ''}`
179}
180
181/** The view one round older (-1) or newer (+1), on its overview; the newest is followed again. */
182export const stepRound = (rounds: readonly Round[], view: View, by: number): View => {
183 const at = shownRound(rounds, view)
184 if (!at) return view
185 const index = Math.min(rounds.length - 1, Math.max(0, rounds.indexOf(at) + by))
186 const target = rounds[index]
187 if (!target || target === at) return view
188 return { roundId: index === rounds.length - 1 ? null : target.id, file: null, screen: 'round' }
189}
190
191/** The view on the next (+1) or previous (-1) file of the shown round, wrapping. */
192export const stepFile = (rounds: readonly Round[], view: View, by: number): View => {
193 const round = shownRound(rounds, view)
194 const file = shownFile(round, view)
195 if (!round || !file) return view
196 const n = round.files.length
197 const index = (((round.files.indexOf(file) + by) % n) + n) % n
198 return { ...view, file: round.files[index]?.path ?? null }
199}
200
201/** How much a row can hold at a width: everything, no folder, or name and counts alone. */
202export type Fit = 'wide' | 'medium' | 'narrow'
203export const fitFor = (columns: number): Fit => (columns >= 72 ? 'wide' : columns >= 46 ? 'medium' : 'narrow')
204
205/**
206 * A GitHub-style size bar of `cells` blocks: the share of added and removed
207 * lines, scaled to the round's largest file so sizes compare at a glance.
208 */
209export const sizeBar = (added: number, removed: number, largest: number, cells = 5) => {
210 const total = added + removed
211 if (total === 0 || largest === 0) return { plus: 0, minus: 0, rest: cells }
212 const filled = Math.max(1, Math.round((total / largest) * cells))
213 let plus = Math.round((added / total) * filled)
214 if (added > 0 && plus === 0) plus = 1
215 if (removed > 0 && plus === filled) plus = filled - 1
216 const minus = filled - plus
217 return { plus, minus: Math.max(0, minus), rest: cells - filled }
218}
219
220/** Cuts `text` to `width` cells, keeping its end: for paths, whose end says the most. */
221export const keepEnd = (text: string, width: number): string =>
222 width <= 0 ? '' : text.length <= width ? text : `…${text.slice(text.length - width + 1)}`
223
224/** Cuts `text` to `width` cells, keeping its start. */
225export const keepStart = (text: string, width: number): string =>
226 width <= 0 ? '' : text.length <= width ? text : `${text.slice(0, width - 1)}…`
227
228/**
229 * The prompt as at most `maxLines` rows of `width` cells, cut at spaces, the last
230 * row ending in … when more was left.
231 */
232export const wrapLines = (text: string, width: number, maxLines: number): string[] => {
233 const room = Math.max(1, width)
234 const lines: string[] = []
235 let rest = text.trim()
236 while (rest !== '' && lines.length < maxLines) {
237 if (rest.length <= room) {
238 lines.push(rest)
239 break
240 }
241 if (lines.length === maxLines - 1) {
242 lines.push(keepStart(rest, room))
243 break
244 }
245 let cut = rest.lastIndexOf(' ', room)
246 if (cut <= 0) cut = room
247 lines.push(rest.slice(0, cut).trimEnd())
248 rest = rest.slice(cut).trimStart()
249 }
250 return lines.length > 0 ? lines : ['']
251}
252
253const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`
254
255/** The warning for shell commands whose changes could not be shown; short when `narrow`. */
256export const shellWarning = (shell: number, isOutsideRepo: boolean, narrow: boolean): string => {
257 const commands = plural(shell, 'shell command')
258 if (narrow) return `⚠ ${isOutsideRepo ? 'No git' : 'Untracked'}: ${commands} not shown`
259 const its = shell === 1 ? 'its' : 'their'
260 return isOutsideRepo
261 ? `⚠ ${commands} ran outside a git repo, so ${its} changes can't be shown. Run git init to track them.`
262 : `⚠ ${commands} couldn't be snapshotted, so ${its} changes aren't shown.`
263}
264
265/** The room the viewer's body has at a pane `width`: its sides are padded by one. */
266const bodyRoom = (width: number) => Math.max(22, width - 2)
267
268/** The round's summary line: how many files changed. Its counts follow it, colored. */
269export const summaryText = (files: number) =>
270 files > 0 ? `${files} file${files === 1 ? '' : 's'} changed` : 'No file changes recorded'
271
272/** Each desktop's file manager, and its name where a row is short. */
273export const FILE_MANAGER: Record<Desktop, { name: string; short: string }> = {
274 wsl: { name: 'File Explorer', short: 'Explorer' },
275 windows: { name: 'File Explorer', short: 'Explorer' },
276 mac: { name: 'Finder', short: 'Finder' },
277 linux: { name: 'file manager', short: 'Files' },
278}
279
280/**
281 * The command that shows `path` in the file manager: a folder opened, a file selected
282 * in its folder. Linux has no common way to select a file, so its folder opens. On WSL
283 * `path` is already the Windows path.
284 */
285export const revealCommand = (desktop: Desktop, path: string, isFolder: boolean): string[] => {
286 if (desktop === 'wsl' || desktop === 'windows') return isFolder ? ['explorer.exe', path] : ['explorer.exe', `/select,${path}`]
287 if (desktop === 'mac') return isFolder ? ['open', path] : ['open', '-R', path]
288 return ['xdg-open', isFolder ? path : splitPath(path).dir || '/']
289}
290
291/** The cells a row of buttons takes: `[ label ]` each, two apart. */
292export const buttonsWidth = (labels: readonly string[]) =>
293 labels.reduce((n, l) => n + l.length + 4, 0) + 2 * Math.max(0, labels.length - 1)
294
295/** Each button's long label, the last ones shortened first until the row fits `room`. */
296export const fitButtons = (room: number, buttons: Record<string, readonly [long: string, short: string]>): Record<string, string> => {
297 const ids = Object.keys(buttons)
298 const labels = Object.fromEntries(ids.map(id => [id, buttons[id]![0]]))
299 for (let i = ids.length - 1; i >= 0 && buttonsWidth(Object.values(labels)) > room; i--) labels[ids[i]!] = buttons[ids[i]!]![1]
300 return labels
301}
302
303/**
304 * The round's buttons: audit while a file is left to open, then the project in the file
305 * manager. They sit at the right end of the summary line when they fit; if not, on a row under it.
306 */
307export const roundButtons = (round: Round, width: number, desktop: Desktop) => {
308 const fm = FILE_MANAGER[desktop]
309 const canAudit = round.files.some(f => f.kind !== 'deleted')
310 const room = bodyRoom(width)
311 const labels = fitButtons(room, {
312 ...(canAudit ? { audit: ['Audit in VS Code', 'Audit'] as const } : {}),
313 files: [`Open in ${fm.name}`, fm.short],
314 })
315 const { added, removed, files } = roundStats(round)
316 const summary =
317 summaryText(files).length + (added > 0 ? `+${added}`.length + 1 : 0) + (removed > 0 ? `−${removed}`.length + 1 : 0)
318 // Two cells at least between the summary and the buttons.
319 return { audit: labels.audit, files: labels.files!, isBeside: summary + 2 + buttonsWidth(Object.values(labels)) <= room }
320}
321
322/**
323 * The rows the viewer wants for what it shows, so it opens no taller than it needs;
324 * `width` is the pane's body, about the docked column.
325 */
326export const wantedRows = (
327 round: Round | undefined,
328 file: FileTouch | undefined,
329 screen: View['screen'],
330 width = 50,
331 desktop: Desktop = 'linux',
332): number => {
333 if (!round) return 6
334 if (screen !== 'round' && file) return diffScreenRows(file, width)
335 const room = bodyRoom(width)
336 const narrow = fitFor(width) === 'narrow'
337 const prompt = wrapLines(promptLine(round.prompt), room - 2, 2).length
338 const warning =
339 round.shellCommands > 0
340 ? 1 + (narrow ? 1 : Math.ceil(shellWarning(round.shellCommands, round.isOutsideRepo === true, false).length / room))
341 : 0
342 // "1-9 open a audit f files p/n round esc close" is 48 cells.
343 const hints = room >= 48 ? 1 : 2
344 const buttons = roundButtons(round, width, desktop).isBeside ? 0 : 2
345 // nav, blank, prompt, meta, blank, summary, [blank, buttons], [blank, files], [blank, warning], blank, hints
346 return 2 + prompt + (narrow ? 0 : 1) + 2 + buttons + (round.files.length > 0 ? 1 + round.files.length : 0) + warning + 1 + hints
347}
348
349/** The finished round whose length matches a "Baked for" line, within a moment's drift. */
350export const roundForDuration = (rounds: readonly Round[], durationMs: number): Round | undefined => {
351 let best: Round | undefined
352 let gap = 1500
353 for (const round of rounds) {
354 if (round.durationMs === undefined) continue
355 const d = Math.abs(round.durationMs - durationMs)
356 if (d <= gap) {
357 gap = d
358 best = round
359 }
360 }
361 return best
362}
363
364/** `path` relative to `root` when inside it, `~/…` under home, else as is. */
365export const displayPath = (path: string, root: string, home?: string): string => {
366 if (root && path.startsWith(`${root}/`)) return path.slice(root.length + 1)
367 if (home && path.startsWith(`${home}/`)) return `~/${path.slice(home.length + 1)}`
368 return path
369}
370
371/** Splits a path into the directory part and the file name. */
372export const splitPath = (path: string): { dir: string; name: string } => {
373 const cut = path.lastIndexOf('/')
374 return cut < 0 ? { dir: '', name: path } : { dir: path.slice(0, cut), name: path.slice(cut + 1) }
375}
376
377/** The prompt as one short line. */
378export const promptLine = (text: string): string => {
379 const line = text.replace(/\s+/g, ' ').trim()
380 return line === '' ? '(continued without a new prompt)' : line
381}
382
383export const clock = (at: number): string => {
384 const d = new Date(at)
385 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
386}
387
388export const duration = (ms: number): string => {
389 const s = Math.max(0, Math.round(ms / 1000))
390 if (s < 60) return `${s}s`
391 const m = Math.floor(s / 60)
392 return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m`
393}
394
395type PatchRecord = { filePath?: string; structuredPatch?: Hunk[]; staged?: boolean }
396type WriteRecord = PatchRecord & { type?: 'create' | 'update'; content?: string; originalFile?: string | null }
397type NotebookRecord = {
398 notebook_path?: string
399 new_source?: string
400 old_source?: string
401 cell_id?: string
402 cell_type?: string
403 language?: string
404 edit_mode?: string
405 error?: string
406}
407
408/**
409 * The file and change a file tool's stored record describes, or undefined when
410 * it changed nothing (an error, a staged write, a tool that edits no file).
411 */
412export const fromToolRecord = (
413 tool: string,
414 toolUseId: string,
415 record: unknown,
416 agentId?: string,
417): { path: string; kind: FileTouch['kind']; change: Change } | undefined => {
418 if (record === null || typeof record !== 'object') return undefined
419 if (tool === 'Edit') {
420 const r = record as PatchRecord
421 if (!r.filePath || r.staged) return undefined
422 const change = makeChange({ toolUseId, tool: 'Edit', agentId }, r.structuredPatch ?? [])
423 return { path: r.filePath, kind: 'modified', change }
424 }
425 if (tool === 'Write') {
426 const r = record as WriteRecord
427 if (!r.filePath || r.staged) return undefined
428 const isNew = r.type === 'create'
429 const patch = r.structuredPatch ?? []
430 const hunks = patch.length > 0 ? patch : isNew ? addedHunk(r.content ?? '') : []
431 const note =
432 hunks.length > 0
433 ? undefined
434 : r.originalFile === null
435 ? 'Rewritten whole; the previous version was too large to diff.'
436 : 'Written with the same content: nothing changed.'
437 const change = makeChange({ toolUseId, tool: 'Write', agentId, note }, hunks)
438 return { path: r.filePath, kind: isNew ? 'added' : 'modified', change }
439 }
440 if (tool === 'NotebookEdit') {
441 const r = record as NotebookRecord
442 if (!r.notebook_path || r.error) return undefined
443 const change = makeChange(
444 {
445 toolUseId,
446 tool: 'NotebookEdit',
447 agentId,
448 language: r.cell_type === 'markdown' ? 'markdown' : r.language,
449 note: `Cell ${r.cell_id ?? '?'} (${r.edit_mode ?? 'edit'})`,
450 },
451 replacedHunk(r.old_source ?? '', r.edit_mode === 'delete' ? '' : (r.new_source ?? '')),
452 )
453 return { path: r.notebook_path, kind: 'modified', change }
454 }
455 return undefined
456}
457
458/** The minimum of a transcript row the rebuild reads. */
459export type TranscriptRow = {
460 role: 'user' | 'assistant'
461 text: string
462 toolUses: readonly { tool_use_id: string; tool: string; result?: unknown; isError?: true }[]
463 toolResults?: readonly unknown[]
464}
465
466/**
467 * Rounds rebuilt from a transcript: each prompt the person typed opens a round,
468 * and the file changes its tool calls stored land in it. Times are unknown (0).
469 */
470export const roundsFromTranscript = (rows: readonly TranscriptRow[]): { rounds: Round[]; turns: number } => {
471 let rounds: Round[] = []
472 let turns = 0
473 let at: Live = { id: 'before-0', turn: 0, prompt: '(before the first prompt)', startedAt: 0, shellCommands: 0 }
474 for (const row of rows) {
475 if (row.role === 'user') {
476 if (row.text.trim() === '' || (row.toolResults && row.toolResults.length > 0)) continue
477 turns++
478 at = { id: `history-${turns}`, turn: turns, prompt: row.text.slice(0, 400), startedAt: 0, shellCommands: 0 }
479 continue
480 }
481 for (const use of row.toolUses) {
482 if (use.isError) continue
483 const found = fromToolRecord(use.tool, use.tool_use_id, use.result)
484 if (found) rounds = recordChange(rounds, at, found.path, found.kind, found.change)
485 }
486 }
487 return { rounds, turns }
488}
489
490/**
491 * A folder cut to `width` by whole segments from its end (`…/round-changes/hooks`),
492 * the nearest folders saying the most; the last segment alone when even one will not fit.
493 */
494export const shortDir = (dir: string, width: number): string => {
495 if (width <= 0) return ''
496 if (dir.length <= width) return dir
497 const parts = dir.split('/')
498 let kept = ''
499 for (let i = parts.length - 1; i >= 0; i--) {
500 const next = kept === '' ? (parts[i] ?? '') : `${parts[i]}/${kept}`
501 if (next.length + 2 > width) break
502 kept = next
503 }
504 return kept === '' ? keepEnd(dir, width) : `…/${kept}`
505}
506
507/**
508 * A file row as one line of `width` cells: the name, its folder when there is room,
509 * and the counts at the right end. The name gives way last.
510 */
511export const fileRowLabel = (name: string, dir: string, counts: string, width: number): string => {
512 const nameRoom = Math.max(4, width - counts.length - 2)
513 const shown = keepStart(name, nameRoom)
514 const dirRoom = width - shown.length - counts.length - 4
515 const folder = dir !== '' && dirRoom > 3 ? ` ${shortDir(dir, dirRoom)}` : ''
516 const left = `${shown}${folder}`
517 return `${left}${' '.repeat(Math.max(1, width - left.length - counts.length))}${counts}`
518}
519
520/** Files an audit opens at most; the rest are in the editor's Source Control view. */
521export const MAX_AUDIT_FILES = 25
522
523/**
524 * The editor command that audits a round: the project folder (its window, if one is
525 * open, else a new one) and each file still there at its first changed line.
526 */
527export const auditCommand = (editor: string, folder: string, files: readonly FileTouch[], max = MAX_AUDIT_FILES) => {
528 const present = files.filter(f => f.kind !== 'deleted')
529 const opened = present.slice(0, max)
530 return {
531 argv: [editor, folder, '-g', ...opened.map(f => `${f.path}:${f.changes[0]?.line ?? 1}`)],
532 opened: opened.length,
533 left: present.length - opened.length,
534 }
535}
536
537/** One file of a `git diff` between two snapshots. */
538export type DiffFile = { path: string; kind: FileTouch['kind']; hunks: Hunk[]; isBinary: boolean }
539
540const unquote = (path: string) =>
541 path.startsWith('"') && path.endsWith('"') ? path.slice(1, -1).replace(/\\(["\\])/g, '$1') : path
542
543/** The files of a `git diff --no-renames` and their hunks, paths relative to the repo's top. */
544export const parseGitDiff = (text: string): DiffFile[] => {
545 const files: DiffFile[] = []
546 let file: DiffFile | undefined
547 let hunk: Hunk | undefined
548 for (const line of text.split('\n')) {
549 if (line.startsWith('diff --git ')) {
550 const b = line.lastIndexOf(' b/')
551 file = { path: unquote(line.slice(b + 3)), kind: 'modified', hunks: [], isBinary: false }
552 hunk = undefined
553 files.push(file)
554 continue
555 }
556 if (!file) continue
557 if (!hunk) {
558 if (line.startsWith('new file mode')) file.kind = 'added'
559 else if (line.startsWith('deleted file mode')) file.kind = 'deleted'
560 else if (line.startsWith('Binary files')) file.isBinary = true
561 else if (line.startsWith('+++ b/')) file.path = unquote(line.slice(6))
562 }
563 const head = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
564 if (head) {
565 hunk = {
566 oldStart: Number(head[1]),
567 oldLines: head[2] === undefined ? 1 : Number(head[2]),
568 newStart: Number(head[3]),
569 newLines: head[4] === undefined ? 1 : Number(head[4]),
570 lines: [],
571 }
572 file.hunks.push(hunk)
573 continue
574 }
575 if (hunk && (line.startsWith(' ') || line.startsWith('+') || line.startsWith('-') || line.startsWith('\\')))
576 hunk.lines.push(line)
577 }
578 return files
579}
580
581/**
582 * About how many rows a file's diff screen draws at `width`, wrapped lines counted:
583 * the nav, title, folder and actions, each change under its rule, the key hints.
584 */
585export const diffScreenRows = (file: FileTouch, width: number, hasDir = true): number => {
586 const room = bodyRoom(width)
587 const code = Math.max(10, width - 9)
588 const hasActions = file.kind !== 'deleted' || file.changes.some(c => !c.agentId)
589 // nav, blank, title, [folder], [blank, actions], blank, hints
590 let rows = 3 + (hasDir ? 1 : 0) + (hasActions ? 2 : 0) + 1 + (room >= 48 ? 1 : 2)
591 for (const c of file.changes) {
592 // blank, rule, [command], [note], [cut note], the diff
593 rows += 2 + (c.command ? 1 : 0) + (c.note ? 1 : 0) + (c.isTruncated ? 1 : 0)
594 for (const h of c.hunks) for (const l of h.lines) rows += Math.max(1, Math.ceil(l.length / code))
595 }
596 return rows
597}
598types/index.d.ts 86 lines1/** One unified-diff hunk, as Edit and Write report it. */
2export type Hunk = {
3 oldStart: number
4 oldLines: number
5 newStart: number
6 newLines: number
7 lines: string[]
8}
9
10/** One tool call that changed a file. */
11export type Change = {
12 toolUseId: string
13 tool: 'Edit' | 'Write' | 'NotebookEdit' | 'Bash'
14 /** The shell command that made the change, for a Bash change. */
15 command?: string
16 /** Set when a subagent made the change: its row is not in the main transcript. */
17 agentId?: string
18 hunks: Hunk[]
19 added: number
20 removed: number
21 /** The first changed line in the file after the change, 1-based. */
22 line: number
23 /** Lines were dropped to keep the stored diff small. */
24 isTruncated: boolean
25 /** Why there is no diff to show, when there is none. */
26 note?: string
27 language?: string
28}
29
30export type FileTouch = {
31 path: string
32 kind: 'added' | 'modified' | 'deleted'
33 changes: Change[]
34}
35
36export type Round = {
37 id: string
38 /** The turn's ordinal in the session. */
39 turn: number
40 prompt: string
41 startedAt: number
42 endedAt?: number
43 files: FileTouch[]
44 /** The turn's length as turn.complete reported it: what finds its "Baked for" line. */
45 durationMs?: number
46 /** Shell commands run this round whose changes could not be captured. */
47 shellCommands: number
48 /** Some of them ran outside any git repo (the rest, if any, failed to snapshot). */
49 isOutsideRepo?: boolean
50}
51
52/** The turn running now, before or after its first change. */
53export type Live = {
54 id: string
55 turn: number
56 prompt: string
57 startedAt: number
58 shellCommands: number
59}
60
61/**
62 * What the viewer shows: a round (null follows the newest), and either its
63 * overview or one file's diff.
64 */
65export type View = { roundId: string | null; file: string | null; screen: 'round' | 'file' }
66
67/** Where the session runs, for the file manager it opens: WSL opens Windows' File Explorer. */
68export type Desktop = 'wsl' | 'windows' | 'mac' | 'linux'
69
70declare module 'claude-code' {
71 interface PluginState {
72 'round-changes': {
73 rounds: Round[]
74 live: Live | null
75 turns: number
76 view: View
77 cwd: string
78 home: string
79 /** The viewer's tree height as the engine measured it at the last scroll, and on which screen (`viewKey`). */
80 scroll: { key: string; contentRows: number } | null
81 /** Where the session runs, found the first time a file manager is needed. */
82 desktop: Desktop | null
83 }
84 }
85}
86