A git pane for Claude Code: review what Claude changed (per prompt, uncommitted or the whole branch), read diffs and rendered Markdown, then stage, commit…

claude-git-file-tree is a git pane for Claude Code. The pane shows next to the conversation. Use it to examine the changes that Claude makes. Then use it to stage, commit, and push the changes.
The purpose of this mod is to make the AI development workflow simpler.
When Claude writes your code, your work changes. You write less code. You examine more changes, and you commit them. For these tasks, you usually open an IDE or a git client, for example GitKraken or Fork.
This mod does the most frequent of these tasks in Claude Code. It can partially replace your IDE and your git client. You do not need a second app or a second terminal.

The pane shows:
/plugin install git-file-tree --marketplace CosminBd/claude-git-file-tree
y to add the marketplace./files./files path/to/file.To use the letter keys, click the pane first. You can also push ctrl+x tab.
In fullscreen mode, the pane shows next to the conversation. In other modes, the pane shows above the prompt.
| Key | Function |
|---|---|
v | Change what the tree compares with. See the table below |
a | Show only the changed files, or show all the files |
f | Find files by name. For example, chk finds checkout.ts |
h | Show the commit history |
The tree can compare with three references:
| View | The tree shows |
|---|---|
| Uncommitted | The changes against HEAD. This is the default view |
| Branch | All the changes of the branch against main or master |
| Prompt | Only the changes since your last prompt |
The letter before each file shows the type of change:
| Letter | Change |
|---|---|
| M | Modified |
| A | Added |
| U | New. Git does not track the file |
| D | Deleted |
| R | Renamed |
The tree refreshes after each edit that Claude makes. While the pane is open, the tree also refreshes every 3 seconds.
The Prompt view shows only the files that changed during the last turn. It also shows new files that git does not track.
When you send a prompt, the mod records a git tree of your files. The mod uses its own index (.git/git-file-tree-*.index). Your staged changes do not change.
When you view the transcript of a subagent, the pane shows the work of that subagent. When you go back to the main conversation, the pane shows all the changes again.
The pane finds the worktree of a subagent from the files that the subagent reads or changes. If the pane did not see these files, it looks in git worktree list. It uses the worktree in the folder agent-<id>, or the worktree whose branch or folder has the name of the subagent.
Click a file to open it. A changed file opens on its diff.

| Key | Function |
|---|---|
d | Show the diff |
s | Show the source, with syntax highlighting |
m | Show the rendered Markdown |
n / p | Go to the next or the previous changed file |
t | Stage or unstage the file |
x | Discard the changes to the file. Push x two times to confirm |
c | Copy the path of the file |
r | Mention the file, or the selected lines, in the prompt. See Mention files and lines |
o | Open the file in its default app |
b | Go back to the tree |
You can put a file or some of its lines in the prompt, for Claude to read when you send the prompt:
@src/cart/cart.ts.@src/cart/cart.ts#L17-19. You can select part of a line: the mention takes the whole line.The mention goes where the cursor is in the prompt. Click again to add more files or lines.
A mention names the file on disk. Lines that the file does not have go in the prompt as a quote instead: removed lines in a diff, the lines of a past commit, the lines of a deleted file.
Mouse selection is available only in fullscreen mode. A selection moves the keyboard to the prompt: click the button, or push ctrl+x tab and then r.
A Markdown file opens rendered. The Markdown viewer fits the text to the width of the pane:

Terminals that can show images (kitty, Ghostty) show PNG files in the pane.
The git operations are available only in the Uncommitted view.
To stage changes:
To commit the staged changes:
c.Claude can write the commit message for you:
w.To change the last commit, select Amend last commit before you click Commit.
The buttons below the commit box show only when they can do an operation:
| Button | Function |
|---|---|
| Push | Push the branch. The key is p |
| Push branch | Push a branch that has no upstream. The upstream becomes origin |
| Force push | Push with --force-with-lease --force-if-includes. It shows when the branch has an upstream. Use it after an amend or a rebase |
| Pull | Pull with --ff-only |
| Fetch | Fetch from the remote |
| Undo commit | Remove the last commit if it is not pushed (git reset --soft). The changes stay staged |
| Create PR ↗ | Push the branch if necessary, then open the GitHub page that creates a PR. It shows only when the branch has no PR. The pane looks for the PR again each minute. GitHub sets the base branch, the template, the reviewers and the draft state |
| PR #14 open | Open the PR of the branch in the browser. You must install the GitHub CLI (gh) and log in |
The line below the buttons shows the result of the last operation. If an operation fails, the line shows the git message.
Push h to show the last 50 commits of the current branch. Each commit shows its age and its author. The commits that are not pushed show first. The Push, Pull and Fetch buttons show at the top, so you can push the commits from the history.

To examine a commit:
v.The pane does not use the model. It runs git and reads files on your computer. The /files command adds no text to the conversation.
Only Write message uses the model. It sends the staged diff (up to 24,000 characters) and the subjects of the last 8 commits. It also sends the conversation.
gh). You must log in.claude plugin validate .
claude plugin test .
claude --plugin-dir .
hooks/vendor/shiki.js is a build of Shiki with only the Vue and Svelte grammars and two themes. To make it again, run scripts/shiki/build.sh.
MIT. The Shiki build in hooks/vendor is MIT too: see hooks/vendor/shiki.LICENSE.
hooks/register.tsx 191 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import * as A from './actions'
5import type { Io } from './actions'
6import * as S from './state'
7import { renderFooter, renderPane } from './view'
8
9/** How often git is read while the pane is open; four times slower while it is closed. */
10const POLL_MS = 3000
11/** Polls between two reads of the branch's PR: a minute. */
12const PR_TICKS = 20
13
14/** How soon the tree follows a switch to a subagent's transcript, or back. */
15const FOLLOW_MS = 250
16
17const ui = atom({ plugin: 'git-file-tree', key: 'ui' } as const, S.INITIAL)
18// The session keeps this value across reloads: a field added since it was written reads as its default.
19
20export const register: Register = on => {
21 let ticks = 0
22 /** The transcript the pane's last drawing showed beside it: an agent id, null for the main one. */
23 let wanted: string | null = null
24 /** The transcript the tree follows now, as the ticker last set it; undefined until the first tick syncs it. */
25 let followed: string | null | undefined
26 /** The name the viewed agent is addressed by: a worktree named after it is its own. */
27 let wantedName: string | null = null
28 /** The engine's closures, built once the session starts; every hook after it works through them. */
29 let io: Io | null = null
30
31 on('session.start', async ($, e, next) => {
32 const engine: Io = {
33 get: async () => ({ ...S.INITIAL, ...(await read($, ui)) }),
34 set: change => update($, ui, state => change({ ...S.INITIAL, ...state })),
35 run: (argv, cwd, init) => $.process.run(argv, { ...(cwd === undefined ? {} : { cwd }), ...init }),
36 now: () => $.clock.now(),
37 writeText: (path, text) => $.fs.write(path, text),
38 stat: path => $.fs.stat(path),
39 readText: path => $.fs.read(path),
40 readBase64: async path => (await $.fs.read(path, { as: 'bytes' })).base64,
41 storeGet: key => $.store.get(key),
42 storeSet: (key, value) => $.store.set(key, value),
43 cwd: () => $.session.cwd(),
44 theme: async () => {
45 const row = (await $.config.list().catch(() => [])).find(entry => entry.key === 'theme')
46
47 return typeof row?.value === 'string' ? row.value : 'dark'
48 },
49 scroll: args => $.ui.scroll(args),
50 focus: args => $.ui.focus(args),
51 open: args => $.ui.open(args),
52 close: id => $.ui.close({ id }),
53 toast: text => $.ui.toast(text),
54 copy: async (text, surface) => (await $.ui.copy({ text, surface })).isCopied,
55 selection: async () => (await $.ui.selection())?.text ?? null,
56 promptBox: () => $.prompt.read(),
57 insert: async text => (await $.prompt.fill({ text, mode: 'insert' })).isFilled,
58 fork: async prompt => {
59 const reply = await $.model.fork({ prompt })
60
61 return reply.isAnswered ? { text: reply.text } : { reason: reply.reason }
62 },
63 }
64 io = engine
65
66 await $.command.register({
67 name: 'files',
68 description: 'Open the git pane: changed files, diffs, commit and push',
69 argumentHint: '[path]',
70 immediate: true,
71 })
72 await A.loadPrefs(engine)
73 void A.takePromptBase(engine, 'session').catch(() => undefined)
74 // A reload with the pane open: the git controls need gh and the remote read (checkGh skips what it knows).
75 void A.refresh(engine)
76 .then(async () => ((await S.pick(engine, 'isOpen')) ? A.checkGh(engine) : undefined))
77 .catch(() => undefined)
78 // Follows the transcript in view: the drawing notes it, this tick (outside any drawing) switches the tree.
79 $.clock.every(FOLLOW_MS, () => {
80 void A.watchSelection(engine).catch(() => undefined)
81 if (wanted === followed) return
82 followed = wanted
83 void A.followView(engine, wanted, wantedName).catch(() => undefined)
84 })
85 $.clock.every(POLL_MS, () => {
86 ticks += 1
87 void (async () => {
88 await A.expireConfirm(engine)
89 const isOpen = await S.pick(engine, 'isOpen')
90 if (isOpen || ticks % 4 === 0) await A.refresh(engine)
91 // A PR made or merged on GitHub (Create PR opens the browser): read it again each minute.
92 if (isOpen && ticks % PR_TICKS === 0) await A.refreshPr(engine)
93 })().catch(() => undefined)
94 })
95
96 return next(e)
97 })
98
99 on('command.run', { command: 'files' }, async ($, e) => {
100 if (io === null) return { text: 'The file tree is still starting.' }
101 const isPlaced = await A.openPane(io)
102 const target = e.args.trim()
103 if (isPlaced && target !== '') {
104 await A.refresh(io)
105 const snap = await S.pick(io, 'snapshot')
106 const cwd = await io.cwd()
107 const absolute = target.startsWith('/') ? target : `${cwd}/${target}`
108 const root = snap?.root ?? cwd
109 const relative = absolute.startsWith(`${root}/`) ? absolute.slice(root.length + 1).replace(/^\.\//, '') : target
110 await A.openFile(io, relative)
111 }
112
113 // No text: nothing of this reaches the model.
114 return {}
115 })
116
117 // Each prompt starts a fresh record of what Claude reads, writes and commits.
118 on('prompt.submit', async ($, e, next) => {
119 if (io !== null) await A.clearActivity(io).catch(() => undefined)
120 // Not awaited: the snapshot lands long before Claude's first edit, and the prompt goes at once.
121 if (io !== null) void A.takePromptBase(io, 'prompt').catch(() => undefined)
122
123 return next(e)
124 }).catch(($, e, next) => next(e))
125
126 // After Claude's reads, edits and commands: mark the files and refresh, never holding up the tool.
127 on('tool.call', async ($, e, next) => {
128 const result = await next(e)
129 if (io === null) return result
130 const engine = io
131 const tool = String(e.tool)
132 const agentId = (e as { agentId?: unknown }).agentId
133 const filePath = (e as { file_path?: unknown; notebook_path?: unknown }).file_path ?? (e as { notebook_path?: unknown }).notebook_path
134 const path = typeof filePath === 'string' ? filePath : null
135 const isWrite = tool === 'Edit' || tool === 'Write' || tool === 'MultiEdit' || tool === 'NotebookEdit'
136
137 // The main conversation's marks; a subagent's count there too when it works in the session's own tree.
138 const noteMain = () => {
139 if (isWrite) void A.noteEdit(engine, path).catch(() => undefined)
140 else if (tool === 'Read' && path !== null) void A.noteRead(engine, path).catch(() => undefined)
141 else if (tool === 'Bash') {
142 const command = (e as { command?: unknown }).command
143 const done = result as { text?: string; isReadOnly?: true; isError?: true }
144 void A.noteShell(engine, typeof command === 'string' ? command : '', done.text ?? '', done.isReadOnly === true, done.isError === true)
145 .catch(() => undefined)
146 }
147 }
148
149 if (typeof agentId !== 'string') noteMain()
150 else if (path !== null && (isWrite || tool === 'Read')) {
151 void A.noteAgent(engine, agentId, isWrite ? 'write' : 'read', path)
152 .then(async root => {
153 if (root === (await A.sessionRoot(engine))) noteMain()
154 })
155 .catch(() => undefined)
156 } else if (tool === 'Bash') void A.refresh(engine).catch(() => undefined)
157
158 return result
159 }).catch(($, e, next) => next(e))
160
161 on('ui.close', { id: 'files' }, async ($, e, next) => {
162 const result = await next(e)
163 await update($, ui, state => ({ ...state, isOpen: false }))
164
165 return result
166 }).catch(($, e, next) => next(e))
167
168 on('ui.render', { component: 'Pane', requestId: 'files' }, async ($, e, next) => {
169 if (io === null) return next(e)
170 // Reads go through this drawing's own `$`, so a later write draws it again.
171 const drawing: Io = { ...io, get: async () => ({ ...S.INITIAL, ...(await read($, ui)) }) }
172 // A drawing may not write, nor anything it starts: the follow tick of session.start makes the switch.
173 const viewed = e.props.view.agentId ?? null
174 const agent = viewed === null ? null : (await $.agent.list().catch(() => [])).find(info => info.id === viewed)
175 // Both at once, so the tick never follows the agent without its name.
176 wantedName = agent?.name ?? null
177 wanted = viewed
178
179 return renderPane({ io: drawing, t: $.ui.resolve(e), e, agentLabel: agent?.description ?? agent?.name ?? null })
180 })
181
182 // The Files button, at the right of the prompt footer beside the mode labels.
183 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
184 if (io === null) return next(e)
185 const drawing: Io = { ...io, get: async () => ({ ...S.INITIAL, ...(await read($, ui)) }) }
186 const footer = await renderFooter({ io: drawing, t: $.ui.resolve(e), e }, e.props.modes)
187
188 return footer ?? next(e)
189 })
190}
191hooks/actions.ts 789 lines1import type { PaneOpenArgs, RenderSurface, UiFocusArgs, UiScrollArgs } from 'claude-code'
2
3import type { ActivityKind, BaseMode, ChangedFile, CommitInfo, GitUi, Preview, PreviewMode, Snapshot } from '../types'
4import { ancestors, isCommit, mergeActivity, pathsIn, toRelative } from './activity'
5import { defaultBranch, EMPTY_TREE, listAll, listCommits, listTree, scan } from './git'
6import type { Git, RunResult } from './git'
7import { defaultMode, loadPreview, modesFor, pngDimensions } from './preview'
8import type { PreviewDeps } from './preview'
9import * as S from './state'
10import { cleanMessage, compareUrl, CONFIRM_MS, discardCommands, messagePrompt, outcomeOf, parsePrView, pathsOf, webUrlOf } from './ops'
11import type { Outcome } from './ops'
12import { reviewOrder } from './tree'
13import { mentionOf, pick } from './mention'
14
15/**
16 * What the actions need from the engine, as closures a hook builds where `$` is in scope
17 * (a mod spells `$` only at its call sites, never passes it on).
18 */
19export type Io = S.StateIo & {
20 run: (argv: string[], cwd?: string, init?: RunInit) => Promise<RunResult>
21 now: () => Promise<number>
22 writeText: (path: string, text: string) => Promise<void>
23 stat: (path: string) => Promise<{ kind: string; size: number }>
24 readText: (path: string) => Promise<string>
25 readBase64: (path: string) => Promise<string>
26 storeGet: (key: string) => Promise<unknown>
27 storeSet: (key: string, value: unknown) => Promise<void>
28 cwd: () => Promise<string>
29 /** Claude Code's theme setting, `dark` when it cannot be read. */
30 theme: () => Promise<string>
31 scroll: (args: UiScrollArgs) => Promise<unknown>
32 focus: (args: UiFocusArgs) => Promise<unknown>
33 open: (args: PaneOpenArgs) => Promise<{ isPlaced: boolean }>
34 close: (id: string) => Promise<void>
35 toast: (text: string) => void
36 copy: (text: string, surface: RenderSurface) => Promise<boolean>
37 /** The text last selected with the mouse, in the pane or the conversation; null with none. */
38 selection: () => Promise<string | null>
39 /** The prompt box: the draft so far and the cursor's offset into it. */
40 promptBox: () => Promise<{ text: string; cursor: number }>
41 /** Puts text in the prompt box at the cursor; false where no box takes it. */
42 insert: (text: string) => Promise<boolean>
43 /** Asks the session's own model, over this conversation, with no tools: its reply, or why there is none. */
44 fork: (prompt: string) => Promise<{ text: string } | { reason: string }>
45}
46
47export type RunInit = { env?: Record<string, string>; stdin?: string; timeoutMs?: number }
48
49const gitOf = (io: Io): Git => (args, cwd) => io.run(['git', '-c', 'core.quotepath=off', '-c', 'color.ui=never', ...args], cwd)
50
51const previewDeps = (io: Io): PreviewDeps => ({
52 git: gitOf(io),
53 size: async path => {
54 try {
55 const stat = await io.stat(path)
56
57 return stat.kind === 'file' ? stat.size : null
58 } catch {
59 return null
60 }
61 },
62 readText: path => io.readText(path),
63 theme: () => io.theme(),
64 pngSize: async path => {
65 try {
66 return pngDimensions((await io.readBase64(path)).slice(0, 32))
67 } catch {
68 return null
69 }
70 },
71})
72
73const savePrefs = async (io: Io): Promise<void> => {
74 const prefs: S.Prefs = { view: await S.pick(io, 'view'), baseMode: await S.pick(io, 'baseMode') }
75 await io.storeSet(S.PREFS_KEY, prefs).catch(() => undefined)
76}
77
78export const loadPrefs = async (io: Io): Promise<void> => {
79 const prefs = ((await io.storeGet(S.PREFS_KEY).catch(() => undefined)) ?? {}) as S.Prefs
80 if (prefs.view === 'changes' || prefs.view === 'all') await S.put(io, 'view', () => prefs.view ?? 'changes')
81 if (prefs.baseMode !== undefined && BASE_ORDER.includes(prefs.baseMode)) await S.put(io, 'baseMode', () => prefs.baseMode ?? 'head')
82}
83
84const failed = (cwd: string, error: unknown, baseMode: Snapshot['baseMode']): Snapshot => ({
85 root: cwd, branch: '', baseMode, baseRev: '', baseLabel: '', files: [],
86 error: 'git-failed', message: error instanceof Error ? error.message : String(error),
87})
88
89const sameJson = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)
90
91/** Shows `path` in the preview screen, in `mode` (or the file's default), at `page`. */
92export const openFile = async (io: Io, path: string, mode?: PreviewMode, page = 0, keepScroll = false): Promise<void> => {
93 const snap = await S.pick(io, 'snapshot')
94 if (snap === null || snap.error !== undefined) return
95 const file = snap.files.find(f => f.path === path)
96 const chosen = mode ?? defaultMode(path, file)
97 let next: Preview
98 try {
99 next = await loadPreview(previewDeps(io), snap, path, chosen, page)
100 } catch (error) {
101 next = {
102 path, mode: chosen, modes: modesFor(path, file), kind: 'note', text: '', page: 0, pages: 1,
103 note: `Could not read it: ${error instanceof Error ? error.message : String(error)}`,
104 }
105 }
106 const shown = await S.pick(io, 'preview')
107 if (!sameJson(shown, next)) await S.put(io, 'preview', () => next)
108 await S.put(io, 'screen', () => 'preview')
109 if (!keepScroll) await io.scroll({ to: 'start', in: S.PANE }).catch(() => undefined)
110}
111
112let isRefreshing = false
113let isQueued = false
114
115/**
116 * The working tree as a git tree, untracked files in and ignored ones out, written through an index
117 * of the mod's own (`name`) so the real one, and what is staged, stays as it is. Null outside a repository.
118 */
119const workTree = async (io: Io, cwd: string, name: string): Promise<string | null> => {
120 const paths = await runGit(io, cwd, ['rev-parse', '--git-path', 'index', '--git-path', `git-file-tree-${name}.index`])
121 const [real, own] = paths.stdout.split('\n')
122 if (paths.exitCode !== 0 || !real || !own) return null
123 // Starting from a copy of the real index, git rehashes only the files that changed.
124 await io.run(['cp', real, own], cwd).catch(() => undefined)
125 const env = { GIT_INDEX_FILE: own }
126 if ((await runGit(io, cwd, ['add', '-A'], { env })).exitCode !== 0) return null
127 const tree = await runGit(io, cwd, ['write-tree'], { env })
128
129 return tree.exitCode === 0 ? tree.stdout.trim() : null
130}
131
132/** Keeps the working tree as the prompt view's base: at each prompt, and once when the session starts. */
133export const takePromptBase = async (io: Io, at: 'prompt' | 'session'): Promise<void> => {
134 if (at === 'session' && (await S.pick(io, 'promptBase')) !== null) return
135 const tree = await workTree(io, await io.cwd(), 'prompt')
136 if (tree !== null) await S.put(io, 'promptBase', () => ({ tree, at }))
137}
138
139/** The git root of each folder asked about, so each folder costs one `git rev-parse`. */
140const toplevels = new Map<string, Promise<string | null>>()
141
142/** The root of the git work tree `absolutePath` lies in (a worktree's own), or null outside one. */
143const gitRootOf = async (io: Io, absolutePath: string): Promise<string | null> => {
144 // A file just written may sit in a folder git has not seen: go up to one that answers.
145 let folder = absolutePath.slice(0, absolutePath.lastIndexOf('/'))
146 for (let depth = 0; depth < 6 && folder !== ''; depth += 1) {
147 let found = toplevels.get(folder)
148 if (found === undefined) {
149 found = runGit(io, folder, ['rev-parse', '--show-toplevel']).then(
150 result => (result.exitCode === 0 ? result.stdout.trim() || null : null),
151 () => null,
152 )
153 toplevels.set(folder, found)
154 }
155 const root = await found
156 if (root !== null) return root
157 folder = folder.slice(0, folder.lastIndexOf('/'))
158 }
159
160 return null
161}
162
163/** The root of the session's own work tree, which the main conversation's marks are relative to. */
164export const sessionRoot = async (io: Io): Promise<string> => {
165 const cwd = await io.cwd()
166
167 return (await gitRootOf(io, `${cwd}/.`)) ?? cwd
168}
169
170/** Where the tree reads git: the session's folder, or the root of the subagent in view. */
171const viewRoot = async (io: Io): Promise<string> => {
172 const agentId = await S.pick(io, 'agentView')
173 const root = agentId === null ? null : ((await S.pick(io, 'agents'))[agentId]?.root ?? null)
174
175 return root ?? (await io.cwd())
176}
177
178const refreshOnce = async (io: Io, forcePreview: string | null): Promise<void> => {
179 const mode = await S.pick(io, 'baseMode')
180 const cwd = await viewRoot(io)
181 const commit = await S.pick(io, 'commit')
182 const base = mode === 'prompt' && commit === null ? await S.pick(io, 'promptBase') : null
183 const now = base !== null ? await workTree(io, cwd, 'now') : null
184 const prompt = base !== null && now !== null ? { before: base.tree, now, label: base.at === 'prompt' ? 'your last prompt' : 'the session start' } : null
185 const isThere = await io.stat(cwd).then(() => true, () => false)
186 const next: Snapshot = isThere
187 ? await scan(gitOf(io), io.run, cwd, mode, commit, prompt).catch(error => failed(cwd, error, mode))
188 : { ...failed(cwd, '', mode), error: 'gone', message: `${cwd} was removed.` }
189 const previous = await S.pick(io, 'snapshot')
190 const hasChanged = !sameJson(previous, next)
191 if (hasChanged) await S.put(io, 'snapshot', () => next)
192 // Another branch or work tree (a subagent's): another PR, or none.
193 if (previous !== null && (previous.root !== next.root || previous.branch !== next.branch)) void refreshPr(io).catch(() => undefined)
194
195 if ((await S.pick(io, 'view')) === 'all' && next.error === undefined) {
196 const list = await (commit ? listTree(gitOf(io), next.root, commit.sha) : listAll(gitOf(io), next.root)).catch(() => null)
197 if (list !== null && !sameJson(await S.pick(io, 'allFiles'), list)) await S.put(io, 'allFiles', () => list)
198 }
199
200 // Keep an open preview current with what is on disk now.
201 const shown = await S.pick(io, 'preview')
202 const isPreviewing = (await S.pick(io, 'screen')) === 'preview'
203 if (shown !== null && isPreviewing && (hasChanged || forcePreview === shown.path)) {
204 await openFile(io, shown.path, shown.mode, shown.page, true)
205 }
206}
207
208/** Reads git again; calls that land while one runs fold into one more pass. */
209export const refresh = async (io: Io, forcePreview: string | null = null): Promise<void> => {
210 if (isRefreshing) {
211 isQueued = true
212
213 return
214 }
215 isRefreshing = true
216 try {
217 if ((await S.pick(io, 'snapshot')) === null) await S.put(io, 'isLoading', () => true)
218 let pass = 0
219 do {
220 isQueued = false
221 await refreshOnce(io, pass === 0 ? forcePreview : null)
222 pass += 1
223 } while (isQueued && pass < 3)
224 } finally {
225 isRefreshing = false
226 await S.put(io, 'isLoading', () => false)
227 }
228}
229
230/** Claude wrote `absolutePath`: mark it and refresh the tree. */
231export const noteEdit = async (io: Io, absolutePath: string | null): Promise<void> => {
232 let relative: string | null = null
233 if (absolutePath !== null) {
234 const root = await sessionRoot(io)
235 relative = absolutePath.startsWith(`${root}/`) ? absolutePath.slice(root.length + 1) : null
236 if (relative !== null && relative !== (await S.pick(io, 'touched'))) await S.put(io, 'touched', () => relative)
237 if (relative !== null) await noteActivity(io, 'write', [relative])
238 }
239 await refresh(io, relative)
240}
241
242const rootOf = async (io: Io): Promise<string> => {
243 const snap = await S.pick(io, 'snapshot')
244
245 return snap?.root ?? (await io.cwd())
246}
247
248/** Marks `paths` (root-relative) with what Claude did, opening the folders they sit in. */
249export const noteActivity = async (io: Io, kind: ActivityKind, paths: readonly string[]): Promise<void> => {
250 if (paths.length === 0) return
251 const folders = new Set(paths.flatMap(ancestors))
252 await io.set(state => ({
253 ...state,
254 activity: mergeActivity(state.activity, kind, paths),
255 collapsed: state.collapsed.filter(folder => !folders.has(folder)),
256 expanded: [...new Set([...state.expanded, ...folders])],
257 }))
258}
259
260/** Claude read a file with its Read tool. */
261export const noteRead = async (io: Io, absolutePath: string): Promise<void> => {
262 const path = toRelative(absolutePath, await sessionRoot(io))
263 if (path !== null) await noteActivity(io, 'read', [path])
264}
265
266/** What a shell command did: a commit marks the committed files; a read-only one, the files it named or printed. */
267export const noteShell = async (io: Io, command: string, output: string, isReadOnly: boolean, isError: boolean): Promise<void> => {
268 if (isCommit(command) && !isError) {
269 await refresh(io)
270 const root = await sessionRoot(io)
271 const shown = await gitOf(io)(['show', '--name-only', '--format=', '--no-renames', 'HEAD'], root)
272 if (shown.exitCode === 0) await noteActivity(io, 'commit', shown.stdout.split('\n').map(line => line.trim()).filter(Boolean))
273
274 return
275 }
276 if (isReadOnly) {
277 const root = await sessionRoot(io)
278 const cwd = await io.cwd()
279 const base = cwd.startsWith(`${root}/`) ? `${cwd.slice(root.length + 1)}/` : ''
280 const known = new Set(await listAll(gitOf(io), root).catch(() => []))
281 await noteActivity(io, 'read', pathsIn(command, output, known, root, base))
282
283 return
284 }
285 await noteEdit(io, null)
286}
287
288/**
289 * A subagent read or wrote `absolutePath`: kept under its id, apart from the main conversation's marks.
290 * Its first file, and then each write, says where it works. Resolves the file's root, null outside git.
291 */
292export const noteAgent = async (io: Io, agentId: string, kind: ActivityKind, absolutePath: string): Promise<string | null> => {
293 const root = await gitRootOf(io, absolutePath)
294 if (root === null) return null
295 const main = await sessionRoot(io)
296 await io.set(state => {
297 const work = state.agents[agentId] ?? { root: null, isApart: false, activity: [] }
298 const agentRoot = work.root === null || kind !== 'read' ? root : work.root
299
300 return {
301 ...state,
302 agents: { ...state.agents, [agentId]: { root: agentRoot, isApart: agentRoot !== main, activity: mergeActivity(work.activity, kind, [absolutePath]) } },
303 }
304 })
305 if ((await S.pick(io, 'agentView')) === agentId) await refresh(io)
306
307 return root
308}
309
310/**
311 * The worktree of a subagent the pane has seen no file of (it started before the mod loaded, or works through
312 * the shell alone): Claude Code's own `agent-<id>` folder, else a branch or a folder named as the agent.
313 */
314const worktreeOf = async (io: Io, agentId: string, name: string | null): Promise<string | null> => {
315 const listed = await runGit(io, await sessionRoot(io), ['worktree', 'list', '--porcelain']).catch(() => null)
316 if (listed === null || listed.exitCode !== 0) return null
317 const trees = listed.stdout.split('\n\n').map(entry => ({
318 path: /^worktree (.+)$/m.exec(entry)?.[1] ?? '',
319 branch: /^branch refs\/heads\/(.+)$/m.exec(entry)?.[1] ?? null,
320 }))
321 const folder = (path: string) => path.slice(path.lastIndexOf('/') + 1)
322 const found =
323 trees.find(tree => folder(tree.path) === `agent-${agentId}`) ??
324 (name === null ? undefined : trees.find(tree => tree.branch === name || folder(tree.path) === name))
325
326 return found?.path || null
327}
328
329/** The person switched the transcript in view: the tree follows that subagent's work, or the main conversation's. */
330export const followView = async (io: Io, agentId: string | null, name: string | null = null): Promise<void> => {
331 if ((await S.pick(io, 'agentView')) === agentId) return
332 if (agentId !== null && ((await S.pick(io, 'agents'))[agentId]?.root ?? null) === null) {
333 const root = await worktreeOf(io, agentId, name)
334 const main = await sessionRoot(io)
335 if (root !== null && root !== main) {
336 await io.set(state => ({
337 ...state,
338 agents: { ...state.agents, [agentId]: { root, isApart: true, activity: state.agents[agentId]?.activity ?? [] } },
339 }))
340 }
341 }
342 const before = await viewRoot(io)
343 await S.put(io, 'agentView', () => agentId)
344 if ((await viewRoot(io)) !== before) {
345 // Another work tree: what the pane showed belongs to the old one.
346 await io.set(state => ({
347 ...state,
348 screen: 'tree',
349 preview: null,
350 commit: null,
351 log: null,
352 allFiles: null,
353 git: { ...S.GIT_INITIAL, hasGh: state.git.hasGh, web: state.git.web },
354 }))
355 }
356 await refresh(io)
357}
358
359/** A new prompt: what Claude did before it is no longer news. */
360export const clearActivity = async (io: Io): Promise<void> => {
361 if ((await S.pick(io, 'activity')).length > 0) await S.put(io, 'activity', () => [])
362}
363
364/** Hands a file or a URL to the system: `open` on macOS, `xdg-open` on Linux. */
365const openExternal = async (io: Io, target: string): Promise<boolean> => {
366 for (const opener of ['open', 'xdg-open']) {
367 const result = await io.run([opener, target]).catch(() => null)
368 if (result !== null && result.exitCode === 0) return true
369 }
370
371 return false
372}
373
374/** Opens `path` (root-relative) in the app the system picks for it. */
375export const openInApp = async (io: Io, path: string): Promise<void> => {
376 const isOpened = await openExternal(io, `${await rootOf(io)}/${path}`)
377 io.toast(isOpened ? `Opened ${path.slice(path.lastIndexOf('/') + 1)}` : 'Could not open it: no app is set for this file')
378}
379
380/**
381 * Names a file or folder in the prompt, as an `@` mention Claude Code reads when the prompt is sent. From the open
382 * file, the lines selected in it narrow the mention to those lines (`@src/a.ts#L12-20`); a selection the file no
383 * longer has (removed lines, a past commit) goes in quoted instead.
384 */
385const FENCE = '```'
386
387/** Keeps the mouse selection in the state while a file is open, so Mention can say what it would name. */
388export const watchSelection = async (io: Io): Promise<void> => {
389 const state = await io.get()
390 if (!state.isOpen || state.screen !== 'preview') return
391 const selected = await io.selection()
392 if (selected !== state.selected) await S.put(io, 'selected', () => selected)
393}
394
395export const mention = async (io: Io, path: string, fromPreview = false): Promise<void> => {
396 const snap = await S.pick(io, 'snapshot')
397 const root = snap?.root ?? (await io.cwd())
398 const cwd = await io.cwd()
399 const file = snap?.files.find(entry => entry.path === path)
400 const preview = fromPreview ? await S.pick(io, 'preview') : null
401 const selected = preview?.path === path ? await io.selection() : null
402 const picked = preview !== null && selected !== null ? pick(preview, selected) : null
403 let text = mentionOf(`${root}/${path}`, cwd)
404 let what = path
405 if (picked !== null && 'diff' in picked) {
406 text = `${text}, these lines of its diff:\n${FENCE}diff\n${picked.diff}\n${FENCE}\n`
407 what = 'the selected diff lines'
408 } else if (picked !== null && (snap?.commit !== undefined || file?.status === 'deleted')) {
409 // Lines the file on disk does not have: a past commit's, a deleted file's.
410 const lines = picked.from === picked.to ? `line ${picked.from}` : `lines ${picked.from}-${picked.to}`
411 const source = snap?.commit === undefined ? 'before it was deleted' : `as of commit ${snap.commit.short}`
412 text = `${text} ${source}, ${lines}:\n${FENCE}\n${picked.text}\n${FENCE}\n`
413 what = `the selected ${lines}`
414 } else if (picked !== null) {
415 text = mentionOf(`${root}/${path}`, cwd, picked)
416 what = picked.from === picked.to ? `line ${picked.from}` : `lines ${picked.from}-${picked.to}`
417 }
418 const box = await io.promptBox()
419 const before = box.text.slice(0, box.cursor)
420 const after = box.text.slice(box.cursor)
421 // A space apart from the words around it; a quote ends on its own line already.
422 const lead = before === '' || /\s$/.test(before) ? '' : ' '
423 const trail = text.endsWith('\n') || /^\s/.test(after) ? '' : ' '
424 const isInserted = await io.insert(`${lead}${text}${trail}`)
425 io.toast(isInserted ? `Mentioned ${what} in the prompt` : 'The prompt box is not available')
426}
427
428export const openUrl = async (io: Io, url: string): Promise<void> => {
429 if (!(await openExternal(io, url))) io.toast('Could not open the browser')
430}
431
432// Git operations ------------------------------------------------------------------------
433
434/** Network operations may take this long before they are stopped. */
435const NETWORK_MS = 120_000
436
437const putGit = (io: Io, change: (git: GitUi) => GitUi) => S.put(io, 'git', change)
438
439/** Runs git for an operation: no prompt can wait for an answer nobody can give. */
440const runGit = (io: Io, root: string, args: string[], init: RunInit = {}): Promise<RunResult> =>
441 io.run(['git', '-c', 'core.quotepath=off', '-c', 'color.ui=never', ...args], root, {
442 ...init,
443 env: { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', ...init.env },
444 })
445
446/** A command's outcome: `okText` (or its own first line) when it worked, git's words when it did not. */
447const outcome = (result: RunResult, okText: string, useOutput = false): Outcome =>
448 result.exitCode === 0
449 ? outcomeOf(true, useOutput ? result.stdout : '', okText)
450 : outcomeOf(false, `${result.stderr}\n${result.stdout}`, `git exited with ${result.exitCode}`)
451
452/** Runs one operation at a time: its outcome on the status line, the tree read again after. */
453const operate = async (io: Io, busy: string, work: (root: string) => Promise<Outcome>): Promise<boolean> => {
454 if ((await S.pick(io, 'git')).busy !== null) return false
455 await putGit(io, git => ({ ...git, busy, confirm: null }))
456 let result: Outcome
457 try {
458 result = await work(await rootOf(io))
459 } catch (error) {
460 result = { ok: false, text: error instanceof Error ? error.message : String(error) }
461 }
462 await putGit(io, git => ({ ...git, busy: null, notice: result }))
463 await refresh(io)
464 // The history marks what is pushed: a push, pull or undo there changes it.
465 if ((await S.pick(io, 'screen')) === 'log') await readLog(io)
466
467 return result.ok
468}
469
470/** The first press of a destructive action arms it; a second within CONFIRM_MS goes ahead. */
471const confirmed = async (io: Io, key: string): Promise<boolean> => {
472 const now = await io.now()
473 const { confirm } = await S.pick(io, 'git')
474 if (confirm !== null && confirm.key === key && now - confirm.at < CONFIRM_MS) return true
475 await putGit(io, git => ({ ...git, confirm: { key, at: now } }))
476
477 return false
478}
479
480/** Disarms a destructive press nobody repeated (the poll calls it). */
481export const expireConfirm = async (io: Io): Promise<void> => {
482 const { confirm } = await S.pick(io, 'git')
483 if (confirm !== null && (await io.now()) - confirm.at >= CONFIRM_MS) await putGit(io, git => ({ ...git, confirm: null }))
484}
485
486const describe = (paths: readonly string[]): string =>
487 paths.length === 1 ? (paths[0] === '.' ? 'all changes' : (paths[0] ?? '')) : `${paths.length} paths`
488
489/** Stages files or folders (root-relative); new files are added, deleted ones removed. */
490export const stage = (io: Io, paths: readonly string[]): Promise<boolean> =>
491 operate(io, 'Staging…', async root => outcome(await runGit(io, root, ['add', '-A', '--', ...paths]), `Staged ${describe(paths)}`))
492
493export const unstage = (io: Io, paths: readonly string[]): Promise<boolean> =>
494 operate(io, 'Unstaging…', async root => {
495 const hasHead = (await S.pick(io, 'snapshot'))?.baseRev !== EMPTY_TREE
496 const args = hasHead ? ['restore', '--staged', '--', ...paths] : ['rm', '--cached', '-r', '-q', '--', ...paths]
497
498 return outcome(await runGit(io, root, args), `Unstaged ${describe(paths)}`)
499 })
500
501export const stageFile = (io: Io, file: ChangedFile) => stage(io, pathsOf(file))
502export const unstageFile = (io: Io, file: ChangedFile) => unstage(io, pathsOf(file))
503
504/** Throws away a file's changes, back to HEAD, on a second press. */
505export const discard = async (io: Io, file: ChangedFile): Promise<void> => {
506 if (!(await confirmed(io, `discard:${file.path}`))) return
507 const isDone = await operate(io, 'Discarding…', async root => {
508 for (const args of discardCommands(file)) {
509 const result = await runGit(io, root, args)
510 if (result.exitCode !== 0) return outcome(result, '')
511 }
512
513 return { ok: true, text: `Discarded the changes to ${file.path}` }
514 })
515 if (isDone) await back(io)
516}
517
518export const setMessage = (io: Io, message: string) => putGit(io, git => ({ ...git, message }))
519
520/** Amend on: the message starts as the last commit's, when none is written yet. */
521export const toggleAmend = async (io: Io): Promise<void> => {
522 const { amend, message } = await S.pick(io, 'git')
523 let next = message
524 if (!amend && message.trim() === '') {
525 const last = await runGit(io, await rootOf(io), ['log', '-1', '--format=%B']).catch(() => null)
526 if (last !== null && last.exitCode === 0) next = last.stdout.trim()
527 }
528 await putGit(io, git => ({ ...git, amend: !amend, message: next }))
529}
530
531/** Why the session's model wrote no message, in words for the status line. */
532const NO_MESSAGE: Record<string, string> = {
533 'nothing-to-fork': 'Claude has not answered yet in this session: there is no conversation to write the message from.',
534 'empty-reply': 'Claude replied with nothing. Try again.',
535 aborted: 'Writing the message was stopped.',
536}
537
538/** Asks Claude, over this conversation, for the message of what is staged, and puts it in the field to edit. */
539export const writeMessage = async (io: Io): Promise<void> => {
540 const { amend } = await S.pick(io, 'git')
541 const staged = ((await S.pick(io, 'snapshot'))?.files ?? []).filter(file => file.staged)
542 if (staged.length === 0 && !amend) {
543 await putGit(io, git => ({ ...git, notice: { ok: false, text: 'Stage the files to commit first.' } }))
544 return
545 }
546 await operate(io, 'Claude is writing the message…', async root => {
547 // An amend's message covers the whole commit it replaces: the staged changes on top of HEAD's parent.
548 const base = amend ? ['HEAD^'] : []
549 const [stat, diff, log, last] = await Promise.all([
550 runGit(io, root, ['diff', '--cached', '--stat', ...base]),
551 runGit(io, root, ['diff', '--cached', ...base]),
552 runGit(io, root, ['log', '-8', '--format=%s']),
553 amend ? runGit(io, root, ['log', '-1', '--format=%B']) : Promise.resolve(null),
554 ])
555 if (diff.exitCode !== 0) return outcome(diff, '')
556 const prompt = messagePrompt({
557 stat: stat.stdout,
558 diff: diff.stdout,
559 subjects: log.exitCode === 0 ? log.stdout.split('\n').filter(line => line.trim() !== '') : [],
560 amend: last !== null && last.exitCode === 0 ? last.stdout.trim() : null,
561 })
562 const reply = await io.fork(prompt)
563 if ('reason' in reply) return { ok: false, text: NO_MESSAGE[reply.reason] ?? `Claude could not write the message (${reply.reason}).` }
564 const message = cleanMessage(reply.text)
565 if (message === '') return { ok: false, text: NO_MESSAGE['empty-reply'] ?? '' }
566 await putGit(io, git => ({ ...git, message }))
567
568 return { ok: true, text: 'Claude wrote the message. Edit it, then commit.' }
569 })
570}
571
572/** Commits what is staged with the written message; then pushes, for Commit & push. */
573export const commit = async (io: Io, thenPush = false): Promise<void> => {
574 const { message, amend } = await S.pick(io, 'git')
575 const staged = ((await S.pick(io, 'snapshot'))?.files ?? []).filter(file => file.staged)
576 if (message.trim() === '') {
577 await putGit(io, git => ({ ...git, notice: { ok: false, text: 'Write a commit message first.' } }))
578 return
579 }
580 if (staged.length === 0 && !amend) {
581 await putGit(io, git => ({ ...git, notice: { ok: false, text: 'Stage the files to commit first.' } }))
582 return
583 }
584 const isDone = await operate(io, 'Committing…', async root => {
585 const args = amend ? ['commit', '--amend', '-F', '-'] : ['commit', '-F', '-']
586 const result = await runGit(io, root, args, { stdin: message.trim() + '\n' })
587 if (result.exitCode !== 0) return outcome(result, '')
588 const head = await runGit(io, root, ['log', '-1', '--format=%h %s'])
589
590 return { ok: true, text: `${amend ? 'Amended' : 'Committed'} ${head.stdout.trim()}` }
591 })
592 if (!isDone) return
593 await putGit(io, git => ({ ...git, message: '', amend: false }))
594 if (thenPush) await push(io)
595}
596
597/** The arguments of a push: a branch without an upstream gets one on the first remote. */
598const pushArgs = async (io: Io, root: string, force: boolean): Promise<string[] | Outcome> => {
599 const snap = await S.pick(io, 'snapshot')
600 if (snap?.upstream !== undefined) return force ? ['push', '--force-with-lease', '--force-if-includes'] : ['push']
601 const remote = await remoteOf(io, root)
602 if (remote === undefined) return { ok: false, text: 'This repository has no remote to push to.' }
603
604 return ['push', '-u', remote, 'HEAD']
605}
606
607/** Pushes the branch; a force push (with lease) on a second press. */
608export const push = async (io: Io, force = false): Promise<void> => {
609 if (force && !(await confirmed(io, 'force'))) return
610 const isDone = await operate(io, force ? 'Force pushing…' : 'Pushing…', async root => {
611 const args = await pushArgs(io, root, force)
612 if (!Array.isArray(args)) return args
613 const snap = await S.pick(io, 'snapshot')
614
615 return outcome(await runGit(io, root, args, { timeoutMs: NETWORK_MS }), `${force ? 'Force pushed' : 'Pushed'} ${snap?.branch ?? ''}`.trim())
616 })
617 if (isDone) await refreshPr(io)
618}
619
620/** Pulls fast-forward only: a diverged branch is left for the person to settle. */
621export const pull = (io: Io) =>
622 operate(io, 'Pulling…', async root => outcome(await runGit(io, root, ['pull', '--ff-only'], { timeoutMs: NETWORK_MS }), 'Pulled', true))
623
624export const fetch = (io: Io) =>
625 operate(io, 'Fetching…', async root => outcome(await runGit(io, root, ['fetch'], { timeoutMs: NETWORK_MS }), 'Fetched'))
626
627/** Undoes the last (unpushed) commit on a second press; its changes stay staged. */
628export const undoCommit = async (io: Io): Promise<void> => {
629 if (!(await confirmed(io, 'undo'))) return
630 await operate(io, 'Undoing…', async root =>
631 outcome(await runGit(io, root, ['reset', '--soft', 'HEAD~1']), 'Undid the last commit. Its changes are staged.'),
632 )
633}
634
635// Pull requests -------------------------------------------------------------------------
636
637/** The remote a branch without an upstream pushes to: origin, else the first. */
638const remoteOf = async (io: Io, root: string): Promise<string | undefined> => {
639 const remotes = (await runGit(io, root, ['remote'])).stdout.split('\n').map(r => r.trim()).filter(Boolean)
640
641 return remotes.includes('origin') ? 'origin' : remotes[0]
642}
643
644/** Asks once whether `gh` is there and signed in, where the repository's web page is, and which branch PRs go to. */
645export const checkGh = async (io: Io): Promise<void> => {
646 const known = await S.pick(io, 'git')
647 // A pane state from before `web` existed lacks it: ask again.
648 if (known.hasGh !== null && known.web !== undefined) return
649 const root = await rootOf(io)
650 const auth = await io.run(['gh', 'auth', 'status'], root, { timeoutMs: 15_000 }).catch(() => null)
651 const hasGh = auth !== null && auth.exitCode === 0
652 const remote = await remoteOf(io, root)
653 const fetchUrl = remote === undefined ? '' : (await runGit(io, root, ['remote', 'get-url', remote])).stdout
654 const web = webUrlOf(fetchUrl)
655 const target = await defaultBranch(gitOf(io), root).catch(() => null)
656 await putGit(io, git => ({
657 ...git,
658 hasGh,
659 // A GitHub Enterprise host is GitHub only when gh says so (refreshPr drops it otherwise).
660 web: web !== null && (web.startsWith('https://github.com/') || hasGh) ? web : null,
661 base: target === null ? null : target.replace(/^origin\//, ''),
662 }))
663 await refreshPr(io)
664}
665
666/** Reads the branch's PR, when `gh` can: on opening the pane and after a push. */
667export const refreshPr = async (io: Io): Promise<void> => {
668 if ((await S.pick(io, 'git')).hasGh !== true) return
669 const view = await io.run(['gh', 'pr', 'view', '--json', 'number,url,state,isDraft'], await rootOf(io), { timeoutMs: 20_000 }).catch(() => null)
670 const pr = view !== null && view.exitCode === 0 ? parsePrView(view.stdout) : null
671 // gh answers this when no remote is on GitHub: no PR can be made here.
672 const isGithub = view === null || !/none of the git remotes/i.test(view.stderr)
673 await putGit(io, git => ({ ...git, pr, hasGh: isGithub, web: isGithub ? git.web : null }))
674}
675
676/**
677 * Pushes the branch when the remote lacks it or is behind, then opens GitHub's page for a new PR in the browser:
678 * GitHub picks the base (the repository's default branch), the template, reviewers and draft.
679 */
680export const openPrPage = async (io: Io): Promise<void> => {
681 const web = (await S.pick(io, 'git')).web
682 if (!web) return
683 await operate(io, 'Opening the PR page…', async root => {
684 const snap = await S.pick(io, 'snapshot')
685 if (snap?.upstream === undefined || (snap.ahead ?? 0) > 0) {
686 const args = await pushArgs(io, root, false)
687 if (!Array.isArray(args)) return args
688 const pushed = await runGit(io, root, args, { timeoutMs: NETWORK_MS })
689 if (pushed.exitCode !== 0) return outcome(pushed, '')
690 }
691 // The branch's name on the remote: its upstream's, which a push just set when it had none.
692 const upstream = (await runGit(io, root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).stdout.trim()
693 const remote = await remoteOf(io, root)
694 const branch = remote !== undefined && upstream.startsWith(`${remote}/`) ? upstream.slice(remote.length + 1) : (snap?.branch ?? '')
695 const url = compareUrl(web, branch)
696
697 return (await openExternal(io, url)) ? { ok: true, text: 'Opened the new PR page in the browser' } : { ok: false, text: 'Could not open the browser', detail: url }
698 })
699}
700
701/** Opens the history screen and reads the recent commits. */
702export const showLog = async (io: Io): Promise<void> => {
703 await S.put(io, 'screen', () => 'log')
704 await io.scroll({ to: 'start', in: S.PANE }).catch(() => undefined)
705 await readLog(io)
706 await refreshPr(io)
707}
708
709const readLog = async (io: Io): Promise<void> => {
710 const log = await listCommits(gitOf(io), await rootOf(io)).catch(() => [])
711 await S.put(io, 'log', () => log)
712}
713
714/** Shows one past commit in the tree, or the working changes again (null). */
715export const showCommit = async (io: Io, commit: CommitInfo | null): Promise<void> => {
716 await io.set(state => ({ ...state, commit, preview: null, screen: 'tree', allFiles: null }))
717 await io.scroll({ to: 'start', in: S.PANE }).catch(() => undefined)
718 await refresh(io)
719}
720
721/** Opens the filter with the cursor in it, or closes it. */
722export const toggleFilter = async (io: Io): Promise<void> => {
723 const filter = await S.put(io, 'filter', value => (value === null ? '' : null))
724 if (filter !== null) await io.focus({ requestId: S.PANE, key: 'filter-input' }).catch(() => undefined)
725}
726
727export const back = async (io: Io): Promise<void> => {
728 const shown = await S.pick(io, 'preview')
729 await S.put(io, 'screen', () => 'tree')
730 if (shown === null) return
731 const key = `row:${shown.path}`
732 await io.scroll({ to: { key }, in: S.PANE, block: 'center' }).catch(() => undefined)
733 await io.focus({ requestId: S.PANE, key }).catch(() => undefined)
734}
735
736/** Moves to the next (1) or previous (-1) changed file in review order. */
737export const step = async (io: Io, delta: 1 | -1): Promise<void> => {
738 const snap = await S.pick(io, 'snapshot')
739 if (snap === null) return
740 const order = reviewOrder(snap.files)
741 if (order.length === 0) return
742 const shown = await S.pick(io, 'preview')
743 const at = shown === null ? -1 : order.indexOf(shown.path)
744 const index = at < 0 ? (delta === 1 ? 0 : order.length - 1) : Math.min(Math.max(at + delta, 0), order.length - 1)
745 const path = order[index]
746 if (path === undefined || (at === index && shown !== null)) return
747 const file = snap.files.find(f => f.path === path)
748 const keep = shown !== null && modesFor(path, file).includes(shown.mode) ? shown.mode : undefined
749 await openFile(io, path, keep)
750}
751
752export const toggleDir = async (io: Io, path: string, isOpenNow: boolean): Promise<void> => {
753 const without = (list: string[]) => list.filter(p => p !== path)
754 await io.set(state => ({
755 ...state,
756 collapsed: isOpenNow ? [...without(state.collapsed), path] : without(state.collapsed),
757 expanded: isOpenNow ? without(state.expanded) : [...without(state.expanded), path],
758 }))
759}
760
761export const toggleView = async (io: Io): Promise<void> => {
762 const next = (await S.pick(io, 'view')) === 'all' ? 'changes' : 'all'
763 await S.put(io, 'view', () => next)
764 await savePrefs(io)
765 if (next === 'all') await refresh(io)
766}
767
768/** The order v walks the comparisons in. */
769export const BASE_ORDER: readonly BaseMode[] = ['head', 'branch', 'prompt']
770
771export const toggleBase = async (io: Io): Promise<void> => {
772 await S.put(io, 'baseMode', mode => BASE_ORDER[(BASE_ORDER.indexOf(mode) + 1) % BASE_ORDER.length] ?? 'head')
773 await savePrefs(io)
774 await refresh(io)
775}
776
777export const openPane = async (io: Io): Promise<boolean> => {
778 const opened = await io.open({ id: S.PANE, title: 'Files', focus: true, columns: 64, rows: 26 })
779 await S.put(io, 'isOpen', () => opened.isPlaced)
780 if (opened.isPlaced) void refresh(io).then(() => checkGh(io)).catch(() => undefined)
781
782 return opened.isPlaced
783}
784
785export const closePane = async (io: Io): Promise<void> => {
786 await io.close(S.PANE).catch(() => undefined)
787 await S.put(io, 'isOpen', () => false)
788}
789hooks/state.ts 46 lines1import type { BaseMode, GitUi, UiState, View } from '../types'
2
3export const PANE = 'files'
4
5export const GIT_INITIAL: GitUi = { busy: null, notice: null, confirm: null, message: '', amend: false, hasGh: null, pr: null, web: null, base: null }
6
7export const INITIAL: UiState = {
8 snapshot: null,
9 allFiles: null,
10 view: 'changes',
11 baseMode: 'head',
12 promptBase: null,
13 collapsed: [],
14 expanded: [],
15 screen: 'tree',
16 commit: null,
17 log: null,
18 git: GIT_INITIAL,
19 preview: null,
20 touched: null,
21 activity: [],
22 agents: {},
23 agentView: null,
24 selected: null,
25 filter: null,
26 isOpen: false,
27 isLoading: false,
28}
29
30/** The state half of the engine's closures (see `Io` in actions.ts). */
31export type StateIo = {
32 get: () => Promise<UiState>
33 set: (change: (state: UiState) => UiState) => Promise<UiState>
34}
35
36/** Reads one field of the state. */
37export const pick = async <K extends keyof UiState>(io: StateIo, key: K): Promise<UiState[K]> => (await io.get())[key]
38
39/** Writes one field of the state from its current value; resolves the new value. */
40export const put = async <K extends keyof UiState>(io: StateIo, key: K, change: (value: UiState[K]) => UiState[K]): Promise<UiState[K]> =>
41 (await io.set(state => ({ ...state, [key]: change(state[key]) })))[key]
42
43/** Preferences kept across sessions in `$.store`. */
44export const PREFS_KEY = 'prefs'
45export type Prefs = { view?: View; baseMode?: BaseMode }
46hooks/view.tsx 930 lines1import type { ElementTable, RenderElement, RenderInput } from 'claude-code'
2
3import type { Activity, ActivityKind, AgentWork, ChangedFile, ColoredSpan, CommitInfo, FileStatus, Preview, PreviewMode, Snapshot } from '../types'
4import * as A from './actions'
5import type { Io } from './actions'
6import { displayWidth, layoutTable, parseBlocks } from './markdown'
7import type { Span } from './markdown'
8import * as S from './state'
9import { ancestors, toRelative } from './activity'
10import { pick } from './mention'
11import { prLabel } from './ops'
12import { buildTree, flatten, matches, reviewOrder } from './tree'
13import type { Row } from './tree'
14
15/** A row's stage or unstage button, at the left of the row. */
16type Gutter = { sign: '+' | '−'; paths: string[] } | null
17
18/** What a drawing works from: the engine's closures (reads subscribing this drawing), the surface's elements, the input. */
19export type Ctx = {
20 io: Io
21 t: ElementTable
22 e: RenderInput
23 /** What the subagent in view is doing, as its Agent call described it; null or absent for the main conversation. */
24 agentLabel?: string | null
25}
26
27/** Rows drawn at most, so a huge expanded tree stays inside one drawing. */
28const MAX_ROWS = 1500
29
30const STATUS: Record<FileStatus, { letter: string; color: string; label: string }> = {
31 modified: { letter: 'M', color: 'warning', label: 'modified' },
32 added: { letter: 'A', color: 'success', label: 'added' },
33 untracked: { letter: 'U', color: 'success', label: 'new' },
34 deleted: { letter: 'D', color: 'error', label: 'deleted' },
35 renamed: { letter: 'R', color: 'suggestion', label: 'renamed' },
36 conflict: { letter: '!', color: 'error', label: 'conflict' },
37}
38
39/** What Claude did to a file, by color: reads and searches purple, writes orange, commits green. */
40const ACTIVITY: Record<ActivityKind, { color: string }> = {
41 read: { color: 'merged' },
42 write: { color: 'claude' },
43 commit: { color: 'success' },
44}
45
46/** The activity marks the rows draw: each file's latest, and the latest of all. */
47type Marks = { byPath: Map<string, Activity>; latest: number; all: readonly Activity[] }
48
49/** ● on the latest thing Claude did, • on the rest. */
50const mark = (c: Ctx, entry: Activity | undefined, latest: number) => {
51 const { Text } = c.t
52 if (entry === undefined) return ''
53
54 return <Text color={ACTIVITY[entry.kind].color} bold={entry.seq === latest}>{entry.seq === latest ? ' ●' : ' •'}</Text>
55}
56
57const MODE_LABEL: Record<PreviewMode, { label: string; hotkey: string }> = {
58 diff: { label: 'Diff', hotkey: 'd' },
59 source: { label: 'Source', hotkey: 's' },
60 rendered: { label: 'Rendered', hotkey: 'm' },
61}
62
63const basename = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
64const dirname = (path: string): string => path.slice(0, path.lastIndexOf('/') + 1)
65
66const totals = (files: readonly ChangedFile[]) => {
67 const byStatus = new Map<FileStatus, number>()
68 let added = 0
69 let removed = 0
70 for (const file of files) {
71 byStatus.set(file.status, (byStatus.get(file.status) ?? 0) + 1)
72 added += file.added ?? 0
73 removed += file.removed ?? 0
74 }
75
76 return { byStatus, added, removed }
77}
78
79const ORDER: FileStatus[] = ['modified', 'added', 'untracked', 'renamed', 'deleted', 'conflict']
80
81/** `3M 2U 1D +120 −30`, each part in its status color: the Text children of a Button or Box. */
82const summaryParts = (c: Ctx, files: readonly ChangedFile[]) => {
83 const { Text } = c.t
84 const { byStatus, added, removed } = totals(files)
85 const parts = ORDER.filter(status => byStatus.has(status)).map(status => (
86 <Text color={STATUS[status].color}>{` ${byStatus.get(status)}${STATUS[status].letter}`}</Text>
87 ))
88 if (added > 0) parts.push(<Text color="success">{` +${added}`}</Text>)
89 if (removed > 0) parts.push(<Text color="error">{` −${removed}`}</Text>)
90
91 return parts
92}
93
94const stats = (c: Ctx, file: ChangedFile) => {
95 const { Text } = c.t
96 if (file.isBinary) return [<Text dimColor> binary</Text>]
97 const parts = []
98 if ((file.added ?? 0) > 0) parts.push(<Text color="success">{` +${file.added}`}</Text>)
99 if ((file.removed ?? 0) > 0) parts.push(<Text color="error">{` −${file.removed}`}</Text>)
100
101 return parts
102}
103
104/** The row with its stage (+) or unstage (−) button before it; a row that has neither keeps the column. */
105const withGutter = (c: Ctx, row: Row, element: RenderElement, gutter: Gutter | undefined) => {
106 const { Box, Button, Text } = c.t
107 if (gutter === undefined) return element
108 if (gutter === null) return <Box key={`line:${row.key}`}><Text>{' '}</Text>{element}</Box>
109 const isStage = gutter.sign === '+'
110
111 return (
112 <Box key={`line:${row.key}`}>
113 <Button key={`${isStage ? 'stage' : 'unstage'}:${row.path}`} plain onPress={() => (isStage ? A.stage(c.io, gutter.paths) : A.unstage(c.io, gutter.paths))}>
114 <Text dimColor>{gutter.sign}</Text>
115 </Button>
116 <Text> </Text>
117 {element}
118 </Box>
119 )
120}
121
122const rowElement = (c: Ctx, row: Row, selected: string | null, marks: Marks, isAll: boolean, gutter?: Gutter) =>
123 withGutter(c, row, withMention(c, row, rowButton(c, row, selected, marks, isAll)), gutter)
124
125/** What Mention would name: the selected lines when the open page has them, else the file. */
126const mentionLabel = (shown: Preview, selected: string | null): string => {
127 const picked = selected === null ? null : pick(shown, selected)
128 if (picked === null) return '@ File'
129 if ('diff' in picked) return '@ Selected lines'
130
131 return picked.from === picked.to ? `@ Line ${picked.from}` : `@ Lines ${picked.from}–${picked.to}`
132}
133
134/** A row with an `@` after it, faint until the row is hovered, that names the file or folder in the prompt; a deleted file has nothing to read. */
135const withMention = (c: Ctx, row: Row, element: RenderElement) => {
136 const { Box, Button, Text } = c.t
137 if (row.file?.status === 'deleted') return element
138
139 return (
140 <Box key={`entry:${row.key}`}>
141 {element}
142 <Button key={`mention:${row.path}`} plain dimColor hover={{ dimColor: false, color: 'claude', bold: true }} onPress={() => A.mention(c.io, row.path)}>
143 {' @'}
144 </Button>
145 </Box>
146 )
147}
148
149const rowButton = (c: Ctx, row: Row, selected: string | null, marks: Marks, isAll: boolean) => {
150 const { Button, Text } = c.t
151 const indent = ' '.repeat(row.depth)
152
153 if (row.isDir) {
154 const showCount = row.changes > 0 && (!row.isOpen || isAll)
155
156 return (
157 <Button key={row.key} plain onPress={() => A.toggleDir(c.io, row.path, row.isOpen)}>
158 {indent}
159 <Text color="subtle">{row.isOpen ? '▾ ' : '▸ '}</Text>
160 <Text bold={row.changes > 0}>{row.label}</Text>
161 {showCount ? <Text color="warning">{` ${row.changes}`}</Text> : ''}
162 {row.isOpen ? '' : mark(c, latestIn(marks.all, row.path), marks.latest)}
163 </Button>
164 )
165 }
166
167 const status = row.file ? STATUS[row.file.status] : null
168 const isDeleted = row.file?.status === 'deleted'
169
170 return (
171 <Button key={row.key} plain onPress={() => A.openFile(c.io, row.path)}>
172 {indent}
173 <Text color={status?.color ?? 'subtle'} bold>{status ? `${status.letter} ` : ' '}</Text>
174 <Text
175 {...(status ? { color: status.color } : {})}
176 bold={row.path === selected}
177 strikethrough={isDeleted}
178 dimColor={isDeleted}
179 >
180 {row.label}
181 </Text>
182 {...(row.file ? stats(c, row.file) : [])}
183 {mark(c, marks.byPath.get(row.path), marks.latest)}
184 </Button>
185 )
186}
187
188/** The latest activity inside the folder `path` (ends in `/`), for a closed folder's row. */
189const latestIn = (activity: readonly Activity[], path: string): Activity | undefined => {
190 let found: Activity | undefined
191 for (const entry of activity) if (entry.path.startsWith(path) && (found === undefined || entry.seq > found.seq)) found = entry
192
193 return found
194}
195
196/** `feature/x → origin/feature/x ↑2 ↓1`: the branch, where it pushes, and how far apart they are. */
197const branchLine = (c: Ctx, snap: { branch: string; upstream?: string; ahead?: number; behind?: number }) => {
198 const { Text } = c.t
199 const parts = [<Text bold>{snap.branch}</Text>]
200 if (snap.upstream === undefined) return parts
201 parts.push(<Text dimColor>{` → ${snap.upstream}`}</Text>)
202 const ahead = snap.ahead ?? 0
203 const behind = snap.behind ?? 0
204 if (ahead === 0 && behind === 0) parts.push(<Text dimColor> ✓ up to date</Text>)
205 if (ahead > 0) parts.push(<Text color="warning">{` ↑${ahead}`}</Text>)
206 if (behind > 0) parts.push(<Text color="suggestion">{` ↓${behind}`}</Text>)
207
208 return parts
209}
210
211/** The git operations work on the working changes of the current branch: not on a past commit, not on the whole branch. */
212const isGitMode = async (c: Ctx, snap: Snapshot): Promise<boolean> =>
213 snap.commit === undefined && snap.error === undefined && (await S.pick(c.io, 'baseMode')) === 'head' && (await sharedAgent(c)) === null
214
215/** The subagent in view, when it works in the session's own tree: the tree shows only its files, with no git operations. */
216const sharedAgent = async (c: Ctx): Promise<AgentWork | null> => {
217 const agentId = await S.pick(c.io, 'agentView')
218 if (agentId === null) return null
219 const work = (await S.pick(c.io, 'agents'))[agentId] ?? { root: null, isApart: false, activity: [] }
220
221 return work.isApart ? null : work
222}
223
224/** A toggle drawn as all its options, the current one bold: `Changed · All`. */
225const choice = (c: Ctx, options: readonly string[], active: number) => {
226 const { Text } = c.t
227
228 return options.flatMap((option, index) => [
229 ...(index > 0 ? [<Text dimColor> · </Text>] : []),
230 index === active ? <Text bold>{option}</Text> : <Text dimColor>{option}</Text>,
231 ])
232}
233
234/** Outside git mode: the keys that lead back to stage, commit and push. */
235const gitHint = (isAll: boolean, isCommit: boolean, baseMode: string): string => {
236 const steps: string[] = []
237 if (isAll) steps.push('a for Changed')
238 if (isCommit) steps.push('v for Working changes')
239 else if (baseMode === 'branch') steps.push('v twice for Uncommitted')
240 else if (baseMode !== 'head') steps.push('v for Uncommitted')
241
242 return `Stage, commit and push: press ${steps.join(', then ')}.`
243}
244
245/** What a destructive button says after its first press. */
246const CONFIRM_TEXT: Record<string, string> = { force: 'Press again to force push (with lease)', undo: 'Press again to undo the last commit' }
247
248/** The line under the toolbar: the running operation, a press to repeat, or how the last one went. */
249const statusLine = async (c: Ctx): Promise<RenderElement | null> => {
250 const { Box, Text, Button } = c.t
251 const git = await S.pick(c.io, 'git')
252 if (git.busy !== null) return <Text dimColor>{git.busy}</Text>
253 if (git.confirm !== null) {
254 const text = CONFIRM_TEXT[git.confirm.key] ?? 'Press x again to discard the changes'
255
256 return <Text color="warning">{text}</Text>
257 }
258 if (git.notice === null) return null
259 const notice = git.notice
260
261 return (
262 <Box flexDirection="column">
263 <Box columnGap={2}>
264 <Text color={notice.ok ? 'success' : 'error'}>{`${notice.ok ? '✓' : '✗'} ${notice.text}`}</Text>
265 <Button key="notice-close" plain onPress={() => S.put(c.io, 'git', g => ({ ...g, notice: null }))}><Text dimColor>✕</Text></Button>
266 </Box>
267 {notice.detail !== undefined ? <Text dimColor>{notice.detail}</Text> : null}
268 </Box>
269 )
270}
271
272/** Why Push cannot run now, or null when it can (or Force push stands in its place). */
273const pushBlocker = (snap: Snapshot, isDetached: boolean, isDiverged: boolean): string | null => {
274 if (isDetached) return 'Push: not on a branch'
275 if (isDiverged) return null
276 if (snap.upstream !== undefined && (snap.ahead ?? 0) === 0) return 'Push: nothing to push, commit first'
277
278 return null
279}
280
281/** Push, pull, fetch, undo and the PR. Push always shows: a dim line says why it cannot run yet. */
282const syncRow = async (c: Ctx, snap: Snapshot): Promise<RenderElement> => {
283 const { Box, Button, Text } = c.t
284 const git = await S.pick(c.io, 'git')
285 const ahead = snap.ahead ?? 0
286 const behind = snap.behind ?? 0
287 const hasUpstream = snap.upstream !== undefined
288 // The scan's names for no branch (a branch name cannot hold a space).
289 const isDetached = snap.branch.startsWith('detached at ') || snap.branch === 'no commits yet' || snap.branch === ''
290 const isDiverged = ahead > 0 && behind > 0
291 const canPr = Boolean(git.web) && git.pr === null && !isDetached && snap.branch !== (git.base ?? 'main')
292 const blocker = pushBlocker(snap, isDetached, isDiverged)
293
294 return (
295 <Box flexWrap="wrap" columnGap={2}>
296 {blocker !== null ? (
297 <Text dimColor>{blocker}</Text>
298 ) : !isDiverged ? (
299 <Button key="push" plain hotkey="p" onPress={() => A.push(c.io)}>{hasUpstream ? 'Push' : 'Push branch'}</Button>
300 ) : null}
301 {/* With lease, on a second press: after an amend or a rebase, or to put the remote back to the local branch. */}
302 {hasUpstream && !isDetached ? <Button key="force-push" plain onPress={() => A.push(c.io, true)}>Force push</Button> : null}
303 {behind > 0 && !isDiverged ? <Button key="pull" plain onPress={() => A.pull(c.io)}>Pull</Button> : null}
304 {hasUpstream ? <Button key="fetch" plain onPress={() => A.fetch(c.io)}>Fetch</Button> : null}
305 {ahead > 0 ? <Button key="undo" plain onPress={() => A.undoCommit(c.io)}>Undo commit</Button> : null}
306 {git.pr !== null ? (
307 <Button key="pr-open" plain onPress={() => A.openUrl(c.io, git.pr?.url ?? '')}>{prLabel(git.pr)}</Button>
308 ) : canPr ? (
309 <Button key="pr-create" plain onPress={() => A.openPrPage(c.io)}>Create PR ↗</Button>
310 ) : null}
311 </Box>
312 )
313}
314
315/** The message and the commit buttons, always; with nothing staged a dim line says how to stage. */
316const commitBox = async (c: Ctx, stagedCount: number): Promise<RenderElement | null> => {
317 const table = c.t
318 const { Box, Button, Text } = table
319 const git = await S.pick(c.io, 'git')
320 if (!('Input' in table)) return null
321 const { Input } = table
322
323 return (
324 <Box flexDirection="column">
325 <Input
326 key="message"
327 label="Message"
328 placeholder="what this commit does"
329 value={git.message}
330 submitLabel="commit"
331 onInput={value => A.setMessage(c.io, value)}
332 onSubmit={async value => {
333 await A.setMessage(c.io, value)
334 await A.commit(c.io)
335 }}
336 />
337 <Box flexWrap="wrap" columnGap={2}>
338 <Button key="write-message" plain hotkey="w" onPress={() => A.writeMessage(c.io)}>Write message</Button>
339 <Button key="commit" plain hotkey="c" onPress={() => A.commit(c.io)}>{git.amend ? 'Amend' : 'Commit'}</Button>
340 <Button key="commit-push" plain onPress={() => A.commit(c.io, true)}>{git.amend ? 'Amend & push' : 'Commit & push'}</Button>
341 <Button key="amend" plain onPress={() => A.toggleAmend(c.io)}>{git.amend ? '[x] Amend last commit' : '[ ] Amend last commit'}</Button>
342 </Box>
343 {stagedCount === 0 && !git.amend ? <Text dimColor>Nothing staged: press + before a file, or Stage all, to choose what to commit.</Text> : null}
344 </Box>
345 )
346}
347
348const renderTree = async (c: Ctx): Promise<RenderElement> => {
349 const table = c.t
350 const { Box, Text, Button } = table
351 const snap = await S.pick(c.io, 'snapshot')
352 const isLoading = await S.pick(c.io, 'isLoading')
353 const isFocused = c.e.component === 'Pane' && c.e.props.isFocused
354
355 if (snap === null) {
356 return <Text dimColor>{isLoading ? 'Reading git…' : 'Nothing read yet.'}</Text>
357 }
358 if (snap.error === 'gone') {
359 return (
360 <Box flexDirection="column">
361 <Text color="warning">This agent's worktree is gone</Text>
362 <Text dimColor>{snap.message ?? ''}</Text>
363 <Text dimColor>Its changes are on its branch, if it committed them. Go back to the main conversation to see the session's files.</Text>
364 </Box>
365 )
366 }
367 if (snap.error !== undefined) {
368 return (
369 <Box flexDirection="column">
370 <Text color="warning">{snap.error === 'not-a-repo' ? 'Not a git repository' : 'git failed'}</Text>
371 <Text dimColor>{snap.message ?? ''}</Text>
372 <Button key="refresh" plain hotkey="r" onPress={() => A.refresh(c.io)}>Try again</Button>
373 </Box>
374 )
375 }
376
377 const view = await S.pick(c.io, 'view')
378 const isAll = view === 'all'
379 const baseMode = await S.pick(c.io, 'baseMode')
380 const filter = await S.pick(c.io, 'filter')
381 // With a subagent in view, its own marks; in the session's own tree, only the files it touched.
382 const agentId = await S.pick(c.io, 'agentView')
383 const agentWork = agentId === null ? null : ((await S.pick(c.io, 'agents'))[agentId] ?? { root: null, isApart: false, activity: [] })
384 const shared = agentWork !== null && !agentWork.isApart ? agentWork : null
385 const activity: Activity[] =
386 agentWork === null
387 ? await S.pick(c.io, 'activity')
388 : agentWork.activity.flatMap(entry => {
389 const path = toRelative(entry.path, snap.root)
390
391 return path === null ? [] : [{ ...entry, path }]
392 })
393 const marks: Marks = {
394 byPath: new Map(activity.map(entry => [entry.path, entry])),
395 latest: activity.reduce((max, entry) => Math.max(max, entry.seq), 0),
396 all: activity,
397 }
398 const shown = await S.pick(c.io, 'preview')
399 const changes = new Map(snap.files.map(f => [f.path, f]))
400
401 // The changes, and every file Claude read, wrote or committed since the prompt.
402 // A past commit shows its own files only.
403 const isCommit = snap.commit !== undefined
404 let paths: string[] = [...new Set([...snap.files.map(f => f.path), ...(isCommit ? [] : activity.map(entry => entry.path))])]
405 if (shared !== null && !isCommit) paths = [...new Set(activity.map(entry => entry.path))]
406 const agentPaths = new Set(paths)
407 const counted = shared !== null && !isCommit ? snap.files.filter(file => agentPaths.has(file.path)) : snap.files
408 if (isAll) paths = [...new Set([...((await S.pick(c.io, 'allFiles')) ?? []), ...paths])]
409 const isFiltering = filter !== null && filter.trim() !== ''
410 if (isFiltering) paths = paths.filter(path => matches(path, filter))
411
412 const activeFolders = new Set(activity.flatMap(entry => ancestors(entry.path)))
413 const collapsed = new Set(await S.pick(c.io, 'collapsed'))
414 const expanded = new Set(await S.pick(c.io, 'expanded'))
415 const options = {
416 // Folders holding changes start open in both views; the rest of the repository starts closed.
417 isOpen: (path: string, count: number) => isFiltering || (!collapsed.has(path) && (count > 0 || activeFolders.has(path) || (isAll && expanded.has(path)))),
418 isCompact: true,
419 }
420
421 // The working changes split in two, as git keeps them: staged, and the rest.
422 const gitMode = !isAll && (await isGitMode(c, snap))
423 const staged = snap.files.filter(file => file.staged)
424 const stagedPaths = new Set(staged.map(file => file.path))
425 const unstagedChanges = new Map(snap.files.filter(file => file.unstaged || !file.staged).map(file => [file.path, file]))
426 const stagedRows = gitMode
427 ? flatten(buildTree(paths.filter(path => stagedPaths.has(path)), new Map(staged.map(file => [file.path, file]))), options).map(row => ({
428 ...row,
429 key: row.key.replace(/^row:/, 'staged:'),
430 }))
431 : []
432 const rows = gitMode
433 ? flatten(buildTree(paths.filter(path => unstagedChanges.has(path) || !changes.has(path)), unstagedChanges), options)
434 : flatten(buildTree(paths, changes), options)
435 const hidden = Math.max(0, stagedRows.length + rows.length - MAX_ROWS)
436 const gutterOf = (row: Row, sign: '+' | '−', section: ReadonlyMap<string, ChangedFile>): Gutter => {
437 if (row.isDir) return row.changes > 0 ? { sign, paths: [row.path] } : null
438 const file = section.get(row.path)
439
440 return file === undefined ? null : { sign, paths: file.status === 'renamed' && file.from && sign === '−' ? [file.from, file.path] : [file.path] }
441 }
442
443 const filterField = (() => {
444 if (filter === null) return null
445 if (!('Input' in table)) return null
446 const { Input } = table
447
448 return (
449 <Box columnGap={1}>
450 <Input
451 key="filter-input"
452 label="Filter"
453 placeholder="type a name, Enter opens the first match"
454 value={filter}
455 autoFocus
456 submitLabel="open"
457 onInput={value => S.put(c.io, 'filter', () => value)}
458 onSubmit={value => {
459 const first = rows.find(row => !row.isDir && matches(row.path, value))
460 if (first) void A.openFile(c.io, first.path)
461 }}
462 />
463 <Button key="filter-clear" plain onPress={() => S.put(c.io, 'filter', () => null)}>✕</Button>
464 </Box>
465 )
466 })()
467
468 let empty: RenderElement | null = null
469 if (rows.length === 0 && stagedRows.length === 0) {
470 empty = shared !== null && !isFiltering && !isCommit ? (
471 <Text dimColor>The pane has seen no file that this agent read or changed.</Text>
472 ) : isFiltering ? (
473 <Text dimColor>No file matches “{filter}”.</Text>
474 ) : isAll ? (
475 <Text dimColor>No files.</Text>
476 ) : isCommit ? (
477 <Text dimColor>No file changes in this commit.</Text>
478 ) : (
479 <Box flexDirection="column">
480 <Text color="success">{snap.baseMode === 'prompt' ? `✓ No changes since ${snap.baseLabel}` : `✓ No changes against ${snap.baseLabel}`}</Text>
481 <Text dimColor>Press a to browse all files, or v to change what the tree compares with.</Text>
482 </Box>
483 )
484 }
485
486 const agentLine =
487 agentWork === null ? null : (
488 <Box flexWrap="wrap">
489 <Text color="claude" bold>{'Agent '}</Text>
490 <Text bold>{c.agentLabel ?? 'subagent'}</Text>
491 <Text dimColor>
492 {agentWork.isApart && agentWork.root !== null ? ` in ${agentWork.root.split('/').slice(-2).join('/')}` : ' the files it read and changed'}
493 </Text>
494 </Box>
495 )
496
497 return (
498 <Box flexDirection="column">
499 {agentLine}
500 <Box flexWrap="wrap">{...branchLine(c, snap)}</Box>
501 <Box flexWrap="wrap">
502 {snap.commit ? <Text>{`${snap.commit.short} ${snap.commit.subject}`}</Text> : <Text dimColor>{snap.baseMode === 'prompt' ? `since ${snap.baseLabel}` : `vs ${snap.baseLabel}`}</Text>}
503 <Text dimColor>{counted.length > 0 ? ` ${counted.length} changed ` : ''}</Text>
504 {...summaryParts(c, counted)}
505 </Box>
506 <Box flexWrap="wrap" columnGap={2}>
507 <Button key="view" plain hotkey="a" onPress={() => A.toggleView(c.io)}>{...choice(c, ['Changed', 'All'], isAll ? 1 : 0)}</Button>
508 {isCommit ? (
509 <Button key="base" plain hotkey="v" onPress={() => A.showCommit(c.io, null)}>Working changes</Button>
510 ) : (
511 <Button key="base" plain hotkey="v" onPress={() => A.toggleBase(c.io)}>{...choice(c, ['Uncommitted', 'Branch', 'Prompt'], A.BASE_ORDER.indexOf(baseMode))}</Button>
512 )}
513 <Button key="history" plain hotkey="h" onPress={() => A.showLog(c.io)}>History</Button>
514 <Button key="filter" plain hotkey="f" onPress={() => A.toggleFilter(c.io)}>Filter</Button>
515 </Box>
516 {filterField}
517 {stagedRows.length > 0 ? (
518 <Box flexDirection="column" marginTop={1}>
519 <Box columnGap={2}>
520 <Text bold>{`Staged ${staged.length}`}</Text>
521 <Button key="unstage-all" plain onPress={() => A.unstage(c.io, staged.flatMap(file => (file.status === 'renamed' && file.from ? [file.from, file.path] : [file.path])))}>
522 Unstage all
523 </Button>
524 </Box>
525 {...stagedRows.slice(0, MAX_ROWS).map(row => rowElement(c, row, shown?.path ?? null, marks, isAll, gutterOf(row, '−', new Map(staged.map(f => [f.path, f])))))}
526 </Box>
527 ) : null}
528 <Box flexDirection="column" marginTop={1}>
529 {gitMode && unstagedChanges.size > 0 ? (
530 <Box columnGap={2}>
531 <Text bold>{`Changes ${unstagedChanges.size}`}</Text>
532 <Button key="stage-all" plain onPress={() => A.stage(c.io, ['.'])}>Stage all</Button>
533 </Box>
534 ) : null}
535 {empty}
536 {...rows
537 .slice(0, Math.max(0, MAX_ROWS - stagedRows.length))
538 .map(row => rowElement(c, row, shown?.path ?? null, marks, isAll, gitMode ? gutterOf(row, '+', unstagedChanges) : undefined))}
539 {hidden > 0 ? <Text dimColor>{`… ${hidden} more rows. Use the filter (f) to narrow.`}</Text> : null}
540 </Box>
541 {/* The git operations last, under the files they act on. */}
542 <Box flexDirection="column" marginTop={1}>
543 {gitMode ? await commitBox(c, staged.length) : null}
544 {gitMode ? (
545 await syncRow(c, snap)
546 ) : (
547 <Text dimColor>{shared !== null ? 'Stage, commit and push: go back to the main conversation.' : gitHint(isAll, isCommit, baseMode)}</Text>
548 )}
549 {gitMode ? await statusLine(c) : null}
550 </Box>
551 {isFocused ? null : <Text dimColor>Click a file to preview. Click the pane (or ctrl+x tab) for the letter keys.</Text>}
552 </Box>
553 )
554}
555
556/** Styled spans as Text pieces. */
557const spanElements = (c: Ctx, spans: readonly Span[]) => {
558 const { Text } = c.t
559
560 return spans.map(span => {
561 const style: { bold?: boolean; italic?: boolean; strikethrough?: boolean; underline?: boolean; dimColor?: boolean; color?: string } = {}
562 if (span.bold) style.bold = true
563 if (span.italic) style.italic = true
564 if (span.strike) style.strikethrough = true
565 if (span.dim) style.dimColor = true
566 if (span.code) style.color = 'permission'
567 if (span.link) {
568 style.color = 'suggestion'
569 style.underline = true
570 }
571
572 return Object.keys(style).length === 0 ? span.text : <Text {...style}>{span.text}</Text>
573 })
574}
575
576/**
577 * A markdown page: headings and tables drawn here, fitted to the pane's `width`;
578 * code fences as highlighted code; the rest (paragraphs, lists, quotes) by the engine's renderer.
579 */
580const renderMarkdown = (c: Ctx, text: string, width: number): RenderElement => {
581 const { Box, Text, Code, Markdown } = c.t
582 const blocks = parseBlocks(text)
583
584 return (
585 <Box flexDirection="column">
586 {...blocks.map((block, index) => {
587 const gap = index === 0 ? 0 : 1
588 switch (block.kind) {
589 case 'heading': {
590 const title = spanElements(c, block.spans)
591 const ruleWidth = Math.max(4, Math.min(width, displayWidth(block.spans.map(s => s.text).join('')) + 2))
592 if (block.level === 1) {
593 return (
594 <Box flexDirection="column" marginTop={gap}>
595 <Text bold color="claude">{...title}</Text>
596 <Text color="claude">{'━'.repeat(width)}</Text>
597 </Box>
598 )
599 }
600 if (block.level === 2) {
601 return (
602 <Box flexDirection="column" marginTop={gap}>
603 <Text bold color="claude">{...title}</Text>
604 <Text dimColor>{'─'.repeat(ruleWidth)}</Text>
605 </Box>
606 )
607 }
608
609 return (
610 <Box marginTop={gap}>
611 <Text bold>
612 <Text color="claude">{`${'#'.repeat(block.level)} `}</Text>
613 {...title}
614 </Text>
615 </Box>
616 )
617 }
618 case 'table':
619 return (
620 <Box flexDirection="column" marginTop={gap}>
621 {...layoutTable(block, width).map(line => <Text wrap="truncate-end">{...spanElements(c, line)}</Text>)}
622 </Box>
623 )
624 case 'code':
625 return (
626 <Box flexDirection="column" marginTop={gap}>
627 {block.language !== '' ? <Text dimColor>{block.language}</Text> : null}
628 {block.language !== '' ? <Code source={block.source} language={block.language} /> : <Code source={block.source} />}
629 </Box>
630 )
631 default:
632 return (
633 <Box marginTop={gap}>
634 <Markdown text={block.text} />
635 </Box>
636 )
637 }
638 })}
639 </Box>
640 )
641}
642
643const renderPreview = async (c: Ctx): Promise<RenderElement> => {
644 const table = c.t
645 const { Box, Text, Button, Code } = table
646 const shown = await S.pick(c.io, 'preview')
647 const snap = await S.pick(c.io, 'snapshot')
648 if (shown === null || snap === null) return renderTree(c)
649
650 const file = snap.files.find(f => f.path === shown.path)
651 const status = file ? STATUS[file.status] : null
652 const order = reviewOrder(snap.files)
653 const position = order.indexOf(shown.path)
654 const bodyColumns = c.e.component === 'Pane' ? c.e.props.bodyColumns : 60
655 const gitMode = await isGitMode(c, snap)
656
657 let content: RenderElement
658 switch (shown.kind) {
659 case 'diff':
660 content = shown.colored
661 ? coloredDiff(c, shown.text, shown.colored)
662 : <Code source={shown.text} format="diff" path={shown.path} />
663 break
664 case 'code':
665 content = shown.colored
666 ? coloredSource(c, shown.colored, shown.firstLine ?? 1)
667 : <Code source={shown.text} path={shown.path} startLine={shown.firstLine ?? 1} />
668 break
669 case 'markdown':
670 content = renderMarkdown(c, shown.text, Math.max(20, bodyColumns - 1))
671 break
672 case 'image': {
673 const image = shown.image
674 if (image !== undefined && 'Image' in c.t) {
675 const { Image } = c.t
676 const columns = Math.max(8, Math.min(255, bodyColumns - 2))
677 // Terminal cells are about twice as tall as wide.
678 const rows = Math.max(4, Math.min(60, Math.round((columns * image.height) / Math.max(1, image.width) / 2)))
679 content = (
680 <Box flexDirection="column">
681 <Image source={{ file: image.file, format: 'png' }} columns={columns} rows={rows} alt={shown.note ?? 'PNG image'} />
682 </Box>
683 )
684 } else {
685 content = <Text dimColor>{shown.note ?? 'Image'}</Text>
686 }
687 break
688 }
689 default:
690 content = <Text dimColor>{shown.note ?? ''}</Text>
691 }
692
693 const pager =
694 shown.pages > 1 ? (
695 <Box columnGap={2} flexWrap="wrap" marginTop={1}>
696 {shown.page > 0 ? (
697 <Button key="page-prev" plain hotkey="k" onPress={() => A.openFile(c.io, shown.path, shown.mode, shown.page - 1)}>Previous page</Button>
698 ) : null}
699 <Text dimColor>
700 {`page ${shown.page + 1} of ${shown.pages}`}
701 {shown.firstLine !== undefined && shown.totalLines !== undefined
702 ? ` · from line ${shown.firstLine} of ${shown.totalLines}`
703 : ''}
704 </Text>
705 {shown.page < shown.pages - 1 ? (
706 <Button key="page-next" plain hotkey="j" onPress={() => A.openFile(c.io, shown.path, shown.mode, shown.page + 1)}>Next page</Button>
707 ) : null}
708 </Box>
709 ) : null
710
711 return (
712 <Box flexDirection="column">
713 <Box flexWrap="wrap" columnGap={2}>
714 <Button key="back" plain hotkey="b" autoFocus onPress={() => A.back(c.io)}>‹ Back</Button>
715 {...shown.modes.map(mode => (
716 <Button key={`mode:${mode}`} plain hotkey={MODE_LABEL[mode].hotkey} onPress={() => A.openFile(c.io, shown.path, mode)}>
717 {mode === shown.mode ? <Text bold color="claude">{MODE_LABEL[mode].label}</Text> : MODE_LABEL[mode].label}
718 </Button>
719 ))}
720 {order.length > 0 ? <Button key="prev" plain hotkey="p" onPress={() => A.step(c.io, -1)}>Prev</Button> : null}
721 {order.length > 0 ? <Button key="next" plain hotkey="n" onPress={() => A.step(c.io, 1)}>Next</Button> : null}
722 <Button
723 key="copy"
724 plain
725 hotkey="c"
726 onPress={async press => {
727 const isCopied = await c.io.copy(shown.path, press.surface)
728 c.io.toast(isCopied ? `Copied ${shown.path}` : 'Could not copy the path')
729 }}
730 >
731 Copy path
732 </Button>
733 <Button key="mention" plain hotkey="r" onPress={() => A.mention(c.io, shown.path, true)}>{mentionLabel(shown, await S.pick(c.io, 'selected'))}</Button>
734 {file?.status === 'deleted' || snap.commit !== undefined ? null : (
735 <Button key="open-app" plain hotkey="o" onPress={() => A.openInApp(c.io, shown.path)}>Open</Button>
736 )}
737 {file !== undefined && gitMode ? (
738 <Button key="stage-toggle" plain hotkey="t" onPress={() => (file.unstaged ? A.stageFile(c.io, file) : A.unstageFile(c.io, file))}>
739 {file.unstaged ? 'Stage' : 'Unstage'}
740 </Button>
741 ) : null}
742 {file !== undefined && gitMode && file.status !== 'conflict' ? (
743 <Button key="discard" plain hotkey="x" onPress={() => A.discard(c.io, file)}>Discard</Button>
744 ) : null}
745 </Box>
746 {gitMode ? await statusLine(c) : null}
747 <Box flexWrap="wrap" marginTop={1}>
748 <Text dimColor>{dirname(shown.path)}</Text>
749 <Text bold {...(status ? { color: status.color } : {})}>{basename(shown.path)}</Text>
750 {status ? <Text color={status.color}>{` ${status.label}`}</Text> : ''}
751 {file?.status === 'renamed' && file.from ? <Text dimColor>{` from ${file.from}`}</Text> : ''}
752 {...(file ? stats(c, file) : [])}
753 {position >= 0 ? <Text dimColor>{` ${position + 1}/${order.length}`}</Text> : ''}
754 </Box>
755 {shown.kind === 'image' && shown.note ? <Text dimColor>{shown.note}</Text> : null}
756 <Box flexDirection="column" marginTop={1}>
757 {content}
758 </Box>
759 {pager}
760 </Box>
761 )
762}
763
764/** A line's colored runs as Text; an empty line keeps its row. */
765const spansOf = (c: Ctx, spans: ColoredSpan[]) => {
766 const { Text } = c.t
767 if (spans.every(([text]) => text === '')) return ' '
768
769 return spans.map(([text, color], i) => (color === null ? text : <Text key={`s${i}`} color={color}>{text}</Text>))
770}
771
772/** A page the pane's own highlighter colored, laid out as Code lays out source: numbered, a long line wrapped beside its number. */
773const coloredSource = (c: Ctx, colored: (ColoredSpan[] | null)[], firstLine: number) => {
774 const { Box, Text } = c.t
775 const widest = String(firstLine + colored.length - 1).length
776
777 return (
778 <Box flexDirection="column">
779 {colored.map((spans, i) => (
780 <Box key={`line:${firstLine + i}`} flexDirection="row">
781 <Box flexShrink={0}>
782 <Text color="inactive">{` ${String(firstLine + i).padStart(widest)} `}</Text>
783 </Box>
784 <Box flexGrow={1} flexShrink={1}>
785 <Text>{spansOf(c, spans ?? [])}</Text>
786 </Box>
787 </Box>
788 ))}
789 </Box>
790 )
791}
792
793/** A diff the pane's own highlighter colored, laid out as Code draws a diff: `...` between hunks, the changed lines on red and green. */
794const coloredDiff = (c: Ctx, text: string, colored: (ColoredSpan[] | null)[]) => {
795 const { Box, Text } = c.t
796 const lines = text.split('\n')
797 const rows: RenderElement[] = []
798 let oldLine = 1
799 let newLine = 1
800 let widest = 1
801 for (const line of lines) {
802 const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))?/.exec(line)
803 if (header) widest = Math.max(widest, String(Number(header[1]) + Number(header[2] ?? 1)).length, String(Number(header[3]) + Number(header[4] ?? 1)).length)
804 }
805 lines.forEach((line, i) => {
806 const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)/.exec(line)
807 if (header) {
808 oldLine = Number(header[1])
809 newLine = Number(header[2])
810 if (rows.length > 0) rows.push(<Text key={`gap:${i}`} dimColor>...</Text>)
811
812 return
813 }
814 if (line.startsWith('\\')) return
815 const sign = line[0] === '-' || line[0] === '+' ? line[0] : ' '
816 const number = sign === '-' ? oldLine : newLine
817 if (sign !== '+') oldLine += 1
818 if (sign !== '-') newLine += 1
819 const background = sign === '-' ? 'diffRemoved' : sign === '+' ? 'diffAdded' : undefined
820 const gutter = ` ${String(number).padStart(widest)} ${sign}`
821 rows.push(
822 <Box key={`line:${i}`} flexDirection="row">
823 <Box flexShrink={0}>
824 {background === undefined
825 ? <Text dimColor>{gutter}</Text>
826 : <Text color={sign === '-' ? 'error' : 'success'} backgroundColor={background}>{gutter}</Text>}
827 </Box>
828 <Box flexGrow={1} flexShrink={1}>
829 {background === undefined
830 ? <Text>{spansOf(c, colored[i] ?? [])}</Text>
831 : <Text backgroundColor={background}>{spansOf(c, colored[i] ?? [])}</Text>}
832 </Box>
833 </Box>,
834 )
835 })
836
837 return <Box flexDirection="column">{rows}</Box>
838}
839
840/** One commit of the history, bold while the tree shows it. */
841const commitRow = (c: Ctx, commit: CommitInfo, shown: CommitInfo | null) => {
842 const { Button, Text } = c.t
843 const isShown = shown?.sha === commit.sha
844
845 return (
846 <Button key={`commit:${commit.sha}`} plain {...(isShown ? { autoFocus: true as const } : {})} onPress={() => A.showCommit(c.io, commit)}>
847 <Text dimColor>{`${commit.short} `}</Text>
848 {isShown ? <Text bold>{commit.subject}</Text> : commit.subject}
849 <Text dimColor>{` ${commit.when} · ${commit.author}`}</Text>
850 </Button>
851 )
852}
853
854/**
855 * The history screen: the working changes, then the latest commits, newest first: those not
856 * pushed in a section of their own above those the remote has, where a remote can say.
857 */
858const renderLog = async (c: Ctx): Promise<RenderElement> => {
859 const { Box, Text, Button } = c.t
860 const log = await S.pick(c.io, 'log')
861 const shown = await S.pick(c.io, 'commit')
862 const snap = await S.pick(c.io, 'snapshot')
863 const upstream = snap?.upstream
864 // Push, pull and fetch act on the branch, whichever commit the tree shows.
865 const canSync = snap !== null && snap.error === undefined && (await sharedAgent(c)) === null
866 const isKnown = (log ?? []).some(commit => commit.isPushed !== undefined)
867 const unpushed = (log ?? []).filter(commit => commit.isPushed === false)
868 const pushed = (log ?? []).filter(commit => commit.isPushed !== false)
869
870 return (
871 <Box flexDirection="column">
872 <Button key="back" plain hotkey="b" onPress={() => S.put(c.io, 'screen', () => 'tree')}>‹ Back</Button>
873 {canSync ? (
874 <Box flexDirection="column" marginTop={1}>
875 {await syncRow(c, snap)}
876 {await statusLine(c)}
877 </Box>
878 ) : null}
879 <Box flexDirection="column" marginTop={1}>
880 <Button key="commit:working" plain {...(shown === null ? { autoFocus: true as const } : {})} onPress={() => A.showCommit(c.io, null)}>
881 {shown === null ? <Text bold>Working changes</Text> : 'Working changes'}
882 </Button>
883 {log === null ? <Text dimColor>Reading history…</Text> : null}
884 {...(isKnown ? [] : log ?? []).map(commit => commitRow(c, commit, shown))}
885 </Box>
886 {isKnown && unpushed.length > 0 ? (
887 <Box flexDirection="column" marginTop={1}>
888 <Text bold color="warning">{`Not pushed ${unpushed.length}`}</Text>
889 {...unpushed.map(commit => commitRow(c, commit, shown))}
890 </Box>
891 ) : null}
892 {isKnown && pushed.length > 0 ? (
893 <Box flexDirection="column" marginTop={1}>
894 <Text bold>{upstream === undefined ? 'On the remote' : `On ${upstream}`}</Text>
895 {...pushed.map(commit => commitRow(c, commit, shown))}
896 </Box>
897 ) : null}
898 </Box>
899 )
900}
901
902export const renderPane = async (c: Ctx): Promise<RenderElement> => {
903 const screen = await S.pick(c.io, 'screen')
904
905 return screen === 'preview' ? renderPreview(c) : screen === 'log' ? renderLog(c) : renderTree(c)
906}
907
908/**
909 * The Files button at the right of the prompt footer, beside the mode labels (`auto mode`):
910 * the labels the engine had, then the button that opens or hides the pane.
911 */
912export const renderFooter = async (c: Ctx, modes: readonly string[]): Promise<RenderElement | null> => {
913 const snap = await S.pick(c.io, 'snapshot')
914 if (snap === null || snap.error !== undefined) return null
915 const { Box, Text, Button } = c.t
916 const isOpen = await S.pick(c.io, 'isOpen')
917
918 return (
919 <Box columnGap={2}>
920 {modes.length > 0 ? <Text dimColor>{modes.join(' & ')}</Text> : null}
921 <Button key="toggle" plain onPress={() => (isOpen ? A.closePane(c.io) : A.openPane(c.io))}>
922 <Text color="claude">▤ </Text>
923 <Text>{isOpen ? 'Hide files' : 'Files'}</Text>
924 {snap.files.length === 0 ? <Text dimColor> clean</Text> : ''}
925 {...summaryParts(c, snap.files)}
926 </Button>
927 </Box>
928 )
929}
930hooks/activity.ts 82 lines1import type { Activity, ActivityKind } from '../types'
2
3/** Activity kept at most: the oldest goes first. */
4const MAX_ACTIVITY = 300
5
6/** Files one search marks at most, so a broad `grep -r` does not light up the whole tree. */
7const MAX_PER_CALL = 40
8
9/** Output lines looked through for paths. */
10const MAX_LINES = 3000
11
12/** A shell command that makes a commit: `git commit`, `git -c k=v commit`, after `&&` or `;`. */
13export const isCommit = (command: string): boolean =>
14 /(^|[\s;&|(])git(\s+-[cC]\s+\S+|\s+--?[\w-]+(=\S+)?)*\s+commit(\s|$)/.test(command) && !/\s--dry-run\b/.test(command)
15
16/** `a/b/c.ts` → `a/`, `a/b/`: the folders a row sits in, as the tree names them. */
17export const ancestors = (path: string): string[] => {
18 const parts = path.split('/').slice(0, -1)
19
20 return parts.map((_, index) => `${parts.slice(0, index + 1).join('/')}/`)
21}
22
23/** Resolves `.` and `..` in a slash path. */
24const normalize = (path: string): string => {
25 const out: string[] = []
26 for (const part of path.split('/')) {
27 if (part === '' || part === '.') continue
28 if (part === '..') out.pop()
29 else out.push(part)
30 }
31
32 return out.join('/')
33}
34
35/** `path` root-relative, or null when it lies outside `root`; `base` is the root-relative folder a relative path starts from. */
36export const toRelative = (path: string, root: string, base = ''): string | null => {
37 if (path.startsWith('/')) return path.startsWith(`${root}/`) ? normalize(path.slice(root.length + 1)) : null
38 if (path.startsWith('~')) return null
39
40 return normalize(base + path)
41}
42
43/**
44 * The repository files a read-only shell command named or printed: the command's own words,
45 * and each output line whole or before its first `:` (grep's `path:line:`). Only paths in `known` count.
46 */
47export const pathsIn = (command: string, output: string, known: ReadonlySet<string>, root: string, base: string): string[] => {
48 const found: string[] = []
49 const consider = (raw: string) => {
50 if (found.length >= MAX_PER_CALL) return
51 const word = raw.trim().replace(/^['"]+|['"]+$/g, '')
52 if (word === '' || word.startsWith('-')) return
53 const path = toRelative(word, root, base)
54 if (path !== null && known.has(path) && !found.includes(path)) found.push(path)
55 }
56
57 for (const word of command.split(/[\s'"=;|&()<>]+/)) consider(word)
58 for (const line of output.split('\n').slice(0, MAX_LINES)) {
59 consider(line)
60 const colon = line.indexOf(':')
61 if (colon > 0) consider(line.slice(0, colon))
62 }
63
64 return found
65}
66
67/**
68 * Adds what Claude just did to the list, latest last. A read never hides a write or a commit
69 * of the same file; a write and a commit replace each other.
70 */
71export const mergeActivity = (activity: readonly Activity[], kind: ActivityKind, paths: readonly string[]): Activity[] => {
72 let seq = activity.reduce((max, entry) => Math.max(max, entry.seq), 0)
73 const byPath = new Map(activity.map(entry => [entry.path, entry]))
74 for (const path of paths) {
75 const before = byPath.get(path)
76 seq += 1
77 byPath.set(path, { path, kind: kind === 'read' && before !== undefined ? before.kind : kind, seq })
78 }
79
80 return [...byPath.values()].sort((a, b) => a.seq - b.seq).slice(-MAX_ACTIVITY)
81}
82hooks/git.ts 387 lines1import type { BaseMode, ChangedFile, CommitInfo, FileStatus, Snapshot } from '../types'
2
3/** git's well-known empty tree: the base of a repository with no commit yet. */
4export const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
5
6export type RunResult = { exitCode: number; stdout: string; stderr: string }
7
8/** Runs git with these arguments in the given directory. */
9export type Git = (args: string[], cwd?: string) => Promise<RunResult>
10
11const BINARY_EXTENSIONS = new Set([
12 'png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'ico', 'bmp', 'tiff', 'psd',
13 'pdf', 'zip', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'jar', 'war',
14 'woff', 'woff2', 'ttf', 'otf', 'eot',
15 'mp3', 'mp4', 'mov', 'avi', 'webm', 'wav', 'ogg', 'flac',
16 'exe', 'dll', 'so', 'dylib', 'bin', 'o', 'a', 'class', 'wasm',
17 'sqlite', 'db', 'phar',
18])
19
20export const extensionOf = (path: string): string => {
21 const name = path.slice(path.lastIndexOf('/') + 1)
22 const dot = name.lastIndexOf('.')
23
24 return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''
25}
26
27export const looksBinary = (path: string): boolean => BINARY_EXTENSIONS.has(extensionOf(path))
28
29const splitZ = (text: string): string[] => {
30 const parts = text.split('\0')
31 if (parts[parts.length - 1] === '') parts.pop()
32
33 return parts
34}
35
36const statusFromPorcelain = (x: string, y: string): FileStatus | null => {
37 const xy = x + y
38 if (xy === '??') return 'untracked'
39 if (xy === '!!') return null
40 if (x === 'U' || y === 'U' || xy === 'AA' || xy === 'DD') return 'conflict'
41 if (x === 'R' || y === 'R') return 'renamed'
42 // Added to the index, then removed from disk: it exists nowhere.
43 if (x === 'A' && y === 'D') return null
44 if (x === 'D' || y === 'D') return 'deleted'
45 if (x === 'A' || x === 'C') return 'added'
46
47 return 'modified'
48}
49
50/** Parses `git status --porcelain=v1 -z`. */
51export const parseStatus = (stdout: string): ChangedFile[] => {
52 const parts = splitZ(stdout)
53 const files: ChangedFile[] = []
54
55 for (let i = 0; i < parts.length; i++) {
56 const entry = parts[i] ?? ''
57 if (entry.length < 4) continue
58 const x = entry[0] ?? ' '
59 const y = entry[1] ?? ' '
60 const path = entry.slice(3)
61 const status = statusFromPorcelain(x, y)
62 // A rename or copy carries its source as the next entry.
63 const from = x === 'R' || x === 'C' || y === 'R' || y === 'C' ? parts[++i] : undefined
64 if (status === null) continue
65 const file: ChangedFile = status === 'renamed' && from !== undefined ? { path, status, from } : { path, status }
66 // X is the index, Y the working tree; `??` lives in the working tree alone.
67 if (x !== ' ' && x !== '?') file.staged = true
68 if (y !== ' ' || x === '?') file.unstaged = true
69 // A conflict is resolved in the working tree before it can be staged.
70 if (status === 'conflict') delete file.staged
71 files.push(file)
72 }
73
74 return files
75}
76
77const statusFromLetter = (letter: string): FileStatus => {
78 switch (letter) {
79 case 'A':
80 case 'C':
81 return 'added'
82 case 'D':
83 return 'deleted'
84 case 'R':
85 return 'renamed'
86 case 'U':
87 return 'conflict'
88 default:
89 return 'modified'
90 }
91}
92
93/** Parses `git diff --name-status -z`. */
94export const parseNameStatus = (stdout: string): ChangedFile[] => {
95 const parts = splitZ(stdout)
96 const files: ChangedFile[] = []
97
98 for (let i = 0; i < parts.length; i++) {
99 const letter = (parts[i] ?? '').charAt(0)
100 if (letter === 'R' || letter === 'C') {
101 const from = parts[++i] ?? ''
102 const path = parts[++i] ?? ''
103 files.push(letter === 'R' ? { path, status: 'renamed', from } : { path, status: 'added' })
104 continue
105 }
106 const path = parts[++i]
107 if (path === undefined) break
108 files.push({ path, status: statusFromLetter(letter) })
109 }
110
111 return files
112}
113
114export type NumStat = { added: number; removed: number; isBinary: boolean }
115
116/** Parses `git diff --numstat -z` into counts by (new) path. */
117export const parseNumstat = (stdout: string): Map<string, NumStat> => {
118 const parts = splitZ(stdout)
119 const stats = new Map<string, NumStat>()
120
121 for (let i = 0; i < parts.length; i++) {
122 const [added = '', removed = '', path = ''] = (parts[i] ?? '').split('\t')
123 const isBinary = added === '-'
124 const stat = { added: isBinary ? 0 : Number(added), removed: isBinary ? 0 : Number(removed), isBinary }
125 if (path !== '') {
126 stats.set(path, stat)
127 continue
128 }
129 // A rename: the paths follow as two entries of their own.
130 i += 1
131 const newPath = parts[++i]
132 if (newPath !== undefined) stats.set(newPath, stat)
133 }
134
135 return stats
136}
137
138/** Parses `wc -l` output into line counts by path. */
139export const parseLineCounts = (stdout: string): Map<string, number> => {
140 const counts = new Map<string, number>()
141
142 for (const line of stdout.split('\n')) {
143 const match = /^\s*(\d+)\s(.+)$/.exec(line)
144 if (match === null) continue
145 const [, count = '0', path = ''] = match
146 if (path === 'total') continue
147 counts.set(path, Number(count))
148 }
149
150 return counts
151}
152
153const byPath = (a: ChangedFile, b: ChangedFile): number => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
154
155const ok = (result: RunResult): string | null => (result.exitCode === 0 ? result.stdout.trim() : null)
156
157/** The default branch to compare a feature branch against: origin's HEAD, else main or master. */
158export const defaultBranch = async (git: Git, root: string): Promise<string | null> => {
159 const remoteHead = ok(await git(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], root))
160 if (remoteHead) return remoteHead
161 for (const candidate of ['main', 'master', 'origin/main', 'origin/master']) {
162 const found = await git(['rev-parse', '--verify', '--quiet', candidate], root)
163 if (found.exitCode === 0) return candidate
164 }
165
166 return null
167}
168
169const untrackedLineCounts = async (
170 run: (argv: string[], cwd: string) => Promise<RunResult>,
171 root: string,
172 files: ChangedFile[],
173): Promise<void> => {
174 const counted = files.filter(f => f.status === 'untracked' && !looksBinary(f.path)).slice(0, 300)
175 if (counted.length === 0) return
176 const result = await run(['wc', '-l', '--', ...counted.map(f => f.path)], root)
177 const counts = parseLineCounts(result.stdout)
178 for (const file of counted) {
179 const lines = counts.get(file.path)
180 if (lines !== undefined) file.added = lines
181 }
182}
183
184const applyStats = (files: ChangedFile[], stats: ReadonlyMap<string, NumStat>): void => {
185 for (const file of files) {
186 const stat = stats.get(file.path)
187 if (stat === undefined) continue
188 file.added = stat.added
189 file.removed = stat.removed
190 if (stat.isBinary) file.isBinary = true
191 }
192}
193
194/** Parses `git log --format=%H%x1f%h%x1f%ar%x1f%an%x1f%s`. */
195export const parseLog = (stdout: string): CommitInfo[] =>
196 stdout
197 .split('\n')
198 .map(line => line.split('\x1f'))
199 .filter(parts => parts.length >= 5 && parts[0] !== '')
200 .map(([sha = '', short = '', when = '', author = '', ...subject]) => ({ sha, short, when, author, subject: subject.join('\x1f') }))
201
202/**
203 * The commits of HEAD that are not pushed: those its upstream lacks, or with no upstream those
204 * no remote branch has. Null when there is no remote to compare with.
205 */
206const unpushedShas = async (git: Git, root: string, count: number): Promise<Set<string> | null> => {
207 const hasUpstream = ok(await git(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], root)) !== null
208 if (!hasUpstream && !ok(await git(['remote'], root))) return null
209 const range = hasUpstream ? ['@{u}..HEAD'] : ['HEAD', '--not', '--remotes']
210 const listed = await git(['rev-list', `--max-count=${count}`, ...range], root)
211 if (listed.exitCode !== 0) return null
212
213 return new Set(listed.stdout.split('\n').filter(Boolean))
214}
215
216/** The latest commits of the current branch, newest first, each marked pushed or not where a remote says. */
217export const listCommits = async (git: Git, root: string, count = 50): Promise<CommitInfo[]> => {
218 const commits = parseLog((await git(['log', `-n${count}`, '--format=%H%x1f%h%x1f%ar%x1f%an%x1f%s'], root)).stdout)
219 const unpushed = await unpushedShas(git, root, count)
220
221 return unpushed === null ? commits : commits.map(commit => ({ ...commit, isPushed: !unpushed.has(commit.sha) }))
222}
223
224/** Every file in a commit, root-relative. */
225export const listTree = async (git: Git, root: string, sha: string): Promise<string[]> =>
226 splitZ((await git(['ls-tree', '-r', '--name-only', '-z', sha], root)).stdout)
227
228/** Reads what changed in the repository around `cwd`, against the chosen base, or what one commit changed. */
229export const scan = async (
230 git: Git,
231 run: (argv: string[], cwd: string) => Promise<RunResult>,
232 cwd: string,
233 baseMode: BaseMode,
234 commit: CommitInfo | null = null,
235 prompt: { before: string; now: string; label: string } | null = null,
236): Promise<Snapshot> => {
237 const top = await git(['rev-parse', '--show-toplevel'], cwd)
238 if (top.exitCode !== 0) {
239 return {
240 root: cwd, branch: '', baseMode, baseRev: '', baseLabel: '', files: [],
241 error: 'not-a-repo', message: 'Not inside a git repository.',
242 }
243 }
244 const root = top.stdout.trim()
245
246 const current = ok(await git(['branch', '--show-current'], root))
247 const hasHead = (await git(['rev-parse', '--verify', '--quiet', 'HEAD'], root)).exitCode === 0
248 const short = hasHead ? ok(await git(['rev-parse', '--short', 'HEAD'], root)) : null
249 const branch = current || (short ? `detached at ${short}` : 'no commits yet')
250
251 const tracking = current && hasHead ? await upstreamOf(git, root) : {}
252
253 if (commit !== null) {
254 // One past commit against its first parent (the empty tree for the first commit).
255 const parent = ok(await git(['rev-parse', '--verify', '--quiet', `${commit.sha}^`], root))
256 const base = parent ?? EMPTY_TREE
257 const changed = await git(['diff', '--name-status', '-z', '-M', base, commit.sha], root)
258 if (changed.exitCode !== 0) {
259 return {
260 root, branch, baseMode, baseRev: base, baseLabel: '', files: [], commit,
261 error: 'git-failed', message: changed.stderr.trim() || `Could not read commit ${commit.short}.`,
262 }
263 }
264 const files = parseNameStatus(changed.stdout)
265 applyStats(files, parseNumstat((await git(['diff', '--numstat', '-z', '-M', base, commit.sha], root)).stdout))
266
267 return { root, branch, ...tracking, baseMode, baseRev: base, baseLabel: parent ? `${commit.short}^` : 'empty tree', files: files.sort(byPath), commit }
268 }
269
270 if (baseMode === 'prompt' && prompt !== null) {
271 // Two trees, both with the untracked files: what changed on disk between them, whoever changed it.
272 const changed = await git(['diff', '--name-status', '-z', '-M', prompt.before, prompt.now], root)
273 if (changed.exitCode !== 0) {
274 return {
275 root, branch, ...tracking, baseMode, baseRev: prompt.before, baseLabel: prompt.label, files: [],
276 error: 'git-failed', message: changed.stderr.trim() || 'Could not compare with the last prompt.',
277 }
278 }
279 const files = parseNameStatus(changed.stdout)
280 applyStats(files, parseNumstat((await git(['diff', '--numstat', '-z', '-M', prompt.before, prompt.now], root)).stdout))
281
282 return { root, branch, ...tracking, baseMode, baseRev: prompt.before, toRev: prompt.now, baseLabel: prompt.label, files: files.sort(byPath) }
283 }
284
285 let baseRev = hasHead ? 'HEAD' : EMPTY_TREE
286 let baseLabel = hasHead ? 'HEAD' : 'empty tree'
287 let effectiveMode: BaseMode = 'head'
288
289 if (baseMode === 'branch' && hasHead) {
290 const target = await defaultBranch(git, root)
291 const mergeBase = target ? ok(await git(['merge-base', 'HEAD', target], root)) : null
292 if (target && mergeBase) {
293 baseRev = mergeBase
294 baseLabel = target.replace(/^origin\//, '')
295 effectiveMode = 'branch'
296 }
297 }
298
299 let files: ChangedFile[]
300 if (effectiveMode === 'head') {
301 const status = await git(['status', '--porcelain=v1', '-z', '--untracked-files=all'], root)
302 if (status.exitCode !== 0) {
303 return {
304 root, branch, baseMode, baseRev, baseLabel, files: [],
305 error: 'git-failed', message: status.stderr.trim() || 'git status failed.',
306 }
307 }
308 files = parseStatus(status.stdout)
309 } else {
310 const changed = await git(['diff', '--name-status', '-z', '-M', baseRev], root)
311 const untracked = await git(['ls-files', '--others', '--exclude-standard', '-z'], root)
312 files = [
313 ...parseNameStatus(changed.stdout),
314 ...splitZ(untracked.stdout).map((path): ChangedFile => ({ path, status: 'untracked' })),
315 ]
316 }
317
318 const numstat = await git(['diff', '--numstat', '-z', '-M', baseRev], root)
319 applyStats(files, parseNumstat(numstat.stdout))
320 await untrackedLineCounts(run, root, files)
321
322 // In the HEAD view git status lists a file staged and edited once; keep one row per path.
323 const unique = new Map(files.map(f => [f.path, f]))
324
325 return { root, branch, ...tracking, baseMode: effectiveMode, baseRev, baseLabel, files: [...unique.values()].sort(byPath) }
326}
327
328/** `2\t1` from `rev-list --left-right --count`: ahead, then behind. */
329export const parseAheadBehind = (text: string): { ahead: number; behind: number } | null => {
330 const match = /^(\d+)\s+(\d+)\s*$/.exec(text.trim())
331
332 return match === null ? null : { ahead: Number(match[1]), behind: Number(match[2]) }
333}
334
335/** The branch's upstream and how far apart they are, as of the last fetch (git is never asked to fetch). */
336const upstreamOf = async (git: Git, root: string): Promise<Pick<Snapshot, 'upstream' | 'ahead' | 'behind'>> => {
337 const upstream = ok(await git(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], root))
338 if (!upstream) return {}
339 const counts = parseAheadBehind(ok(await git(['rev-list', '--left-right', '--count', 'HEAD...@{u}'], root)) ?? '')
340
341 return counts === null ? { upstream } : { upstream, ...counts }
342}
343
344/** Every file git knows of or would add, root-relative. */
345export const listAll = async (git: Git, root: string): Promise<string[]> => {
346 const result = await git(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], root)
347
348 return [...new Set(splitZ(result.stdout))]
349}
350
351/** Keeps a unified diff's hunks and drops the file headers before them. */
352export const hunksOnly = (diff: string): string => {
353 const start = diff.search(/^@@ /m)
354
355 return start < 0 ? '' : diff.slice(start)
356}
357
358/** The diff of one file against the base, hunks only. */
359export const fileDiff = async (git: Git, snapshot: Snapshot, file: ChangedFile | undefined, path: string): Promise<string> => {
360 const root = snapshot.root
361 if (file?.status === 'untracked') {
362 const result = await git(['diff', '--no-color', '--no-index', '--', '/dev/null', path], root)
363
364 return hunksOnly(result.stdout)
365 }
366 const paths = file?.status === 'renamed' && file.from ? [file.from, path] : [path]
367 const end = snapshot.commit?.sha ?? snapshot.toRev
368 const revs = end === undefined ? [snapshot.baseRev] : [snapshot.baseRev, end]
369 const result = await git(['diff', '--no-color', '-M', ...revs, '--', ...paths], root)
370
371 return hunksOnly(result.stdout)
372}
373
374/** The file as a commit has it; null when the commit lacks it. */
375export const contentAt = async (git: Git, root: string, rev: string, path: string): Promise<string | null> => {
376 const result = await git(['show', `${rev}:${path}`], root)
377
378 return result.exitCode === 0 ? result.stdout : null
379}
380
381/** The file as the base has it (for a deleted file's source). */
382export const baseContent = async (git: Git, snapshot: Snapshot, path: string): Promise<string | null> => {
383 const result = await git(['show', `${snapshot.baseRev}:${path}`], snapshot.root)
384
385 return result.exitCode === 0 ? result.stdout : null
386}
387hooks/preview.ts 243 lines1import type { ChangedFile, Preview, PreviewMode, Snapshot } from '../types'
2import { baseContent, contentAt, extensionOf, fileDiff, looksBinary } from './git'
3import type { Git } from './git'
4import { colorDiff, colorPage, shikiLanguageOf } from './highlight'
5import { blockPageRanges } from './markdown'
6
7/** Characters one page draws: a drawing holds 100,000, and the header needs a little. */
8export const PAGE_CHARS = 60_000
9const PAGE_LINES = 2_000
10/** A rendered markdown page is smaller: table rules and padding add to what it draws. */
11const MARKDOWN_PAGE_CHARS = 30_000
12const MAX_FILE_BYTES = 3 * 1024 * 1024
13
14export type PreviewDeps = {
15 git: Git
16 /** The file's size in bytes, or null when it is missing. */
17 size: (absolutePath: string) => Promise<number | null>
18 readText: (absolutePath: string) => Promise<string>
19 /** A PNG's pixel size, or null when it is not one. */
20 pngSize: (absolutePath: string) => Promise<{ width: number; height: number } | null>
21 /** Claude Code's theme setting (`dark`, `light`, ...): the colors the pane's own highlighter picks. */
22 theme: () => Promise<string>
23}
24
25export const isMarkdown = (path: string): boolean => ['md', 'markdown', 'mdx'].includes(extensionOf(path))
26
27/** The file on each side of its diff: null where it is missing (new, deleted) or cannot be read. */
28const diffSides = async (deps: PreviewDeps, snapshot: Snapshot, file: ChangedFile | undefined, path: string) => {
29 const isNew = file?.status === 'untracked' || file?.status === 'added' || snapshot.baseRev === ''
30 const before = isNew ? null : await contentAt(deps.git, snapshot.root, snapshot.baseRev, file?.from ?? path).catch(() => null)
31 const end = snapshot.commit?.sha ?? snapshot.toRev
32 const after =
33 file?.status === 'deleted' ? null
34 : end !== undefined ? await contentAt(deps.git, snapshot.root, end, path).catch(() => null)
35 : await deps.readText(`${snapshot.root}/${path}`).catch(() => null)
36
37 return { before, after }
38}
39
40/** The modes a file offers, in toolbar order. */
41export const modesFor = (path: string, file: ChangedFile | undefined): PreviewMode[] => {
42 const modes: PreviewMode[] = []
43 if (file !== undefined && !file.isBinary && !looksBinary(path)) modes.push('diff')
44 modes.push('source')
45 if (isMarkdown(path)) modes.push('rendered')
46
47 return modes
48}
49
50/** What a file opens in: its changes when it has some, else its content. */
51export const defaultMode = (path: string, file: ChangedFile | undefined): PreviewMode => {
52 const markdownMode: PreviewMode = isMarkdown(path) ? 'rendered' : 'source'
53 if (file === undefined) return markdownMode
54 if (file.status === 'added' || file.status === 'untracked') return markdownMode
55 if (file.isBinary || looksBinary(path)) return 'source'
56
57 return 'diff'
58}
59
60/** Splits lines into pages of at most `budget` characters and `maxLines` lines: [start, end) each. */
61export const pageRanges = (lines: readonly string[], budget = PAGE_CHARS, maxLines = PAGE_LINES): Array<[number, number]> => {
62 const ranges: Array<[number, number]> = []
63 let start = 0
64 let size = 0
65
66 lines.forEach((line, index) => {
67 const cost = line.length + 1
68 if (index > start && (size + cost > budget || index - start >= maxLines)) {
69 ranges.push([start, index])
70 start = index
71 size = 0
72 }
73 size += cost
74 })
75 if (start < lines.length || ranges.length === 0) ranges.push([start, lines.length])
76
77 return ranges
78}
79
80const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/
81
82/** Cuts a hunk longer than `budget` into hunks of its own, each with a header that parses. */
83export const splitHunk = (hunk: string, budget = PAGE_CHARS): string[] => {
84 if (hunk.length <= budget) return [hunk]
85 const [header = '', ...body] = hunk.split('\n')
86 const match = HUNK_HEADER.exec(header)
87 if (match === null) return [hunk]
88 let oldLine = Number(match[1])
89 let newLine = Number(match[3])
90 const tail = match[5] ?? ''
91 const pieces: string[] = []
92
93 for (const [start, end] of pageRanges(body, budget - header.length - 2)) {
94 const lines = body.slice(start, end)
95 const oldCount = lines.filter(l => l.startsWith(' ') || l.startsWith('-')).length
96 const newCount = lines.filter(l => l.startsWith(' ') || l.startsWith('+')).length
97 pieces.push([`@@ -${oldLine},${oldCount} +${newLine},${newCount} @@${tail}`, ...lines].join('\n'))
98 oldLine += oldCount
99 newLine += newCount
100 }
101
102 return pieces
103}
104
105/** Pages a diff on hunk boundaries, so every page is hunks that parse. */
106export const diffPages = (diff: string, budget = PAGE_CHARS): string[] => {
107 const hunks = diff
108 .replace(/\n$/, '')
109 .split(/\n(?=@@ )/)
110 .filter(h => h.startsWith('@@ '))
111 .flatMap(h => splitHunk(h, budget))
112 const pages: string[] = []
113 let page: string[] = []
114 let size = 0
115
116 for (const hunk of hunks) {
117 if (page.length > 0 && size + hunk.length + 1 > budget) {
118 pages.push(page.join('\n'))
119 page = []
120 size = 0
121 }
122 page.push(hunk)
123 size += hunk.length + 1
124 }
125 if (page.length > 0) pages.push(page.join('\n'))
126
127 return pages
128}
129
130const formatBytes = (bytes: number): string =>
131 bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`
132
133const clampPage = (page: number, pages: number): number => Math.min(Math.max(0, page), Math.max(0, pages - 1))
134
135/** Loads what the preview screen draws for `path` in `mode`, one page of it. */
136export const loadPreview = async (
137 deps: PreviewDeps,
138 snapshot: Snapshot,
139 path: string,
140 mode: PreviewMode,
141 page = 0,
142): Promise<Preview> => {
143 const file = snapshot.files.find(f => f.path === path)
144 const modes = modesFor(path, file)
145 const shownMode = modes.includes(mode) ? mode : defaultMode(path, file)
146 const base = { path, mode: shownMode, modes, page: 0, pages: 1 }
147 const note = (text: string): Preview => ({ ...base, kind: 'note', text: '', note: text })
148
149 if (shownMode === 'diff') {
150 const diff = await fileDiff(deps.git, snapshot, file, path)
151 if (diff === '') return note(file?.status === 'renamed' ? `Renamed from ${file.from ?? '?'}, content unchanged.` : 'No line changes (mode or whitespace only).')
152 const pages = diffPages(diff)
153 const at = clampPage(page, pages.length)
154 const text = pages[at] ?? ''
155 const shown = { ...base, kind: 'diff' as const, text, page: at, pages: pages.length }
156 const language = shikiLanguageOf(path)
157 if (language === null) return shown
158 const { before, after } = await diffSides(deps, snapshot, file, path)
159 const colored = colorDiff(text, language, await deps.theme(), before, after)
160
161 return colored ? { ...shown, colored } : shown
162 }
163
164 const absolute = `${snapshot.root}/${path}`
165 let text: string
166 if (file?.status === 'deleted') {
167 const old = await baseContent(deps.git, snapshot, path)
168 if (old === null) return note('Deleted; its last version could not be read.')
169 text = old
170 } else if (snapshot.commit !== undefined) {
171 // A past commit: the file as that commit has it.
172 if (looksBinary(path) || file?.isBinary) return note('Binary file.')
173 const old = await contentAt(deps.git, snapshot.root, snapshot.commit.sha, path)
174 if (old === null) return note(`Not in commit ${snapshot.commit.short}.`)
175 if (old.length > MAX_FILE_BYTES) return note('Too large to preview.')
176 if (old === '') return note('Empty file.')
177 text = old
178 } else {
179 const size = await deps.size(absolute)
180 if (size === null) return note('File not found on disk.')
181 if (extensionOf(path) === 'png') {
182 const dimensions = await deps.pngSize(absolute)
183 if (dimensions !== null) {
184 return { ...base, kind: 'image', text: '', image: { file: absolute, ...dimensions }, note: `${dimensions.width}×${dimensions.height} PNG, ${formatBytes(size)}` }
185 }
186 }
187 if (looksBinary(path) || file?.isBinary) return note(`Binary file, ${formatBytes(size)}.`)
188 if (size > MAX_FILE_BYTES) return note(`Too large to preview (${formatBytes(size)}).`)
189 if (size === 0) return note('Empty file.')
190 text = await deps.readText(absolute)
191 }
192 if (text.includes('\0')) return note('Binary file.')
193
194 const lines = text.replace(/\n$/, '').split('\n')
195 const ranges = shownMode === 'rendered' ? blockPageRanges(lines, MARKDOWN_PAGE_CHARS) : pageRanges(lines)
196 const at = clampPage(page, ranges.length)
197 const [start, end] = ranges[at] ?? [0, lines.length]
198 const language = shownMode === 'rendered' ? null : shikiLanguageOf(path)
199 const colored = language === null ? undefined : colorPage(text, language, await deps.theme(), start, end)
200
201 return {
202 ...base,
203 kind: shownMode === 'rendered' ? 'markdown' : 'code',
204 text: lines.slice(start, end).join('\n'),
205 page: at,
206 pages: ranges.length,
207 firstLine: start + 1,
208 totalLines: lines.length,
209 ...(colored ? { colored } : {}),
210 }
211}
212
213const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
214
215const decodeBase64 = (text: string): number[] => {
216 const bytes: number[] = []
217 let buffer = 0
218 let bits = 0
219 for (const char of text) {
220 const value = BASE64.indexOf(char)
221 if (value < 0) continue
222 buffer = (buffer << 6) | value
223 bits += 6
224 if (bits >= 8) {
225 bits -= 8
226 bytes.push((buffer >> bits) & 0xff)
227 }
228 }
229
230 return bytes
231}
232
233/** Reads a PNG's width and height from its header bytes (base64 of the file). */
234export const pngDimensions = (base64Head: string): { width: number; height: number } | null => {
235 const bytes = decodeBase64(base64Head)
236 const signature = [0x89, 0x50, 0x4e, 0x47]
237 if (bytes.length < 24 || signature.some((b, i) => bytes[i] !== b)) return null
238 const read32 = (at: number): number =>
239 (((bytes[at] ?? 0) << 24) | ((bytes[at + 1] ?? 0) << 16) | ((bytes[at + 2] ?? 0) << 8) | (bytes[at + 3] ?? 0)) >>> 0
240
241 return { width: read32(16), height: read32(20) }
242}
243hooks/ops.ts 111 lines1import type { ChangedFile, PrInfo } from '../types'
2
3/** How long a destructive press waits for its second press. */
4export const CONFIRM_MS = 4000
5
6/** What a git operation came to, as the status line shows it. */
7export type Outcome = { ok: boolean; text: string; detail?: string }
8
9const DETAIL_LINES = 12
10
11/** git's words as a status line: the first meaningful line, the rest kept for a failure. */
12export const outcomeOf = (ok: boolean, output: string, fallback: string): Outcome => {
13 const lines = output
14 .split('\n')
15 .map(line => line.replace(/^(error|fatal|hint|remote): /, '').trimEnd())
16 .filter(line => line.trim() !== '')
17 const [first = fallback, ...rest] = lines
18 const detail = rest.slice(0, DETAIL_LINES).join('\n')
19
20 return ok || detail === '' ? { ok, text: first } : { ok, text: first, detail }
21}
22
23/** The paths a stage or unstage of `file` touches: a rename moves both its paths. */
24export const pathsOf = (file: ChangedFile): string[] => (file.status === 'renamed' && file.from ? [file.from, file.path] : [file.path])
25
26/**
27 * The commands that throw away the changes to `file`, back to HEAD: a new or added file is
28 * deleted, a rename is undone, anything else is restored in the index and on disk.
29 */
30export const discardCommands = (file: ChangedFile): string[][] => {
31 switch (file.status) {
32 case 'untracked':
33 return [['clean', '-f', '--', file.path]]
34 case 'added':
35 return [['rm', '-f', '--', file.path]]
36 case 'renamed':
37 return [
38 ['rm', '-f', '--', file.path],
39 ['restore', '--source=HEAD', '--staged', '--worktree', '--', file.from ?? file.path],
40 ]
41 default:
42 return [['restore', '--source=HEAD', '--staged', '--worktree', '--', file.path]]
43 }
44}
45
46/** `gh pr view --json number,url,state,isDraft`, or null when there is no PR. */
47export const parsePrView = (stdout: string): PrInfo | null => {
48 try {
49 const value = JSON.parse(stdout) as Partial<PrInfo>
50 if (typeof value.number !== 'number' || typeof value.url !== 'string') return null
51
52 return { number: value.number, url: value.url, state: String(value.state ?? 'OPEN'), isDraft: value.isDraft === true }
53 } catch {
54 return null
55 }
56}
57
58/**
59 * A remote's web page (`https://github.com/o/r`), from its fetch URL: `git@host:o/r.git`, `ssh://git@host:22/o/r.git`,
60 * `https://host/o/r.git`. Null for any other form (a local path).
61 */
62export const webUrlOf = (remote: string): string | null => {
63 const scp = /^[\w.-]+@([\w.-]+):\/?([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(remote.trim())
64 if (scp) return `https://${scp[1]}/${scp[2]}`
65 const url = /^(?:ssh|git|https?):\/\/(?:[^@/]+@)?([\w.-]+)(:\d+)?\/([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(remote.trim())
66 if (!url) return null
67 const port = remote.startsWith('http') ? (url[2] ?? '') : ''
68
69 return `${remote.startsWith('http:') ? 'http' : 'https'}://${url[1]}${port}/${url[3]}`
70}
71
72/** GitHub's page that opens a PR for `branch` against the repository's default branch. */
73export const compareUrl = (web: string, branch: string): string =>
74 `${web}/compare/${branch.split('/').map(encodeURIComponent).join('/')}?expand=1`
75
76/** A PR's state as the header says it: `PR #14 open`, `PR #14 draft`, `PR #14 merged`. */
77export const prLabel = (pr: PrInfo): string => `PR #${pr.number} ${pr.isDraft && pr.state === 'OPEN' ? 'draft' : pr.state.toLowerCase()}`
78
79/** How much of the staged diff the message prompt carries; the file list always goes whole. */
80export const MESSAGE_DIFF_CHARS = 24_000
81
82/**
83 * The prompt that asks the session's model for a commit message: the staged changes, and the
84 * repository's last subjects so the message reads like the rest of its history.
85 */
86export const messagePrompt = (input: { stat: string; diff: string; subjects: readonly string[]; amend: string | null }): string => {
87 const diff = input.diff.length > MESSAGE_DIFF_CHARS ? `${input.diff.slice(0, MESSAGE_DIFF_CHARS)}\n[… the rest of the diff is left out]` : input.diff
88
89 return [
90 'Write the git commit message for the staged changes below. Use what you know from this conversation about why they were made.',
91 input.amend === null ? '' : `This replaces the last commit (amend). Its message was:\n${input.amend}`,
92 input.subjects.length > 0 ? `Write it in the style of the repository's recent commits:\n${input.subjects.map(subject => `- ${subject}`).join('\n')}` : '',
93 'A subject line in the imperative, at most 60 characters, with no type prefix (feat:, fix:) and no closing period. Then, when the why is not obvious from the subject, a blank line and a short body in plain sentences saying why, wrapped at 72 columns.',
94 'Reply with the message alone: no quotes, no code fence, nothing before or after it.',
95 `Staged files:\n${input.stat.trim()}`,
96 `Staged diff:\n${diff.trim()}`,
97 ]
98 .filter(part => part !== '')
99 .join('\n\n')
100}
101
102/** The model's reply as a commit message: a code fence or wrapping quotes taken off. */
103export const cleanMessage = (reply: string): string => {
104 let text = reply.trim()
105 const fenced = /^```[^\n]*\n([\s\S]*?)\n```$/.exec(text)
106 if (fenced) text = (fenced[1] ?? '').trim()
107 if (/^(["'`]).*\1$/s.test(text)) text = text.slice(1, -1).trim()
108
109 return text
110}
111hooks/tree.ts 130 lines1import type { ChangedFile } from '../types'
2
3type Node = {
4 name: string
5 /** Root-relative; a folder's ends in `/`. */
6 path: string
7 isDir: boolean
8 children: Map<string, Node>
9 file?: ChangedFile
10 /** Changed files at or below this node. */
11 changes: number
12}
13
14export type Row = {
15 key: string
16 path: string
17 /** What the row shows: a name, or a compacted folder chain (`app/Http/`). */
18 label: string
19 depth: number
20 isDir: boolean
21 isOpen: boolean
22 changes: number
23 file?: ChangedFile
24}
25
26export type FlattenOptions = {
27 /** Whether a folder (path ending in `/`, holding `changes` changed files) shows its children. */
28 isOpen: (path: string, changes: number) => boolean
29 /** Folds a chain of single-folder folders into one row, as editors do. */
30 isCompact: boolean
31}
32
33const newNode = (name: string, path: string, isDir: boolean): Node => ({
34 name, path, isDir, children: new Map(), changes: 0,
35})
36
37/** Builds the folder tree over `paths`, marking each changed file. */
38export const buildTree = (paths: Iterable<string>, changes: ReadonlyMap<string, ChangedFile>): Node => {
39 const root = newNode('', '', true)
40
41 for (const path of paths) {
42 const parts = path.split('/')
43 let node = root
44 let prefix = ''
45 parts.forEach((part, index) => {
46 const isLast = index === parts.length - 1
47 prefix += isLast ? part : `${part}/`
48 let child = node.children.get(part + (isLast ? '' : '/'))
49 if (child === undefined) {
50 child = newNode(part, prefix, !isLast)
51 node.children.set(part + (isLast ? '' : '/'), child)
52 }
53 node = child
54 })
55 const file = changes.get(path)
56 if (file !== undefined) node.file = file
57 }
58
59 const count = (node: Node): number => {
60 node.changes = node.isDir ? [...node.children.values()].reduce((sum, child) => sum + count(child), 0) : node.file ? 1 : 0
61
62 return node.changes
63 }
64 count(root)
65
66 return root
67}
68
69const sorted = (node: Node): Node[] =>
70 [...node.children.values()].sort((a, b) => {
71 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
72
73 return a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true })
74 })
75
76/** Lays the tree out as the rows the pane draws, top to bottom. */
77export const flatten = (root: Node, options: FlattenOptions): Row[] => {
78 const rows: Row[] = []
79
80 const walk = (node: Node, depth: number): void => {
81 for (const child of sorted(node)) {
82 if (!child.isDir) {
83 rows.push({
84 key: `row:${child.path}`, path: child.path, label: child.name, depth,
85 isDir: false, isOpen: false, changes: child.changes, ...(child.file ? { file: child.file } : {}),
86 })
87 continue
88 }
89 let shown = child
90 let label = `${child.name}/`
91 while (options.isCompact && shown.children.size === 1) {
92 const only = [...shown.children.values()][0]
93 if (only === undefined || !only.isDir) break
94 shown = only
95 label += `${only.name}/`
96 }
97 const isOpen = options.isOpen(shown.path, shown.changes)
98 rows.push({ key: `row:${shown.path}`, path: shown.path, label, depth, isDir: true, isOpen, changes: shown.changes })
99 if (isOpen) walk(shown, depth + 1)
100 }
101 }
102 walk(root, 0)
103
104 return rows
105}
106
107/** Case-insensitive subsequence match, so `lancon` finds `LandingController.php`. */
108export const matches = (path: string, filter: string): boolean => {
109 const needle = filter.trim().toLowerCase()
110 if (needle === '') return true
111 const hay = path.toLowerCase()
112 if (hay.includes(needle)) return true
113 let at = 0
114 for (const char of needle) {
115 if (char === ' ') continue
116 at = hay.indexOf(char, at)
117 if (at < 0) return false
118 at += 1
119 }
120
121 return true
122}
123
124/** The changed files in the order the changes view lists them (for next and previous). */
125export const reviewOrder = (files: readonly ChangedFile[]): string[] => {
126 const tree = buildTree(files.map(f => f.path), new Map(files.map(f => [f.path, f])))
127
128 return flatten(tree, { isOpen: () => true, isCompact: false }).filter(row => !row.isDir).map(row => row.path)
129}
130hooks/mention.ts 82 lines1import type { Preview } from '../types'
2
3/**
4 * What a selection in the open file comes to: its lines in the file as it is now, or, for a diff selection that
5 * holds removed lines (which the file no longer has), the diff lines themselves. `text` is the lines, whole.
6 */
7export type Picked = { from: number; to: number; text: string } | { diff: string }
8
9/** One line the pane shows: its text, and where it is in the file now (null for a removed line). */
10type Shown = { text: string; line: number | null; sign: string }
11
12/** The pane's own line numbers (the Vue and Svelte views draw them as text, so a selection takes them along). */
13const GUTTER = /^\s*\d+ [+\- ]?/
14
15/** Text with no whitespace: the terminal draws a tab as spaces, and breaks a long line where the pane is narrow. */
16const bare = (text: string): string => text.replace(/\s+/g, '')
17
18const shownLines = (preview: Preview): Shown[] => {
19 if (preview.kind === 'code') {
20 const first = preview.firstLine ?? 1
21
22 return preview.text.split('\n').map((text, i) => ({ text, line: first + i, sign: ' ' }))
23 }
24 const shown: Shown[] = []
25 let newLine = 1
26 for (const line of preview.text.split('\n')) {
27 const header = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(line)
28 if (header) {
29 newLine = Number(header[1])
30 continue
31 }
32 if (line.startsWith('\\') || line === '') continue
33 const sign = line[0] ?? ' '
34 shown.push({ text: line.slice(1), line: sign === '-' ? null : newLine, sign })
35 if (sign !== '-') newLine += 1
36 }
37
38 return shown
39}
40
41/**
42 * Finds the selected text among the lines the preview shows: in a source page or a diff page, the first place that
43 * holds it. Lines compare without their whitespace, so a selection that starts or ends inside a line, or holds a long
44 * line the pane wrapped over several rows, still finds its lines. Null when the page does not have it (a selection in
45 * the conversation, or a stale one).
46 */
47export const pick = (preview: Preview, selected: string): Picked | null => {
48 if (preview.kind !== 'code' && preview.kind !== 'diff') return null
49 const shown = shownLines(preview)
50 // Each character of the page, without whitespace, and the line it is on.
51 let page = ''
52 const lineOf: number[] = []
53 shown.forEach((line, i) => {
54 const text = bare(line.text)
55 page += text
56 for (let n = 0; n < text.length; n++) lineOf.push(i)
57 })
58 // `...` is the gap the pane draws between hunks.
59 const parts = selected.split('\n').filter(part => part.trim() !== '...')
60 // As selected, then without the numbers the pane's own views draw.
61 for (const wanted of [bare(parts.join('')), bare(parts.map(part => part.replace(GUTTER, '')).join(''))]) {
62 const at = wanted === '' ? -1 : page.indexOf(wanted)
63 if (at < 0) continue
64 const lines = shown.slice(lineOf[at] ?? 0, (lineOf[at + wanted.length - 1] ?? 0) + 1)
65 if (lines.some(line => line.line === null)) return { diff: lines.map(line => `${line.sign}${line.text}`).join('\n') }
66 const numbers = lines.map(line => line.line ?? 0)
67
68 return { from: Math.min(...numbers), to: Math.max(...numbers), text: lines.map(line => line.text).join('\n') }
69 }
70
71 return null
72}
73
74/** How the prompt names a path: relative to where the session runs when inside it, quoted when it has a space. */
75export const mentionOf = (absolute: string, cwd: string, range?: { from: number; to: number }): string => {
76 const path = absolute.startsWith(`${cwd}/`) ? absolute.slice(cwd.length + 1) : absolute
77 const fragment = range === undefined ? '' : range.from === range.to ? `#L${range.from}` : `#L${range.from}-${range.to}`
78 const text = `${path}${fragment}`
79
80 return /\s/.test(text) ? `@"${text}"` : `@${text}`
81}
82hooks/markdown.ts 597 lines1/**
2 * The parts of markdown the pane draws itself: headings (the engine's are bold body text),
3 * tables (the engine sizes them to the terminal, not the pane) and code fences.
4 * Everything else goes to the engine's `Markdown` as prose.
5 */
6
7export type Span = {
8 text: string
9 bold?: boolean
10 italic?: boolean
11 strike?: boolean
12 code?: boolean
13 link?: boolean
14 /** Table rules and the dim labels of the stacked layout. */
15 dim?: boolean
16}
17
18type Style = Omit<Span, 'text'>
19
20export type Align = 'left' | 'center' | 'right'
21
22export type Block =
23 | { kind: 'heading'; level: number; spans: Span[]; start: number; end: number }
24 | { kind: 'table'; align: Align[]; header: Span[][]; rows: Span[][][]; start: number; end: number }
25 | { kind: 'code'; language: string; source: string; start: number; end: number }
26 | { kind: 'prose'; text: string; start: number; end: number }
27
28/** One drawn row of a table: styled pieces that add up to the width it was laid out for. */
29export type Line = Span[]
30
31// Inline ----------------------------------------------------------------------------------
32
33const PUNCTUATION = /[!-/:-@[-`{-~]/
34const WORD = /[\p{L}\p{N}]/u
35
36const pushSpan = (out: Span[], span: Span): void => {
37 if (span.text === '') return
38 const last = out[out.length - 1]
39 if (last !== undefined && sameStyle(last, span)) last.text += span.text
40 else out.push({ ...span })
41}
42
43const styleKeys = ['bold', 'italic', 'strike', 'code', 'link', 'dim'] as const
44
45const sameStyle = (a: Style, b: Style): boolean => styleKeys.every(key => Boolean(a[key]) === Boolean(b[key]))
46
47/** Where the `]` closing the `[` at `open` is, brackets nesting; -1 when none. */
48const closingBracket = (src: string, open: number): number => {
49 let depth = 0
50 for (let i = open; i < src.length; i += 1) {
51 if (src[i] === '\\') {
52 i += 1
53 continue
54 }
55 if (src[i] === '[') depth += 1
56 if (src[i] === ']') {
57 depth -= 1
58 if (depth === 0) return i
59 }
60 }
61
62 return -1
63}
64
65/** Bold, italic, strikethrough, code and links, as styled spans; the markers dropped. */
66export const parseInline = (src: string, style: Style = {}): Span[] => {
67 const out: Span[] = []
68 let buffer = ''
69 const flush = () => {
70 pushSpan(out, { text: buffer, ...style })
71 buffer = ''
72 }
73 const nest = (inner: string, extra: Style) => {
74 flush()
75 for (const span of parseInline(inner, { ...style, ...extra })) pushSpan(out, span)
76 }
77 let i = 0
78
79 while (i < src.length) {
80 const char = src[i] ?? ''
81 const nextChar = src[i + 1] ?? ''
82
83 if (char === '\\' && PUNCTUATION.test(nextChar)) {
84 buffer += nextChar
85 i += 2
86 continue
87 }
88
89 if (char === '`') {
90 let ticks = 1
91 while (src[i + ticks] === '`') ticks += 1
92 const fence = '`'.repeat(ticks)
93 const end = src.indexOf(fence, i + ticks)
94 if (end > i) {
95 flush()
96 const inner = src.slice(i + ticks, end)
97 pushSpan(out, { text: /^ .* $/.test(inner) ? inner.slice(1, -1) : inner, ...style, code: true })
98 i = end + ticks
99 } else {
100 buffer += fence
101 i += ticks
102 }
103 continue
104 }
105
106 const pair = src.slice(i, i + 2)
107 if ((pair === '**' || pair === '__' || pair === '~~') && src[i + 2] !== undefined && src[i + 2] !== ' ') {
108 let end = src.indexOf(pair, i + 2)
109 // `***both***`: the bold closes on the last two stars.
110 while (end > 0 && src[end + 2] === pair[0]) end += 1
111 const isWordUnderscore = pair === '__' && (WORD.test(src[i - 1] ?? '') || WORD.test(src[end + 2] ?? ''))
112 if (end > i + 2 && !isWordUnderscore) {
113 nest(src.slice(i + 2, end), pair === '~~' ? { strike: true } : { bold: true })
114 i = end + 2
115 continue
116 }
117 }
118
119 if ((char === '*' || char === '_') && nextChar !== '' && nextChar !== ' ' && nextChar !== char) {
120 const opensMidWord = char === '_' && WORD.test(src[i - 1] ?? '')
121 // The closing mark: not half of a `**` inside, not after a space.
122 let end = src.indexOf(char, i + 1)
123 while (end > 0 && (src[end + 1] === char || src[end - 1] === ' ')) {
124 end = src.indexOf(char, src[end + 1] === char ? end + 2 : end + 1)
125 }
126 const closesMidWord = char === '_' && end > 0 && WORD.test(src[end + 1] ?? '')
127 if (end > i + 1 && src[end - 1] !== ' ' && !opensMidWord && !closesMidWord) {
128 nest(src.slice(i + 1, end), { italic: true })
129 i = end + 1
130 continue
131 }
132 }
133
134 const isImage = char === '!' && nextChar === '['
135 if (char === '[' || isImage) {
136 const open = isImage ? i + 1 : i
137 const close = closingBracket(src, open)
138 if (close > open && src[close + 1] === '(') {
139 const end = src.indexOf(')', close + 2)
140 if (end > close) {
141 const label = src.slice(open + 1, close)
142 nest(label === '' ? src.slice(close + 2, end) : label, { link: true })
143 i = end + 1
144 continue
145 }
146 }
147 }
148
149 if (char === '<') {
150 const end = src.indexOf('>', i + 1)
151 const inner = end > i ? src.slice(i + 1, end) : ''
152 if (/^(https?:|mailto:|file:)\S+$/.test(inner)) {
153 flush()
154 pushSpan(out, { text: inner, ...style, link: true })
155 i = end + 1
156 continue
157 }
158 }
159
160 buffer += char
161 i += 1
162 }
163 flush()
164
165 return out
166}
167
168// Width -----------------------------------------------------------------------------------
169
170const isZeroWidth = (cp: number): boolean =>
171 (cp >= 0x300 && cp <= 0x36f) || cp === 0x200b || cp === 0x200c || cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f)
172
173const isWide = (cp: number): boolean =>
174 (cp >= 0x1100 && cp <= 0x115f) ||
175 (cp >= 0x2e80 && cp <= 0xa4cf) ||
176 (cp >= 0xac00 && cp <= 0xd7a3) ||
177 (cp >= 0xf900 && cp <= 0xfaff) ||
178 (cp >= 0xfe30 && cp <= 0xfe4f) ||
179 (cp >= 0xff00 && cp <= 0xff60) ||
180 (cp >= 0xffe0 && cp <= 0xffe6) ||
181 (cp >= 0x1f300 && cp <= 0x1faff) ||
182 (cp >= 0x20000 && cp <= 0x3fffd)
183
184const charWidth = (char: string): number => {
185 const cp = char.codePointAt(0) ?? 0
186
187 return isZeroWidth(cp) ? 0 : isWide(cp) ? 2 : 1
188}
189
190/** Columns `text` takes in a terminal. */
191export const displayWidth = (text: string): number => {
192 let width = 0
193 for (const char of text) width += charWidth(char)
194
195 return width
196}
197
198const spansWidth = (spans: readonly Span[]): number => spans.reduce((sum, span) => sum + displayWidth(span.text), 0)
199
200const spansText = (spans: readonly Span[]): string => spans.map(span => span.text).join('')
201
202// Wrapping --------------------------------------------------------------------------------
203
204type Piece = { text: string; style: Style; isSpace: boolean }
205
206const styleOf = (span: Span): Style => {
207 const { text: _text, ...style } = span
208
209 return style
210}
211
212/** Splits spans into words and runs of spaces, each keeping its span's style. */
213const pieces = (spans: readonly Span[]): Piece[] =>
214 spans.flatMap(span =>
215 (span.text.match(/\s+|\S+/g) ?? []).map(text => ({ text: /^\s/.test(text) ? ' ' : text, style: styleOf(span), isSpace: /^\s/.test(text) })),
216 )
217
218/** Cuts `text` into chunks of at most `width` columns. */
219const hardBreak = (text: string, width: number): string[] => {
220 const chunks: string[] = []
221 let chunk = ''
222 let used = 0
223 for (const char of text) {
224 const w = charWidth(char)
225 if (used + w > width && chunk !== '') {
226 chunks.push(chunk)
227 chunk = ''
228 used = 0
229 }
230 chunk += char
231 used += w
232 }
233 if (chunk !== '') chunks.push(chunk)
234
235 return chunks
236}
237
238/** Wraps styled spans to lines of at most `width` columns, breaking words only when they cannot fit. */
239export const wrapSpans = (spans: readonly Span[], width: number): Line[] => {
240 const lines: Line[] = []
241 let line: Line = []
242 let used = 0
243 const breakLine = () => {
244 lines.push(line)
245 line = []
246 used = 0
247 }
248
249 for (const piece of pieces(spans)) {
250 if (piece.isSpace) {
251 if (used > 0 && used < width) {
252 pushSpan(line, { text: ' ', ...piece.style })
253 used += 1
254 }
255 continue
256 }
257 const w = displayWidth(piece.text)
258 if (used + w > width && used > 0) {
259 // Drop the space the line ended on.
260 const last = line[line.length - 1]
261 if (last !== undefined && last.text.endsWith(' ')) {
262 last.text = last.text.slice(0, -1)
263 if (last.text === '') line.pop()
264 }
265 breakLine()
266 }
267 if (w <= width) {
268 pushSpan(line, { text: piece.text, ...piece.style })
269 used += w
270 continue
271 }
272 const chunks = hardBreak(piece.text, width)
273 chunks.forEach((chunk, index) => {
274 pushSpan(line, { text: chunk, ...piece.style })
275 used += displayWidth(chunk)
276 if (index < chunks.length - 1) breakLine()
277 })
278 }
279 if (line.length > 0 || lines.length === 0) lines.push(line)
280
281 return lines.map(l => {
282 const last = l[l.length - 1]
283 if (last !== undefined && last.text.endsWith(' ')) last.text = last.text.replace(/ +$/, '')
284
285 return l.filter(span => span.text !== '')
286 })
287}
288
289// Blocks ----------------------------------------------------------------------------------
290
291const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/
292const HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/
293const DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
294const LIST_OR_QUOTE = /^\s*([-*+]|\d+[.)]|>)(\s|$)/
295
296/** A table row's cells: pipes split them, except escaped ones and ones inside code. */
297export const splitRow = (line: string): string[] => {
298 let text = line.trim()
299 if (text.startsWith('|')) text = text.slice(1)
300 if (text.endsWith('|') && !text.endsWith('\\|')) text = text.slice(0, -1)
301 const cells: string[] = []
302 let cell = ''
303 let inCode = false
304 for (let i = 0; i < text.length; i += 1) {
305 const char = text[i] ?? ''
306 if (char === '\\' && text[i + 1] === '|') {
307 cell += '|'
308 i += 1
309 continue
310 }
311 if (char === '`') inCode = !inCode
312 if (char === '|' && !inCode) {
313 cells.push(cell.trim())
314 cell = ''
315 continue
316 }
317 cell += char
318 }
319 cells.push(cell.trim())
320
321 return cells
322}
323
324const alignOf = (cell: string): Align => {
325 const text = cell.trim()
326 if (text.startsWith(':') && text.endsWith(':')) return 'center'
327 if (text.endsWith(':')) return 'right'
328
329 return 'left'
330}
331
332const isTableStart = (lines: readonly string[], at: number): boolean => {
333 const head = lines[at] ?? ''
334 const rule = lines[at + 1] ?? ''
335 if (!head.includes('|') || !DELIMITER.test(rule) || !rule.includes('-')) return false
336
337 return splitRow(head).length === splitRow(rule).length
338}
339
340/** The document as blocks, each knowing its lines `[start, end)`. */
341export const parseBlocks = (text: string): Block[] => {
342 const lines = text.split('\n')
343 const blocks: Block[] = []
344 let prose: string[] = []
345 let proseStart = 0
346
347 const flushProse = (end: number) => {
348 let first = 0
349 let last = prose.length
350 while (first < last && (prose[first] ?? '').trim() === '') first += 1
351 while (last > first && (prose[last - 1] ?? '').trim() === '') last -= 1
352 if (first < last) blocks.push({ kind: 'prose', text: prose.slice(first, last).join('\n'), start: proseStart, end })
353 prose = []
354 }
355 const addProse = (line: string, at: number) => {
356 if (prose.length === 0) proseStart = at
357 prose.push(line)
358 }
359
360 let i = 0
361 // Front matter reads as YAML.
362 if (lines[0] === '---') {
363 const close = lines.findIndex((line, index) => index > 0 && (line === '---' || line === '...'))
364 if (close > 0) {
365 blocks.push({ kind: 'code', language: 'yaml', source: lines.slice(1, close).join('\n'), start: 0, end: close + 1 })
366 i = close + 1
367 }
368 }
369
370 while (i < lines.length) {
371 const line = lines[i] ?? ''
372
373 const fence = FENCE.exec(line)
374 if (fence !== null) {
375 const marker = fence[1] ?? '```'
376 let end = i + 1
377 while (end < lines.length && !new RegExp(`^ {0,3}${marker[0] === '`' ? '`' : '~'}{${marker.length},}\\s*$`).test(lines[end] ?? '')) end += 1
378 flushProse(i)
379 blocks.push({ kind: 'code', language: fence[2] ?? '', source: lines.slice(i + 1, end).join('\n'), start: i, end: Math.min(end + 1, lines.length) })
380 i = end + 1
381 continue
382 }
383
384 const heading = HEADING.exec(line)
385 if (heading !== null) {
386 flushProse(i)
387 blocks.push({ kind: 'heading', level: (heading[1] ?? '#').length, spans: parseInline((heading[2] ?? '').trim()), start: i, end: i + 1 })
388 i += 1
389 continue
390 }
391
392 // Setext: a lone line of text over === or ---.
393 const previous = prose[prose.length - 1]
394 const beforePrevious = prose.length > 1 ? prose[prose.length - 2] : ''
395 const isLoneText =
396 previous !== undefined && previous.trim() !== '' && (beforePrevious ?? '').trim() === '' && !LIST_OR_QUOTE.test(previous) && !previous.includes('|')
397 if (isLoneText && (/^ {0,3}=+\s*$/.test(line) || /^ {0,3}-{2,}\s*$/.test(line))) {
398 prose.pop()
399 flushProse(i - 1)
400 blocks.push({ kind: 'heading', level: line.trim().startsWith('=') ? 1 : 2, spans: parseInline(previous.trim()), start: i - 1, end: i + 1 })
401 i += 1
402 continue
403 }
404
405 if (isTableStart(lines, i)) {
406 flushProse(i)
407 const header = splitRow(line)
408 const align = splitRow(lines[i + 1] ?? '').map(alignOf)
409 const rows: Span[][][] = []
410 let end = i + 2
411 while (end < lines.length) {
412 const row = lines[end] ?? ''
413 if (row.trim() === '' || FENCE.test(row) || HEADING.test(row)) break
414 const cells = splitRow(row)
415 rows.push(header.map((_, column) => parseInline(cells[column] ?? '')))
416 end += 1
417 }
418 blocks.push({ kind: 'table', align, header: header.map(cell => parseInline(cell)), rows, start: i, end })
419 i = end
420 continue
421 }
422
423 addProse(line, i)
424 i += 1
425 }
426 flushProse(lines.length)
427
428 return blocks
429}
430
431/**
432 * Pages a markdown file on block boundaries, so no page starts inside a table or a fence:
433 * `[start, end)` line ranges of at most `budget` characters, a block larger than that cut by lines.
434 */
435export const blockPageRanges = (lines: readonly string[], budget: number): Array<[number, number]> => {
436 const blocks = parseBlocks(lines.join('\n'))
437 const ranges: Array<[number, number]> = []
438 let start = 0
439 let size = 0
440 const costOf = (from: number, to: number) => lines.slice(from, to).reduce((sum, line) => sum + line.length + 1, 0)
441
442 // Blank lines between blocks belong to the block after them.
443 const edges = blocks.map((block, index) => (index === 0 ? 0 : block.start)).concat(lines.length)
444 for (let index = 0; index < edges.length - 1; index += 1) {
445 const from = edges[index] ?? 0
446 const to = edges[index + 1] ?? lines.length
447 const cost = costOf(from, to)
448 if (size > 0 && size + cost > budget) {
449 ranges.push([start, from])
450 start = from
451 size = 0
452 }
453 if (cost > budget) {
454 // One block too large for a page: cut it by lines.
455 let at = from
456 let used = 0
457 for (let line = from; line < to; line += 1) {
458 const lineCost = (lines[line] ?? '').length + 1
459 if (line > at && used + lineCost > budget) {
460 ranges.push([start, line])
461 start = line
462 at = line
463 used = 0
464 }
465 used += lineCost
466 }
467 size = used
468 continue
469 }
470 size += cost
471 }
472 if (start < lines.length || ranges.length === 0) ranges.push([start, lines.length])
473
474 return ranges
475}
476
477// Tables ----------------------------------------------------------------------------------
478
479const BORDER = { top: ['┌', '┬', '┐'], middle: ['├', '┼', '┤'], bottom: ['└', '┴', '┘'] } as const
480
481const rule = (widths: readonly number[], [left, cross, right]: readonly [string, string, string]): Line => [
482 { text: left + widths.map(w => '─'.repeat(w + 2)).join(cross) + right, dim: true },
483]
484
485const pad = (line: Line, width: number, align: Align): Line => {
486 const gap = Math.max(0, width - spansWidth(line))
487 const before = align === 'right' ? gap : align === 'center' ? Math.floor(gap / 2) : 0
488 const after = gap - before
489 const out: Line = []
490 if (before > 0) out.push({ text: ' '.repeat(before) })
491 for (const span of line) pushSpan(out, span)
492 if (after > 0) pushSpan(out, { text: ' '.repeat(after) })
493
494 return out
495}
496
497/** One table row as drawn lines, each cell wrapped to its column. */
498const gridRow = (cells: readonly Span[][], widths: readonly number[], align: readonly Align[], isHeader: boolean): Line[] => {
499 const wrapped = widths.map((width, column) => {
500 const spans = (cells[column] ?? []).map(span => (isHeader ? { ...span, bold: true } : span))
501
502 return wrapSpans(spans, width)
503 })
504 const height = Math.max(1, ...wrapped.map(cell => cell.length))
505 const lines: Line[] = []
506 for (let row = 0; row < height; row += 1) {
507 const line: Line = [{ text: '│', dim: true }]
508 widths.forEach((width, column) => {
509 line.push({ text: ' ' })
510 for (const span of pad(wrapped[column]?.[row] ?? [], width, align[column] ?? 'left')) line.push(span)
511 line.push({ text: ' ' }, { text: '│', dim: true })
512 })
513 lines.push(line)
514 }
515
516 return lines
517}
518
519/** How wide each column is drawn in `width` columns, or null when even the narrowest layout overflows. */
520export const columnWidths = (header: readonly Span[][], rows: readonly Span[][][], width: number): number[] | null => {
521 const columns = header.length
522 const all = [header, ...rows]
523 const natural = header.map((_, column) => Math.max(1, ...all.map(row => spansWidth(row[column] ?? []))))
524 const room = width - (3 * columns + 1)
525 if (natural.reduce((a, b) => a + b, 0) <= room) return natural
526
527 // The narrowest a column goes: its longest word whole when they all fit, else cut at a cap;
528 // a grid that would chop short words reads worse than cards.
529 const longestWord = header.map((_, column) =>
530 Math.max(1, ...all.flatMap(row => spansText(row[column] ?? []).split(/\s+/).map(displayWidth))),
531 )
532 const leastFor = (cap: number) => natural.map((n, column) => Math.min(n, Math.max(3, Math.min(cap, longestWord[column] ?? 1))))
533 const sum = (list: readonly number[]) => list.reduce((a, b) => a + b, 0)
534 const least = [Infinity, 30, 20].map(leastFor).find(list => sum(list) <= room)
535 if (least === undefined) return null
536 const leastSum = sum(least)
537
538 // Share what is left by how much more each column wants.
539 const want = natural.map((n, column) => n - (least[column] ?? 0))
540 const wantSum = want.reduce((a, b) => a + b, 0)
541 const spare = room - leastSum
542 const widths = least.map((l, column) => l + Math.floor(((want[column] ?? 0) * spare) / Math.max(1, wantSum)))
543 let left = room - widths.reduce((a, b) => a + b, 0)
544 while (left > 0) {
545 let best = -1
546 widths.forEach((w, column) => {
547 if (w < (natural[column] ?? 0) && (best < 0 || (natural[column] ?? 0) - w > (natural[best] ?? 0) - (widths[best] ?? 0))) best = column
548 })
549 if (best < 0) break
550 widths[best] = (widths[best] ?? 0) + 1
551 left -= 1
552 }
553
554 return widths
555}
556
557/** A table that cannot fit as a grid: each row a card of `Header value` lines. */
558const cards = (header: readonly Span[][], rows: readonly Span[][][], width: number): Line[] => {
559 const labelWidth = Math.min(Math.max(...header.map(spansWidth), 1), Math.floor(width / 3))
560 const lines: Line[] = []
561 rows.forEach((row, index) => {
562 if (index > 0) lines.push([{ text: '─'.repeat(width), dim: true }])
563 header.forEach((label, column) => {
564 const labelLines = wrapSpans(label.map(span => ({ ...span, bold: true, dim: true })), labelWidth)
565 const valueLines = wrapSpans(row[column] ?? [], Math.max(1, width - labelWidth - 2))
566 const height = Math.max(labelLines.length, valueLines.length)
567 for (let at = 0; at < height; at += 1) {
568 const line = pad(labelLines[at] ?? [], labelWidth, 'left')
569 line.push({ text: ' ' })
570 for (const span of valueLines[at] ?? []) line.push(span)
571 lines.push(line.filter(span => span.text !== ''))
572 }
573 })
574 })
575
576 return lines
577}
578
579/** A table laid out in `width` columns: a grid when it fits, else stacked cards. */
580export const layoutTable = (table: Extract<Block, { kind: 'table' }>, width: number): Line[] => {
581 const widths = columnWidths(table.header, table.rows, width)
582 if (widths === null) return cards(table.header, table.rows, width)
583
584 const headerLines = gridRow(table.header, widths, table.header.map((_, column) => (table.align[column] === 'right' ? 'right' : 'center')), true)
585 const bodies = table.rows.map(row => gridRow(row, widths, table.align, false))
586 // Rules between rows only where some row wraps: one-line rows read fine without.
587 const isWrapped = bodies.some(lines => lines.length > 1)
588 const lines: Line[] = [rule(widths, BORDER.top), ...headerLines, rule(widths, BORDER.middle)]
589 bodies.forEach((body, index) => {
590 if (index > 0 && isWrapped) lines.push(rule(widths, BORDER.middle))
591 lines.push(...body)
592 })
593 lines.push(rule(widths, BORDER.bottom))
594
595 return lines
596}
597hooks/highlight.ts 98 lines1import type { ColoredSpan } from '../types'
2import { extensionOf } from './git'
3import { createHighlighter } from './vendor/shiki.js'
4import type { Highlighter, ShikiLanguage, ShikiTheme } from './vendor/shiki.js'
5
6/**
7 * The files Claude Code's highlighter has no grammar for, which the pane colors with its own copy of Shiki:
8 * the same grammars as VS Code, so a Vue template's attributes, directives and expressions are colored too.
9 */
10const LANGUAGES: Record<string, ShikiLanguage> = { vue: 'vue', svelte: 'svelte' }
11
12/** Monokai is the palette Claude Code's own dark syntax colors come from. */
13const themeFor = (theme: string): ShikiTheme => (theme.startsWith('light') ? 'github-light' : 'monokai')
14
15/** Larger files keep Claude Code's highlighting: a grammar takes a while over them. */
16const MAX_CHARS = 400_000
17
18export const shikiLanguageOf = (path: string): ShikiLanguage | null => LANGUAGES[extensionOf(path)] ?? null
19
20/** Made on first use, as the grammars compile then (about half a second). */
21let highlighter: Highlighter | null = null
22
23/** The last two texts colored: the pane redraws the open file every few seconds, and a diff colors both its sides. */
24const cache = new Map<string, ColoredSpan[][]>()
25const CACHED = 2
26
27/**
28 * Each line of `text` as runs of one color; the theme's own foreground is left as the terminal's text color. Null
29 * when the file is too large or the grammar fails on it.
30 */
31export const colorLines = (text: string, language: ShikiLanguage, theme: string): ColoredSpan[][] | null => {
32 if (text.length > MAX_CHARS) return null
33 const shikiTheme = themeFor(theme)
34 const key = `${language}\0${shikiTheme}\0${text}`
35 const cached = cache.get(key)
36 if (cached !== undefined) return cached
37 let lines: ColoredSpan[][]
38 try {
39 highlighter ??= createHighlighter()
40 const fg = highlighter.getTheme(shikiTheme).fg.toLowerCase()
41 lines = highlighter.codeToTokensBase(text.replace(/\n$/, ''), { lang: language, theme: shikiTheme }).map(tokens => {
42 const spans: ColoredSpan[] = []
43 for (const token of tokens) {
44 const color = token.color === undefined || token.color.toLowerCase() === fg ? null : token.color.toLowerCase()
45 const last = spans.at(-1)
46 if (last !== undefined && last[1] === color) last[0] += token.content
47 else spans.push([token.content, color])
48 }
49
50 return spans
51 })
52 } catch {
53 return null
54 }
55 cache.set(key, lines)
56 if (cache.size > CACHED) cache.delete(cache.keys().next().value ?? '')
57
58 return lines
59}
60
61/** A page of the file colored: lines `start` to `end`. */
62export const colorPage = (text: string, language: ShikiLanguage, theme: string, start: number, end: number): ColoredSpan[][] | undefined =>
63 colorLines(text, language, theme)?.slice(start, end)
64
65/**
66 * A diff's lines colored: a removed line as the old file colors it, a kept or added one as the new file does, so a
67 * line keeps what its file had open around it (a tag over several lines, a template string). Null for a hunk's
68 * header and git's no-newline note; the colors leave out the line's sign.
69 */
70export const colorDiff = (diff: string, language: ShikiLanguage, theme: string, before: string | null, after: string | null): (ColoredSpan[] | null)[] | undefined => {
71 const older = before === null ? null : colorLines(before, language, theme)
72 const newer = after === null ? null : colorLines(after, language, theme)
73 if (older === null && newer === null) return undefined
74 const lines: (ColoredSpan[] | null)[] = []
75 let oldLine = 1
76 let newLine = 1
77 for (const line of diff.split('\n')) {
78 const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)/.exec(line)
79 const plain: ColoredSpan[] = [[line.slice(1), null]]
80 if (header) {
81 oldLine = Number(header[1])
82 newLine = Number(header[2])
83 lines.push(null)
84 } else if (line.startsWith('\\')) {
85 lines.push(null)
86 } else if (line.startsWith('-')) {
87 lines.push(older?.[oldLine - 1] ?? plain)
88 oldLine += 1
89 } else {
90 lines.push(newer?.[newLine - 1] ?? plain)
91 if (!line.startsWith('+')) oldLine += 1
92 newLine += 1
93 }
94 }
95
96 return lines
97}
98