The diff pane as a plugin: /diff opens the session's uncommitted changes beside the transcript, file by file with their hunks, refreshed as Claude edits and…

The diff pane as a plugin: /diff opens the session's uncommitted changes beside the transcript, one row per changed file and every file's hunks beneath, and closes it again; each toggle leaves Diff panel shown or Diff panel hidden in the transcript. The header, the file list and its toggles stay put while the wheel moves the hunks under them three rows a tick, or the list a file a tick while the wheel is over a list longer than its eight rows (the plugin answers the pane's ui.scroll itself); a row's click puts that file's hunks at the top; the list also scrolls under the built-in's list keys (ctrl+up/ctrl+down, opt+up/opt+down), and ctrl+x b moves the comparison base on, as the built-in's chord does: both through Buttons that declare the engine's own actions. The pane refreshes as Claude edits and runs shell commands, and while it is open it polls the repository's HEAD so a commit or checkout made elsewhere shows too. The main loop's first successful edit of a session opens the pane by itself, as the built-in panel opens on its first checkpoint: where the layout docks it beside the transcript (the fullscreen layout, which each drawing's viewport says), the terminal is wide enough (144 columns when the person never chose, 110 when they kept it open before; a person who closed it is left alone) and file checkpointing is on; a subagent's edit or a shell command never makes the first ask, and where the surface does not say, nothing opens by itself. A docked pane fetches before it opens, as the built-in panel primes its data, so it never lands on Loading diff….
An open nobody asked for starts its own fetch, after any fetch already running. It opens the pane only if that fetch succeeds and lists a file, and the person has not opened or closed the pane in the meantime, so it never lands on an empty state such as No changes this session or Diff unavailable. If it does not open, it asks again when that fetch ends if an edit or shell command landed during it, and otherwise at the next edit or shell command that lands. An open the engine leaves waiting undrawn is withdrawn, so no later resize seats it, and the next edit or shell command that lands asks again. An open answered no-surface (nothing is attached that draws it yet, as before a host's page attaches) is kept instead: /diff says so, nothing polls or refreshes while no one sees the pane, and its first drawing reads the repository again and counts it shown. A session resumed or continued whose transcript already holds such an edit opens the pane on the same terms as soon as the width is known. The built-in opens on the history it restores even when the tree lists nothing; this one leaves that case to the next edit or shell command that lands.
Under the fullscreen layout a terminal under 110 columns gets the built-in's line asking for a wider one and nothing opens. Without that layout (CLAUDE_CODE_NO_FLICKER=0, which /diff learns from the command's presentation) the pane opens inline at any width, focused and as tall as its content (the open's rows), in the built-in dialog's shape: the title, the count, five file rows at a time round the selected one (❯, where the focus ring starts; the plugin follows the ring's walk through ui.focus and re-centres the rows as the built-in does), the key hints; Enter shows that file's hunks alone, Escape backs out to the list and then closes, leaving Diff dialog dismissed; toasts show while it is up, as beside the docked pane. A file's ask button arms that file: its hunks ride the next prompt as context, once.
The pane compares the working tree against HEAD, split at the session's start (the default; the start the engine gives in $.session.usage(), so a resumed session keeps its first and /clear begins anew), against HEAD plainly, or against the merge-base with the default branch; the base line under the header names a base other than the session's, and the choice is kept per repository in the plugin's store. A picker shows one earlier turn's edits instead of the working tree, read from the session's messages. Files that changed before the session started (by their timestamp, among the paths already dirty when the pane first read the repository), and noise (lockfiles, generated and test files), are listed apart and folded until asked for; a rename lists as git prints it. Outside a git repository /diff says so and does nothing else.
Git runs when the built-in panel's would: nothing at the session's start; one git rev-parse, in the directory the session started in, when /diff or the first edit a pane has room to open on first needs the repository (an answer of no repository is kept too, until /clear or /resume forgets it); and the working tree is read only by a fetch for an open pane after an edit that landed or a shell command that ran, or by the fetch before a pane opens. Two reads have no counterpart in the built-in: a git status at a pane's first fetch, which stands in for the change time the built-in dates a moved file by, and the fetches an open nobody asked for repeats after its first fetch did not open the pane: one after each later edit or shell command that lands, and one more when one landed during a fetch.
hooks/register.ts is the module; everything under hooks/ is its parts.
| event | what the hook does |
|---|---|
session.start | Binds the engine once and registers /diff (a session where another /diff is listed leaves the plugin idle); asks nothing of the repository, which /diff or the first edit pins when it comes; off its dispatch, reads the transcript, and for a resumed session whose turns edited opens the pane as the first edit would. |
ui.render of PromptHint | Reads the terminal's width and whether its layout docks a pane, which decide whether the first edit opens the pane. |
ui.render of Pane | Draws the pane: docked, the header, base line, source picker, file list and toggles over the window of hunks; inline, the dialog. |
command.run of diff | Pins the repository when none is, opens or closes the pane (focused and closing on Escape without the fullscreen layout), says which, and remembers the choice. |
ui.close of the pane | Backs out of the dialog's detail view instead of closing; else remembers the person's close as /diff's. |
ui.scroll of the pane | Docked, moves the hunks under the pinned header and list (three rows a wheel tick, a page a page key), or the list when the wheel is over it, and keeps the engine's window still. |
ui.focus in the pane | In the dialog's list, selects the file the ring lands on, re-centres the five rows on it, and lands the ring where that row now sits. |
command.run of clear, resume | Forgets the session's state, the pinned repository with it. /resume closes the pane; /clear leaves an open pane up and reads afresh. |
tool.call of Edit, Write, NotebookEdit | After an edit that landed (not refused, not failed), refreshes an open pane. The main loop's first such edit pins the repository and asks to open the pane if the terminal has the room and checkpointing is on; after an ask that did not open it, any edit that lands asks again. |
tool.call of Bash, PowerShell | After a command that was not refused, failed and interrupted ones too, refreshes an open pane; after an ask that did not open the pane, also asks to open it. |
prompt.submit | Adds the armed file's hunks to the prompt's context and disarms. |
$clock.after, clock.every, clock.now, command.register, env.get (CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING), fs.list, fs.read, fs.stat, process.run (git, read-only), session.id, session.messages, settings.read, store.get, store.set, telemetry.log, telemetry.mark, ui.close, ui.invalidate, ui.log, ui.open, ui.resolve, ui.status.
$.telemetry is the telemetry plugin's noun; where it is absent the rows are dropped and nothing else changes.
claude --plugin-dir /path/to/diff
then /diff inside a git repository with a modified file.
hooks/register.ts 1160 lines1import type {
2 Args,
3 On,
4 PaneOpenArgs,
5 ResultOf,
6 SessionMessage,
7 Timer,
8} from 'claude-code'
9
10import Ask from './ask'
11import Backend from './backend'
12import { COMMAND_SPEC } from './command-spec'
13import { drawnFilesOf } from './drawn-files-of'
14import { entryKindsOf } from './entry-kinds-of'
15import type Git from './git'
16import type { Host } from './host'
17import { isCheckpointing } from './is-checkpointing'
18import { isOnPaneSurface } from './is-on-pane-surface'
19import { isRecord } from './is-record'
20import Limits from './limits'
21import { messageOf } from './message-of'
22import { mtimeOf } from './mtime-of'
23import Names from './names'
24import OpenOutcome from './open-outcome'
25import PaneState from './pane-state'
26import PaneToggle from './pane-toggle'
27import Record from './record'
28import Tools from './tools'
29import Turns from './turns'
30import Views from './views'
31
32/**
33 * Registers the diff pane: `/diff` once the built-in stands down, the
34 * pane's drawing and refresh, its opening on Claude's first edit, the ask.
35 *
36 * Git runs when the built-in's would: none at the start; `/diff` or the main
37 * loop's first checkpointed edit with room pins the backend, until `/clear`,
38 * which reads afresh under a pane it leaves open.
39 *
40 * @param on the engine's registrar
41 */
42export function register(on: On) {
43 let host: Host | null = null
44 let backend: Backend.Backend | null = null
45 let probing: Promise<boolean> | null = null
46 let sessionStartMs = 0
47 let isPaneOpen = false
48 let awaited: (typeof Record.SHOWN_TRIGGERS)[number] | null = null
49 let dialogRows: number | null = null
50 let hasAutoOpened = false
51 let isAutoOpenPending = false
52 let personCloses = 0
53 let hasRestoredEdits = false
54 let columns: number | null = null
55 let shownSessionId: string | null = null
56 let armed: Ask.ArmedAsk | null = null
57 let carrying: Ask.ArmedAsk | null = null
58 let isRefreshing = false
59 let isRefreshQueued = false
60 let reading: Promise<void> = Promise.resolve()
61 let generation = 0
62 let landed = 0
63 let bodyStamp: string | null = null
64 let bodyBase: string | null = null
65
66 const bodyLoads = new Set<string>()
67
68 const polled = { toplevel: '', headKey: '' }
69 const pin = { cwd: '', isEmpty: false, epoch: 0 }
70
71 let model: PaneState.PaneModel = PaneState.INITIAL_MODEL
72
73 const timers = new Map<'refresh' | 'redraw' | 'poll', Timer>()
74 const loggedBaseKinds = new Set<'ok' | 'sad'>()
75
76 const currentOf = (engine: Host): Host => host ?? engine
77 const isPaneSeen = (): boolean => isPaneOpen && awaited === null
78
79 const backendHostOf = (engine: Host): Backend.BackendHost => ({
80 run: (argv, init) =>
81 currentOf(engine).run(
82 argv,
83 pin.cwd === '' ? init : { cwd: pin.cwd, ...init },
84 ),
85 readFile: path => currentOf(engine).readFile(path),
86 mtimeOf: path => mtimeOf(currentOf(engine))(path),
87 entryKindsOf: dir => entryKindsOf(currentOf(engine))(dir),
88 nowMs: () => currentOf(engine).now(),
89 sessionStartMsOf: () => sessionStartMs,
90 onBranchBase: base => {
91 const isError = base.kind === 'error'
92
93 const outcome: Record.MarkOutcome = isError
94 ? { kind: 'sad', reason: base.reason }
95 : {
96 kind: 'ok',
97 props: {
98 outcome: { value: base.kind, of: Record.BASE_OUTCOMES },
99 },
100 }
101
102 if (!loggedBaseKinds.has(outcome.kind)) {
103 loggedBaseKinds.add(outcome.kind)
104
105 Record.recorderOf(currentOf(engine)).mark(
106 Record.FEATURES.baseResolve,
107 outcome,
108 )
109 }
110 },
111 })
112
113 function pinBackend(engine: Host): Promise<boolean> {
114 if (backend || pin.isEmpty) {
115 return Promise.resolve(true)
116 }
117
118 probing ??= probeBackend(engine).finally(() => {
119 probing = null
120 })
121
122 return probing
123 }
124
125 async function probeBackend(engine: Host): Promise<boolean> {
126 const asked = { isAnswered: true }
127 const probeHost = backendHostOf(engine)
128 const { epoch } = pin
129
130 const probed = await Backend.backendOf(
131 {
132 ...probeHost,
133 run: (argv, init) =>
134 probeHost.run(argv, init).catch((error: unknown) => {
135 asked.isAnswered &&=
136 argv[0] !== 'git' || !/\baborted\b/.test(messageOf(error))
137
138 throw error
139 }),
140 },
141 Backend.INSTALLED_BACKEND_PROBES,
142 )
143
144 if (epoch !== pin.epoch) {
145 return false
146 }
147
148 backend ??= probed
149 pin.isEmpty = backend === null && asked.isAnswered
150
151 if (!probed || backend !== probed) {
152 return asked.isAnswered || backend !== null
153 }
154
155 startPoll(engine, probed)
156
157 const stored = PaneState.baseModeOf(
158 await engine
159 .storeGet(Names.baseStoreKeyOf(probed.repository.toplevel))
160 .catch(() => undefined),
161 )
162
163 const mode = stored && probed.baseModes.includes(stored) ? stored : null
164
165 model = {
166 ...model,
167 words: probed.words,
168 baseModes: probed.baseModes,
169 ...(mode && { requestedMode: mode }),
170 }
171
172 return true
173 }
174
175 function unpin() {
176 backend = null
177 pin.isEmpty = false
178 pin.epoch += 1
179 polled.toplevel = ''
180 polled.headKey = ''
181 timers.get('poll')?.cancel()
182 timers.delete('poll')
183 }
184
185 function dialogPane(): PaneOpenArgs {
186 return {
187 id: Names.PANE_ID,
188 title: Names.PANE_TITLE,
189 closeOnEscape: true,
190 rows: Views.dialogRowsOf(model),
191 }
192 }
193
194 function fitDialog(engine: Host) {
195 const rows = Views.dialogRowsOf(model)
196
197 const isStale =
198 isPaneOpen && model.isFullscreen === false && rows !== dialogRows
199
200 if (isStale) {
201 dialogRows = rows
202 void engine.openPane(dialogPane()).catch(() => undefined)
203 }
204 }
205
206 function redraw(engine: Host) {
207 fitDialog(engine)
208
209 if (timers.has('redraw')) {
210 return
211 }
212
213 timers.set(
214 'redraw',
215 engine.after(Limits.REDRAW_COALESCE_MS, () => {
216 timers.delete('redraw')
217 engine.invalidate()
218 }),
219 )
220 }
221
222 async function loadBodies(engine: Host): Promise<boolean> {
223 const { data } = model
224 const pinned = backend
225
226 if (!data || !pinned) {
227 bodyStamp = null
228 bodyBase = null
229 bodyLoads.clear()
230 model = { ...model, bodies: PaneState.NO_BODIES }
231
232 return false
233 }
234
235 const stamp = bodyStampOf(data)
236 const isNewBase = data.baseRef !== bodyBase
237
238 if (stamp !== bodyStamp) {
239 bodyStamp = stamp
240 bodyLoads.clear()
241 }
242
243 if (isNewBase) {
244 bodyBase = data.baseRef
245 model = { ...model, bodies: PaneState.NO_BODIES }
246 redraw(engine)
247 }
248
249 return fetchBodies(engine, pinned, data)
250 }
251
252 const bodyStampOf = (data: Git.DiffData) => `${generation}|${data.baseRef}`
253
254 async function fetchBodies(
255 engine: Host,
256 pinned: Backend.Backend,
257 data: Git.DiffData,
258 ): Promise<boolean> {
259 const stamp = bodyStampOf(data)
260
261 const files = drawnFilesOf(model).filter(file => !bodyLoads.has(file.path))
262
263 for (const file of files) {
264 bodyLoads.add(file.path)
265 }
266
267 const read = await pinned.fetchHunks(data, files)
268 const isCurrent = bodyStamp === stamp && read.size > 0
269
270 if (isCurrent) {
271 model = { ...model, bodies: new Map([...model.bodies, ...read]) }
272 redraw(engine)
273 }
274
275 return [...read.values()].includes(null)
276 }
277
278 function keepBaseline() {
279 const pinned = backend
280
281 if (!pinned || polled.headKey !== '') {
282 return
283 }
284
285 void pinned
286 .headKeyOf()
287 .catch(() => '')
288 .then(key => {
289 const isFirst = backend === pinned && polled.headKey === ''
290
291 if (isFirst) {
292 polled.headKey = key
293 }
294 })
295 }
296
297 function startPoll(engine: Host, pinned: Backend.Backend) {
298 const readHeadKey = () => pinned.headKeyOf().catch(() => '')
299
300 if (polled.toplevel === pinned.repository.toplevel) {
301 return
302 }
303
304 timers.get('poll')?.cancel()
305 polled.toplevel = pinned.repository.toplevel
306 polled.headKey = ''
307
308 timers.set(
309 'poll',
310 engine.every(Limits.HEAD_POLL_MS, () => {
311 if (!isPaneSeen()) {
312 return
313 }
314
315 void readHeadKey().then(key => {
316 const hasMoved = polled.headKey !== '' && key !== polled.headKey
317
318 polled.headKey = key
319
320 if (hasMoved) {
321 scheduleRefresh(engine)
322 }
323 })
324 }),
325 )
326 }
327
328 async function refresh(engine: Host): Promise<void> {
329 if (isRefreshing) {
330 isRefreshQueued = true
331
332 return
333 }
334
335 isRefreshing = true
336
337 let settle = (): void => undefined
338
339 reading = new Promise(resolve => {
340 settle = resolve
341 })
342
343 const record = Record.recorderOf(engine)
344 const pinned = backend
345
346 const fetched = (): Promise<Git.FetchOutcome> =>
347 pinned
348 ? pinned.fetchDiff(model.requestedMode)
349 : Promise.resolve({ kind: 'no-repository' })
350
351 try {
352 model = { ...model, isLoading: model.data === null }
353
354 const [outcome, messages] = await Promise.all([
355 fetched(),
356 engine.messages().catch((): SessionMessage[] => []),
357 ])
358
359 model = PaneState.afterFetch(model, { outcome, messages })
360
361 switch (outcome.kind) {
362 case 'no-repository':
363 break
364 case 'unavailable':
365 record.mark(Record.FEATURES.read, {
366 kind: 'sad',
367 reason: 'git_diff_failed',
368 })
369
370 break
371 case 'data':
372 generation += 1
373
374 break
375 }
376
377 const hasHunksFailed = await loadBodies(engine)
378
379 if (outcome.kind === 'data') {
380 record.mark(
381 Record.FEATURES.read,
382 hasHunksFailed
383 ? { kind: 'sad', reason: 'git_hunks_failed' }
384 : { kind: 'ok' },
385 )
386 }
387 } catch (error) {
388 record.mark(Record.FEATURES.read, {
389 kind: 'sad',
390 reason: 'git_diff_threw',
391 })
392
393 throw error
394 } finally {
395 isRefreshing = false
396 settle()
397 redraw(engine)
398
399 if (isRefreshQueued) {
400 isRefreshQueued = false
401 scheduleRefresh(engine)
402 }
403 }
404 }
405
406 function scheduleRefresh(engine: Host): void {
407 timers.get('refresh')?.cancel()
408
409 timers.set(
410 'refresh',
411 engine.after(Limits.REFRESH_DEBOUNCE_MS, () => {
412 timers.delete('refresh')
413 void refresh(engine)
414 }),
415 )
416 }
417
418 async function markShown(
419 engine: Host,
420 trigger: (typeof Record.SHOWN_TRIGGERS)[number],
421 ): Promise<void> {
422 const sessionId = await engine.sessionId().catch(() => null)
423
424 if (sessionId !== null && sessionId !== shownSessionId) {
425 shownSessionId = sessionId
426 Record.recorderOf(engine).shown(trigger, Record.widthBucketOf(columns))
427 }
428 }
429
430 async function showKept(
431 engine: Host,
432 trigger: (typeof Record.SHOWN_TRIGGERS)[number],
433 ): Promise<void> {
434 await markShown(engine, trigger)
435 await pinBackend(engine)
436 keepBaseline()
437 void refresh(engine)
438 }
439
440 async function openPane(
441 engine: Host,
442 trigger: (typeof Record.SHOWN_TRIGGERS)[number],
443 closesBefore = personCloses,
444 ): Promise<OpenOutcome.OpenOutcome> {
445 const isUnasked = trigger === 'auto_open'
446 const epochBefore = pin.epoch
447
448 /**
449 * An open nobody asked for decides on a read it starts itself. A read
450 * already running (a refresh started now would only queue behind it) may
451 * predate the latest edit or a /resume, so it is waited out first.
452 */
453 while (isUnasked && isRefreshing) {
454 await reading
455 }
456
457 const isOvertaken =
458 isPaneOpen || pin.epoch !== epochBefore || personCloses !== closesBefore
459
460 if (isUnasked && isOvertaken) {
461 return 'withdrawn'
462 }
463
464 const isDialog = model.isFullscreen === false
465
466 model = {
467 ...model,
468 selectedPath: null,
469 dialogView: 'list',
470 place: { ...model.place, top: 0, listStart: 0 },
471 }
472
473 dialogRows = isDialog ? Views.dialogRowsOf(model) : null
474
475 const landedBefore = landed
476 const generationBefore = generation
477
478 if (!isDialog) {
479 await refresh(engine).catch(() => undefined)
480 }
481
482 /**
483 * generation moves only when a read returns data (a failed read keeps the
484 * old list), so an unasked open shows a fresh list with a file in it.
485 */
486 const { data } = model
487
488 const isShowable =
489 generation !== generationBefore &&
490 pin.epoch === epochBefore &&
491 !isPaneOpen &&
492 personCloses === closesBefore &&
493 data !== null &&
494 PaneState.headerTotalsOf(
495 data,
496 PaneState.partitionOf(
497 data.files,
498 model.isNoiseShown ? 'shown' : 'hidden',
499 ),
500 ).filesCount > 0
501
502 if (isUnasked && !isShowable) {
503 return 'withdrawn'
504 }
505
506 const opened = await engine.openPane(
507 isDialog
508 ? { ...dialogPane(), focus: true }
509 : { id: Names.PANE_ID, title: Names.PANE_TITLE },
510 )
511
512 const outcome = OpenOutcome.openOutcomeOf(opened)
513
514 if (outcome === 'withdrawn') {
515 await engine.closePane({ id: Names.PANE_ID }).catch(() => undefined)
516
517 return outcome
518 }
519
520 isPaneOpen = true
521 keepBaseline()
522
523 if (outcome === 'awaited') {
524 awaited = trigger
525 } else {
526 await markShown(engine, trigger)
527 }
528
529 const isStale = isDialog || landed !== landedBefore
530
531 if (isStale) {
532 void refresh(engine)
533 }
534
535 return outcome
536 }
537
538 async function closePane(engine: Host): Promise<void> {
539 await engine.closePane({ id: Names.PANE_ID })
540 isPaneOpen = false
541 awaited = null
542 }
543
544 function markTabSwitch(engine: Host, tab: (typeof Record.TABS)[number]) {
545 Record.recorderOf(engine).mark(Record.FEATURES.tabSwitch, {
546 kind: 'ok',
547 props: { tab: { value: tab, of: Record.TABS } },
548 })
549 }
550
551 async function openOnFirstEdit(engine: Host): Promise<void> {
552 const isTaken = () => isPaneOpen || hasAutoOpened
553
554 if (isTaken()) {
555 return
556 }
557
558 const closesBefore = personCloses
559 const preference = await engine.storeGet(Names.STORE_OPEN_KEY)
560 const isKeptOpen = preference === true
561
562 const floor = isKeptOpen
563 ? Limits.OPEN_MIN_COLUMNS
564 : Limits.AUTO_OPEN_MIN_COLUMNS
565
566 const hasRoom =
567 preference !== false &&
568 model.isFullscreen === true &&
569 columns !== null &&
570 columns >= floor
571
572 if (!hasRoom || isTaken()) {
573 return
574 }
575
576 const isCheckpointed = await engine.isCheckpointing().catch(() => true)
577
578 if (!isCheckpointed || isTaken()) {
579 return
580 }
581
582 await pinBackend(engine)
583
584 if (!backend || isTaken()) {
585 return
586 }
587
588 const landedBefore = landed
589 const { epoch } = pin
590
591 hasAutoOpened = true
592
593 const outcome = await openPane(engine, 'auto_open', closesBefore).catch(
594 (): OpenOutcome.OpenOutcome => 'withdrawn',
595 )
596
597 /**
598 * After a /clear or /resume, hasAutoOpened and any retry belong to the new
599 * conversation, which reset hasAutoOpened and may have started an attempt
600 * of its own.
601 */
602 if (pin.epoch !== epoch) {
603 return
604 }
605
606 hasAutoOpened = outcome !== 'withdrawn'
607 isAutoOpenPending = !hasAutoOpened
608
609 /**
610 * An edit or shell command that landed during the attempt may have given
611 * the diff something to list, and a main-loop edit that arrived then
612 * returned early at the isTaken check above, so try again.
613 */
614 if (!hasAutoOpened && landed !== landedBefore) {
615 await openOnFirstEdit(engine)
616 }
617 }
618
619 async function openOnRestore(engine: Host): Promise<void> {
620 hasRestoredEdits =
621 Turns.turnDiffsOf(
622 await engine.messages().catch((): SessionMessage[] => []),
623 ).length > 0
624
625 if (hasRestoredEdits) {
626 await openOnFirstEdit(engine)
627 }
628 }
629
630 function disarm(engine: Host) {
631 armed = null
632 model = { ...model, armedPath: null }
633 engine.status(undefined)
634 }
635
636 const actionsOf = (engine: Host): Views.PaneActions => ({
637 selectFile: path => {
638 const isDocked = model.placement === 'dock'
639
640 model = {
641 ...model,
642 selectedPath: path,
643 dialogView: isDocked ? model.dialogView : 'detail',
644 place: isDocked ? Views.placeAtFile(model, path) : model.place,
645 }
646
647 void loadBodies(engine).catch(() => undefined)
648 redraw(engine)
649 },
650 scrollList: delta => {
651 model = { ...model, place: Views.listScrolledBy(model, delta) }
652 redraw(engine)
653 },
654 toggleNoise: () => {
655 model = { ...model, isNoiseShown: !model.isNoiseShown }
656 void loadBodies(engine)
657 redraw(engine)
658 },
659 togglePreSession: () => {
660 model = { ...model, isPreSessionShown: !model.isPreSessionShown }
661 void loadBodies(engine)
662 redraw(engine)
663 },
664 cycleBase: () => {
665 const { baseModes, requestedMode } = model
666
667 const mode =
668 baseModes[(baseModes.indexOf(requestedMode) + 1) % baseModes.length] ??
669 requestedMode
670
671 if (mode === requestedMode) {
672 return
673 }
674
675 model = { ...model, requestedMode: mode }
676
677 Record.recorderOf(engine).mark(Record.FEATURES.baseSwitch, {
678 kind: 'ok',
679 props: { mode: { value: mode, of: model.baseModes } },
680 })
681
682 const toplevel = model.data?.repository.toplevel
683
684 if (toplevel !== undefined) {
685 void engine
686 .storeSet(Names.baseStoreKeyOf(toplevel), mode)
687 .catch(() => undefined)
688 }
689
690 void refresh(engine)
691 redraw(engine)
692 },
693 chooseSource: value => {
694 const index = Number(value)
695 const isTurn = value !== 'current' && Number.isInteger(index)
696
697 const source: PaneState.Source = isTurn
698 ? { kind: 'turn', index }
699 : { kind: 'current' }
700
701 model = { ...model, source, selectedPath: null, dialogView: 'list' }
702 redraw(engine)
703 },
704 toggleAsk: path => {
705 if (armed?.path === path) {
706 disarm(engine)
707 redraw(engine)
708
709 return
710 }
711
712 arm(engine, path)
713 },
714 })
715
716 function arm(engine: Host, path: string) {
717 armed = Ask.armedAskOf(
718 path,
719 PaneState.pickedTurnOf(model)?.files.find(file => file.path === path)
720 ?.hunks ??
721 model.bodies.get(path)?.hunks ??
722 [],
723 )
724
725 model = { ...model, armedPath: path }
726
727 engine.status(
728 `${Views.sanitizeName(path)} rides your next prompt (press ` +
729 `asked ✓ to drop it)`,
730 )
731
732 redraw(engine)
733 }
734
735 async function startedAtOf(engine: Host): Promise<number | null> {
736 const startedAt: unknown = await engine.startedAt().catch(() => undefined)
737
738 return typeof startedAt === 'number' ? startedAt : null
739 }
740
741 async function bind(engine: Host, cwd: string): Promise<void> {
742 sessionStartMs = (await startedAtOf(engine)) ?? (await engine.now())
743 pin.cwd = cwd
744
745 try {
746 await engine.registerCommand(COMMAND_SPEC)
747 host = engine
748 } catch (error) {
749 const reason = messageOf(error)
750
751 if (!Names.BUILTIN_HOLDS_PATTERN.test(reason)) {
752 engine.uiLog(Names.registerFailedTextOf(Views.sanitizeName(reason)))
753 }
754 }
755 }
756
757 on('session.start', async ($, e, next) => {
758 await bind(
759 {
760 now: () => $.clock.now(),
761 after: (ms, fn) => $.clock.after(ms, fn),
762 every: (ms, fn) => $.clock.every(ms, fn),
763 run: (argv, init) => $.process.run(argv, init),
764 stat: path => $.fs.stat(path),
765 listDir: path => $.fs.list(path),
766 readFile: path => $.fs.read(path),
767 storeGet: key => $.store.get(key),
768 storeSet: (key, value) => $.store.set(key, value),
769 isCheckpointing: async () =>
770 isCheckpointing(
771 await $.settings.read(),
772 await $.env.get('CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING'),
773 ),
774 messages: () => $.session.messages(),
775 invalidate: () => $.ui.invalidate('ui.render'),
776 status: text => $.ui.status(text),
777 uiLog: text => $.ui.log(text),
778 openPane: pane => $.ui.open(pane),
779 closePane: pane => $.ui.close(pane),
780 registerCommand: spec => $.command.register(spec),
781 sessionId: () => $.session.id(),
782 startedAt: () =>
783 $.session
784 .usage()
785 .then((usage: unknown) =>
786 isRecord(usage) ? usage.startedAt : undefined,
787 ),
788 mark: entry => $.telemetry.mark(entry),
789 log: entry => $.telemetry.log(entry),
790 },
791 e.cwd,
792 )
793
794 if (host) {
795 void openOnRestore(host).catch(() => undefined)
796 }
797
798 return next(e)
799 })
800
801 on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
802 if (isOnPaneSurface(e)) {
803 const { viewport } = e
804
805 const isFirstMeasure = columns === null && viewport?.columns !== undefined
806
807 columns = viewport?.columns ?? columns
808
809 model = {
810 ...model,
811 isFullscreen: viewport?.isFullscreen ?? model.isFullscreen,
812 }
813
814 if (isFirstMeasure && hasRestoredEdits && host) {
815 void openOnFirstEdit(host).catch(() => undefined)
816 }
817 }
818
819 return next(e)
820 })
821
822 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
823 if (e.requestId !== Names.PANE_ID || !host || !isOnPaneSurface(e)) {
824 return next(e)
825 }
826
827 const { Box, Text, Button, Select, Code } = await $.ui.resolve(e)
828
829 columns = e.viewport?.columns ?? columns
830
831 if (awaited !== null) {
832 const trigger = awaited
833
834 awaited = null
835 void showKept(host, trigger).catch(() => undefined)
836 }
837
838 /**
839 * A seat that changed since the last drawing lists other rows, whose
840 * bodies are read once.
841 *
842 * The model takes the new seat in this same pass, so the drawing that
843 * read asks for finds the seat unchanged.
844 */
845 const isReseated = e.props.placement !== model.placement
846
847 model = {
848 ...model,
849 placement: e.props.placement,
850 place: {
851 ...model.place,
852 columns: Math.max(
853 1,
854 e.props.bodyColumns - Limits.PANE_RIGHT_PAD_COLUMNS,
855 ),
856 rows: e.props.scroll.bodyRows,
857 },
858 }
859
860 if (isReseated) {
861 void loadBodies(host).catch(() => undefined)
862 }
863
864 return Views.paneView(
865 {
866 ui: { Box, Text, Button, Select, Code },
867 actions: actionsOf(host),
868 columns: e.props.bodyColumns,
869 rows: e.props.scroll.bodyRows,
870 },
871 model,
872 { placement: e.props.placement, terminalColumns: columns },
873 )
874 })
875
876 on('command.run', { command: 'diff' }, async ($, e, next) => {
877 if (!host) {
878 return next(e)
879 }
880
881 const isAnswered = (await pinBackend(host)) || (await pinBackend(host))
882
883 if (!backend) {
884 return {
885 text: isAnswered
886 ? Names.NOT_IN_REPOSITORY_TEXT
887 : Names.GIT_UNANSWERED_TEXT,
888 }
889 }
890
891 const { isFullscreen } = e.presentation
892
893 columns = e.presentation.columns
894 model = { ...model, isFullscreen }
895
896 const toggle = PaneToggle.paneToggleOf({
897 isOpen: isPaneOpen,
898 columns: isFullscreen ? columns : null,
899 })
900
901 if (toggle === 'too-narrow') {
902 return { text: Names.RESIZE_TERMINAL_TEXT }
903 }
904
905 const isOpening = toggle === 'open'
906
907 if (!isOpening) {
908 personCloses += 1
909 }
910
911 const outcome = isOpening
912 ? await openPane(host, 'manual')
913 : await closePane(host).then(() => 'placed' as const)
914
915 if (outcome === 'withdrawn') {
916 return { text: Names.RESIZE_TERMINAL_TEXT }
917 }
918
919 if (outcome === 'awaited') {
920 return { text: Names.AWAITS_SURFACE_TEXT }
921 }
922
923 if (!isFullscreen) {
924 return isOpening ? {} : { text: Names.DIALOG_DISMISSED_TEXT }
925 }
926
927 markTabSwitch(host, isOpening ? 'diff' : 'convo')
928 await host.storeSet(Names.STORE_OPEN_KEY, isOpening).catch(() => undefined)
929
930 return {
931 text: isOpening ? Names.PANEL_SHOWN_TEXT : Names.PANEL_HIDDEN_TEXT,
932 }
933 })
934
935 on('ui.close', { id: Names.PANE_ID }, async ($, e, next) => {
936 const isBack =
937 e.origin.kind === 'person' &&
938 model.placement === 'inline' &&
939 model.dialogView === 'detail'
940
941 if (isBack && host) {
942 model = { ...model, dialogView: 'list' }
943 redraw(host)
944
945 dialogRows = Views.dialogRowsOf(model)
946
947 void host
948 .openPane({ ...dialogPane(), focus: true })
949 .catch(() => undefined)
950
951 return { deny: 'back to the file list' }
952 }
953
954 const result = await next(e)
955 const isClosed = result.deny === undefined
956 const isPersons = isClosed && e.origin.kind === 'person'
957
958 if (isClosed) {
959 isPaneOpen = false
960 awaited = null
961 }
962
963 if (isPersons) {
964 personCloses += 1
965 }
966
967 const isDocking = model.isFullscreen !== false
968
969 if (isPersons && host && isDocking) {
970 markTabSwitch(host, 'convo')
971 await host.storeSet(Names.STORE_OPEN_KEY, false).catch(() => undefined)
972 }
973
974 return result
975 })
976
977 on('ui.focus', { plugin: Names.PLUGIN_NAMES }, ($, e, next) => {
978 const isListed =
979 model.placement === 'inline' && model.dialogView === 'list' && host
980
981 const focus = isListed ? Views.dialogFocusOf(model, e.element) : null
982
983 if (focus === 'stay') {
984 return {}
985 }
986
987 if (!focus || !host) {
988 return next(e)
989 }
990
991 model = { ...model, selectedPath: focus.selectedPath }
992 void loadBodies(host).catch(() => undefined)
993 fitDialog(host)
994 host.invalidate()
995
996 return next({ ...e, element: focus.landing })
997 })
998
999 on('ui.scroll', { requestId: Names.PANE_ID }, ($, e, next) => {
1000 const isOwnBody = e.origin.kind === 'person' && model.placement === 'dock'
1001
1002 if (!isOwnBody || !host) {
1003 return next(e)
1004 }
1005
1006 const isOverList = Views.isWheelOverList(model, e)
1007
1008 model = {
1009 ...model,
1010 place: isOverList
1011 ? Views.listScrolledBy(model, e.by)
1012 : Views.bodyScrolledBy(model, e),
1013 }
1014
1015 host.invalidate()
1016
1017 return {}
1018 })
1019
1020 on('command.run', { command: ['clear', 'resume'] }, async ($, e, next) => {
1021 const result = await next(e)
1022
1023 if (!host) {
1024 return result
1025 }
1026
1027 const isResume = e.command === 'resume'
1028 const isKeptOpen = isPaneSeen() && !isResume
1029
1030 if (isPaneOpen && isResume) {
1031 await closePane(host).catch(() => undefined)
1032 }
1033
1034 unpin()
1035 hasAutoOpened = false
1036 isAutoOpenPending = false
1037 hasRestoredEdits = false
1038 bodyStamp = null
1039 bodyBase = null
1040 bodyLoads.clear()
1041 disarm(host)
1042 model = PaneState.afterNewSession(model)
1043
1044 sessionStartMs =
1045 (await startedAtOf(host)) ??
1046 (isResume ? sessionStartMs : await host.now())
1047
1048 if (isKeptOpen) {
1049 await showKept(host, 'manual')
1050 }
1051
1052 if (isResume) {
1053 void openOnRestore(host).catch(() => undefined)
1054 }
1055
1056 return result
1057 })
1058
1059 function afterTool(
1060 engine: Host,
1061 e: Args<'tool.call'>,
1062 result: ResultOf['tool.call'] | undefined,
1063 ) {
1064 const isEdit = Tools.EDITING_TOOLS.some(name => name === e.tool)
1065
1066 const hasEdited =
1067 isEdit &&
1068 result !== undefined &&
1069 result.deny === undefined &&
1070 result.isError !== true
1071
1072 const hasLanded = isEdit ? hasEdited : Tools.mayHaveWritten(result)
1073
1074 if (hasLanded) {
1075 landed += 1
1076 }
1077
1078 if (hasLanded && isPaneSeen()) {
1079 scheduleRefresh(engine)
1080 }
1081
1082 const isMainLoopEdit = hasEdited && e.agentId === undefined
1083
1084 /**
1085 * Only a main-loop edit, or a restored session, makes the first ask. After
1086 * an ask that did not open the pane, any edit or shell command that lands
1087 * asks again, since it may have given the diff something to list.
1088 */
1089 if (isMainLoopEdit || (hasLanded && isAutoOpenPending)) {
1090 void openOnFirstEdit(engine).catch(() => undefined)
1091 }
1092 }
1093
1094 on(
1095 'tool.call',
1096 { tool: [...Tools.EDITING_TOOLS, ...Tools.SHELL_TOOLS] },
1097 async ($, e, next) => {
1098 let result: ResultOf['tool.call'] | undefined
1099
1100 try {
1101 result = await next(e)
1102
1103 return result
1104 } finally {
1105 if (host) {
1106 afterTool(host, e, result)
1107 }
1108 }
1109 },
1110 )
1111
1112 on('prompt.submit', async ($, e, next) => {
1113 const asked = armed
1114
1115 if (!host || !asked || carrying === asked) {
1116 return next(e)
1117 }
1118
1119 const context = e.context ?? []
1120
1121 const text = Ask.fittedAskTextOf(
1122 asked.text,
1123 Limits.PROMPT_CONTEXT_MAX_CHARS -
1124 context.reduce((sum, entry) => sum + entry.length, 0),
1125 )
1126
1127 if (text === undefined) {
1128 disarm(host)
1129
1130 host.status(
1131 `${Views.sanitizeName(asked.path)}'s diff did not fit in the prompt ` +
1132 `and was dropped`,
1133 )
1134
1135 redraw(host)
1136
1137 return next(e)
1138 }
1139
1140 carrying = asked
1141
1142 try {
1143 const result = await next({ ...e, context: [...context, text] })
1144
1145 if (result.drop === undefined) {
1146 Record.recorderOf(host).asked()
1147
1148 if (armed === asked) {
1149 disarm(host)
1150 redraw(host)
1151 }
1152 }
1153
1154 return result
1155 } finally {
1156 carrying = null
1157 }
1158 })
1159}
1160hooks/ask/index.ts 7 lines1export * from './armed-ask'
2export * from './armed-ask-of.js'
3export * from './ask-cut-note'
4export * from './fitted-ask-text-of.js'
5
6export * as default from '.'
7hooks/backend/index.ts 6 lines1export * from './backend-of.js'
2export * from './installed-backend-probes.js'
3export * from './types'
4
5export * as default from '.'
6hooks/command-spec/index.ts 4 lines1export * from './command-spec.js'
2
3export * as default from '.'
4hooks/drawn-files-of/index.ts 4 lines1export * from './drawn-files-of.js'
2
3export * as default from '.'
4hooks/entry-kinds-of/index.ts 4 lines1export * from './entry-kinds-of.js'
2
3export * as default from '.'
4hooks/git/index.ts 21 lines1export * from './argv'
2export * from './cut-hunks'
3export * from './display-path-of'
4export * from './empty-file-hunks'
5export * from './failed-run'
6export * from './fetch-diff'
7export * from './fetch-hunks'
8export * from './git-backend-of.js'
9export * from './git-base-modes'
10export * from './git-words'
11export * from './hunk-after.js'
12export * from './hunk-of'
13export * from './large-file-hunks'
14export * from './parse'
15export * from './probes'
16export * from './rename-display-of'
17export * from './tiers'
18export * from './types'
19
20export * as default from '.'
21hooks/host/index.ts 4 lines1export type * from './host.js'
2
3export * as default from '.'
4hooks/is-checkpointing/index.ts 4 lines1export * from './is-checkpointing.js'
2
3export * as default from '.'
4hooks/is-on-pane-surface/index.ts 4 lines1export * from './is-on-pane-surface.js'
2
3export * as default from '.'
4hooks/is-record/index.ts 4 lines1export * from './is-record.js'
2
3export * as default from '.'
4hooks/limits/index.ts 9 lines1export * from './columns'
2export * from './dialog-path-floor.js'
3export * from './sizes'
4export * from './timing'
5export * from './todo-bar-cells.js'
6export * from './todo-bar-reserve.js'
7
8export * as default from '.'
9