Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add a /wt-diff pane to the Claude Code plugin (#4638)
Maximilian Roos2c04fb370427
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex b47360f33..63acdac62 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -10,7 +10,7 @@"plugins": [{"name": "worktrunk",- "description": "Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows. This plugin provides configuration guidance (LLM commit messages, project hooks, worktree paths) and automatic activity tracking (π€/π¬ indicators in `wt list` showing active Claude sessions).",+ "description": "Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows. This plugin provides configuration guidance (LLM commit messages, project hooks, worktree paths), automatic activity tracking (π€/π¬ indicators in `wt list` showing active Claude sessions), and a `/wt-diff` pane showing each worktree's changes.","source": "./plugins/worktrunk"}]diff --git a/docs/src/content/docs/claude-code.md b/docs/src/content/docs/claude-code.mdindex 7ad0684a9..adebe1fba 100644--- a/docs/src/content/docs/claude-code.md+++ b/docs/src/content/docs/claude-code.md@@ -12,6 +12,7 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de| Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β || Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |+| `/wt-diff` pane | β | | | | | |The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly.@@ -146,6 +147,24 @@ Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktClaude Code asks for confirmation before a session enters an existing worktree by path outside `.claude/worktrees/`, which in worktrunk's default layout is every worktree. The plugin's `PermissionRequest` hook answers yes for a worktree of the repository the session is working in that sits where `worktree-path` puts its branch, so a background session doesn't stop at that prompt. Entering any other worktree still asks.+## `/wt-diff` pane (Claude Code only)++`/wt-diff` opens a pane beside the conversation that lists the worktrees the session has worked in, with the selected one's [`wt step diff`](/step/#wt-step-diff) below: everything since the branch left the default branch, committed, uncommitted, and untracked. `/wt-diff <branch>` selects another worktree.++A worktree joins the list when the session starts or moves into it, or when the session or one of its subagents edits a file there or runs a command there that isn't read-only. Until the pane first opens, the pane only notes those directories, without running `git` or `wt`.++| Key | Action |+|---|---|+| `1`β`9` | Select a worktree |+| `j` / `k` | Next or previous file |+| `ctrl+β` / `ctrl+β` | Next or previous file, from the prompt |+| `r` | Refresh |+| β β, PageUp, PageDown | Scroll |++The other keys work while the pane has the keyboard, which it takes when it opens. Running `/wt-diff` again gives it back, as does `ctrl+x tab`, which moves focus from the prompt to the line above it when another plugin draws one, then to the pane. `esc` returns to the prompt.++The pane needs a Claude Code release that loads plugin hooks modules; earlier releases load the rest of the plugin without it.+## Statusline (Claude Code only)`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. Claude Code runs it in the background, which is what makes the occasional 1β2 second CI fetch invisible.diff --git a/plugins/worktrunk/.claude-plugin/plugin.json b/plugins/worktrunk/.claude-plugin/plugin.jsonindex 196b7cc3c..d5fe4022f 100644--- a/plugins/worktrunk/.claude-plugin/plugin.json+++ b/plugins/worktrunk/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "worktrunk",- "description": "Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows. This plugin provides configuration guidance (LLM commit messages, project hooks, worktree paths) and automatic activity tracking (π€/π¬ indicators in `wt list` showing active Claude sessions).",+ "description": "Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows. This plugin provides configuration guidance (LLM commit messages, project hooks, worktree paths), automatic activity tracking (π€/π¬ indicators in `wt list` showing active Claude sessions), and a `/wt-diff` pane showing each worktree's changes.","author": {"name": "Worktrunk","url": "https://github.com/max-sixty/worktrunk"@@ -14,5 +14,6 @@"claude-code","agent"],- "icon": "./.claude-plugin/icon.png"+ "icon": "./.claude-plugin/icon.png",+ "types": "./types/index.d.ts"}diff --git a/plugins/worktrunk/AGENTS.md b/plugins/worktrunk/AGENTS.mdindex 8294cfdea..0be095a22 100644--- a/plugins/worktrunk/AGENTS.md+++ b/plugins/worktrunk/AGENTS.md@@ -10,6 +10,7 @@ The repository root is the marketplace for Claude Code and Codex and the Gemini- All three integrations call plugins/worktrunk/hooks/wt.sh. On Windows, Codex commandWindows calls hooks/wt.cmd to find Git Bash before running wt.sh. The command must parse in cmd.exe, Windows PowerShell, and pwsh; test it in all three shells with a plugin path containing spaces. Marker failures must not raise hook errors.- The Codex manifest uses the native PLUGIN_ROOT variable, braced as `${PLUGIN_ROOT}` in Windows commands for Codex's textual substitution. SessionEnd has a three-second timeout, Codex's event ceiling.- The shared skills mirror exposes wt-switch-create to Codex and Gemini, even though only Claude can switch the current session directory. Keep one authored skill tree.+- hooks/register.tsx is the plugin's one Claude Code hooks module (the early-access function hooks API), named under `modules` in hooks/hooks.json; it serves `/wt-diff`. types/index.d.ts is its state contract and tests/ its suite. Claude Code releases without modules drop the key and still load `hooks`, and Codex and Gemini never read it. Work on it with `claude --plugin-dir plugins/worktrunk`, which overrides an installed copy, and check it with `claude plugin validate plugins/worktrunk` and `claude plugin test plugins/worktrunk`.test_plugin_layout_is_consolidated checks loader paths and layout. test_docs_are_in_sync checks the skills mirror.diff --git a/plugins/worktrunk/hooks/hooks.json b/plugins/worktrunk/hooks/hooks.jsonindex 3230c6268..c1ffdad88 100644--- a/plugins/worktrunk/hooks/hooks.json+++ b/plugins/worktrunk/hooks/hooks.json@@ -1,4 +1,5 @@{+ "modules": ["./register.tsx"],"hooks": {"UserPromptSubmit": [{diff --git a/plugins/worktrunk/hooks/patch.ts b/plugins/worktrunk/hooks/patch.tsnew file mode 100644index 000000000..867bcea85--- /dev/null+++ b/plugins/worktrunk/hooks/patch.ts@@ -0,0 +1,117 @@+import type { FileDiff } from '../types'++/**+ * Splits a `git diff` patch into its files, keeping each file's hunks as the+ * source a `Code` element draws under `format: 'diff'`.+ *+ * Reads the headers git writes with `--no-color --no-ext-diff`, the `a/` and+ * `b/` prefixes and `core.quotePath=false`: `diff --git a/<old> b/<new>`, then+ * `new file`, `deleted file`, `rename to`, `Binary files` or `---`/`+++`+ * lines, then hunks. Git ends a `---`/`+++` name holding a space with a tab,+ * and still C-quotes one holding a tab, newline, quote or backslash.+ */+export function parsePatch(patch: string): FileDiff[] {+ const files: FileDiff[] = []+ for (const chunk of patch.split(/^(?=diff --git )/m)) {+ if (!chunk.startsWith('diff --git ')) {+ continue+ }+ const lines = chunk.split('\n')+ const first = lines[0] ?? ''+ const hunkAt = lines.findIndex(line => line.startsWith('@@'))+ const header = hunkAt === -1 ? lines : lines.slice(0, hunkAt)+ const body = hunkAt === -1 ? [] : lines.slice(hunkAt)+ const named = (prefix: string) => {+ const rest = header.find(line => line.startsWith(prefix))?.slice(prefix.length)+ return rest === undefined ? undefined : unquote(rest)+ }+ // A `---` or `+++` name without its side's prefix; `/dev/null` has none.+ const side = (prefix: string, at: string) => {+ const name = named(prefix)+ return name?.startsWith(at) === true ? name.slice(at.length) : undefined+ }+ const has = (prefix: string) => header.some(line => line.startsWith(prefix))++ // `+++ b/<path>` names the file after the change; a deletion has+ // `+++ /dev/null` and names it on `---`. A file with no hunks (binary,+ // mode-only, pure rename) names it only on `diff --git`.+ const quoted = / ("(?:[^"\\]|\\.)*")$/.exec(first)?.[1]+ const path =+ named('rename to ') ??+ side('+++ ', 'b/') ??+ side('--- ', 'a/') ??+ (quoted === undefined+ ? first.replace(/^diff --git a\/.* b\//, '')+ : unquote(quoted).replace(/^b\//, ''))++ let added = 0+ let deleted = 0+ for (const line of body) {+ if (line.startsWith('+')) {+ added += 1+ } else if (line.startsWith('-')) {+ deleted += 1+ }+ }++ const status: FileDiff['status'] = has('Binary files ')+ ? 'binary'+ : has('new file mode')+ ? 'added'+ : has('deleted file mode')+ ? 'deleted'+ : has('rename to ')+ ? 'renamed'+ : 'modified'++ const from = named('rename from ')+ const modes = [named('old mode '), named('new mode ')]+ const notes = [+ from === undefined ? null : `from ${from}`,+ modes[0] === undefined ? null : `mode ${modes[0]} β ${modes[1]}`,+ ].filter(note => note !== null)++ files.push({+ path: printable(path),+ status,+ added,+ deleted,+ note: notes.length === 0 ? null : printable(notes.join(', ')),+ hunks: printable(body.join('\n').replace(/\n+$/, '')),+ })+ }+ return files+}++const ESCAPES: Record<string, string> = {+ a: String.fromCharCode(7),+ b: '\b',+ f: '\f',+ n: '\n',+ r: '\r',+ t: '\t',+ v: '\v',+}++/**+ * A name as git wrote it on a header line: C-quoted and escaped, or bare and+ * ended with a tab when it holds a space.+ */+function unquote(name: string): string {+ if (!name.startsWith('"')) {+ return name.replace(/\t$/, '')+ }+ return name+ .slice(1, name.lastIndexOf('"'))+ .replace(/\\([0-7]{3}|.)/g, (_, code: string) =>+ code.length === 3 ? String.fromCharCode(Number.parseInt(code, 8)) : (ESCAPES[code] ?? code),+ )+}++/**+ * Replaces the control characters a drawn text refuses (all but tab and+ * newline: a CRLF file's `\r`, an escape sequence in a fixture) with U+FFFD.+ */+export function printable(text: string): string {+ return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, 'οΏ½')+}diff --git a/plugins/worktrunk/hooks/register.tsx b/plugins/worktrunk/hooks/register.tsxnew file mode 100644index 000000000..e48c56a30--- /dev/null+++ b/plugins/worktrunk/hooks/register.tsx@@ -0,0 +1,657 @@+import { atom, read, update } from 'claude-code'+import type { EngineInterface, Register, Timer } from 'claude-code'++import type { DiffView, FileDiff, Row, Touched } from '../types'+import { parsePatch, printable } from './patch'++/**+ * `/wt-diff`: a pane showing `wt step diff` for each worktree this session+ * worked in. Claude Code only; it is the plugin's one hooks module.+ *+ * Until the pane opens, the hooks only note directories: the session's own,+ * each directory Edit, Write or NotebookEdit wrote a file in, and each one a+ * Bash call ran in or changed a file in, subagents' calls included. Nothing+ * runs git or `wt`, and nothing is drawn. A hook reads `$.session.cwd()` as its+ * own loop's directory, so the session's directory, which the pane marks `@`,+ * is read only in hooks of the main loop: at the session's start, after each+ * of its turns and of its tool calls that were not read-only, and on a press.+ *+ * While the pane is open, each refresh resolves the noted directories to+ * worktrees with `git rev-parse`, cached per directory, and Worktrunk computes+ * everything shown: `wt list --format=json` the rows, one call per repository,+ * and `wt step diff` the selected worktree's files. It refreshes when the pane+ * opens, when a worktree is selected, after tool calls that were not+ * read-only (once a burst of them goes quiet) and at the end of each turn.+ */++const PANE = 'wt-diff'+// Characters of hunks drawn at once; a drawing draws its first 100,000.+const BUDGET = 80_000+// `wt list` JSON in the envelope this module reads, whatever schema the+// person's config picks.+const LIST_JSON = ['--config-set', 'list.json-schema=2', 'list', '--format=json']+// `git -c core.quotePath=false`, through git's environment spelling of `-c`.+const QUOTE_PATH_OFF = {+ GIT_CONFIG_COUNT: '1',+ GIT_CONFIG_KEY_0: 'core.quotePath',+ GIT_CONFIG_VALUE_0: 'false',+}++const seen = atom({ plugin: 'worktrunk', key: 'seen' } as const, [], {+ shape: 'seen-1',+})+const here = atom({ plugin: 'worktrunk', key: 'here' } as const, null)+const touched = atom({ plugin: 'worktrunk', key: 'touched' } as const, [], {+ shape: 'touched-1',+})+const rows = atom({ plugin: 'worktrunk', key: 'rows' } as const, [], {+ shape: 'rows-1',+})+const current = atom({ plugin: 'worktrunk', key: 'current' } as const, null)+const selected = atom({ plugin: 'worktrunk', key: 'selected' } as const, null)+const diffs = atom({ plugin: 'worktrunk', key: 'diffs' } as const, {}, {+ shape: 'diffs-1',+})+// -1 while the pane shows its top, so the first `j` reaches the first file.+const cursor = atom({ plugin: 'worktrunk', key: 'cursor' } as const, -1)++type Located = { root: string; commonDir: string }++// Per load: a reload asks git again and drops a pending refresh.+const located = new Map<string, Located | null>()+let refreshTimer: Timer | undefined+let refreshing: Promise<void> = Promise.resolve()++export const register: Register = on => {+ on('session.start', async ($, e, next) => {+ await $.command.register({+ name: 'wt-diff',+ description: 'Show `wt step diff` for the worktrees this session worked in',+ argumentHint: '[branch]',+ immediate: true,+ })+ const started = await next(e)+ await note($, [await noteHere($)])+ return started+ })++ on('command.run', { command: 'wt-diff' }, async ($, e) => {+ const branch = e.args.trim()+ const cwd = await $.session.cwd()+ // Bare on an open pane, it gives the pane the keys and keeps what it shows.+ const shown = branch === '' && (await isPaneOpen($)) ? await read($, selected) : null+ const root =+ shown ??+ (branch === ''+ ? ((await locate($, cwd))?.root ?? null)+ : await worktreeOf($, cwd, branch))+ if (root === null) {+ return {+ text:+ branch === ''+ ? `wt-diff: ${cwd} is in no git worktree`+ : `wt-diff: no worktree for branch ${branch}`,+ }+ }+ await note($, [await noteHere($), root])+ if (shown === null) {+ await select($, root)+ }+ const opened = await $.ui.open({ id: PANE, title: 'wt step diff', focus: true })+ await refresh($)+ return opened.isPlaced ? {} : { text: 'wt-diff: the pane is open but not shown here.' }+ })++ // It judges nothing: where it fails, the call goes on as it ran.+ on('tool.call', async ($, e, next) => {+ const ran = await next(e)+ // A call the tool ran read-only changed no file and no directory.+ if (ran.deny !== undefined || ran.isReadOnly === true) {+ return ran+ }+ const dirs: string[] = []+ if (e.tool === 'Edit' || e.tool === 'Write') {+ dirs.push(parentOf(e.file_path))+ } else if (e.tool === 'NotebookEdit') {+ dirs.push(parentOf(e.notebook_path))+ } else if (e.tool === 'Bash') {+ // Where the command ran: a subagent's own directory, in its calls.+ dirs.push(await $.session.cwd(), ...changedFiles(ran.result).map(parentOf))+ }+ if (e.agentId === undefined) {+ dirs.push(await noteHere($))+ }+ await note($, dirs)+ // What the call changed shows once a burst of calls goes quiet.+ if (await isPaneOpen($)) {+ refreshTimer?.cancel()+ refreshTimer = $.clock.after(400, () => {+ void refresh($)+ })+ }+ return ran+ }).catch(($, e, next) => next(e))++ on('turn.complete', async ($, e, next) => {+ const done = await next(e)+ if (e.agentId === undefined) {+ await note($, [await noteHere($)])+ void refresh($)+ }+ return done+ })++ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {+ const { Box, Button, Code, Text } = $.ui.resolve(e)+ const [list, known, own, root, all, at] = await Promise.all([+ read($, touched),+ read($, rows),+ read($, current),+ read($, selected),+ read($, diffs),+ read($, cursor),+ ])++ // The session's own worktree first, then the most recently worked in.+ const ordered = [...list].sort(+ (a, b) =>+ Number(b.root === own) - Number(a.root === own) || b.lastAt - a.lastAt,+ )+ const rowOf = (one: string) => known.find(row => row.root === one)+ const view = root === null ? undefined : all[root]+ const row = root === null ? undefined : rowOf(root)+ const files = view?.files ?? []+ // At the top, the first file is the one shown first.+ const drawn = drawnFiles(files, Math.max(at, 0))++ return (+ <Box flexDirection="column">+ <Text bold>Worktrees this session worked in</Text>+ {ordered.length === 0 && <Text dimColor>None yet.</Text>}+ {ordered.map((one, index) => {+ const info = rowOf(one.root)+ return (+ <Button+ key={`wt:${one.root}`}+ plain+ hotkey={index < 9 ? String(index + 1) : undefined}+ onPress={() => pick($, one.root)}+ >+ {one.root === root ? 'βΈ ' : ' '}+ {info?.branch ?? baseName(one.root)}+ {one.root === own ? ' @' : ''}{' '}+ <Text dimColor>{info === undefined ? '' : summary(info)}</Text>+ </Button>+ )+ })}+ <Text dimColor>{'β'.repeat(Math.max(10, e.props.bodyColumns))}</Text>+ {root === null ? (+ <Text dimColor>Select a worktree.</Text>+ ) : (+ <Box flexDirection="column">+ <Text>+ <Text bold>{row?.branch ?? baseName(root)}</Text>+ <Text dimColor>+ {' '}+ vs {row?.target ?? 'default branch'} Β· {files.length} files Β·{' '}+ </Text>+ <Text color="diffAdded">+{sum(files, 'added')}</Text>{' '}+ <Text color="diffRemoved">-{sum(files, 'deleted')}</Text>+ </Text>+ <Box flexDirection="row" gap={2}>+ <Button key="refresh" plain hotkey="r" label="refresh" onPress={() => reload($)} />+ {/* j and k as in Claude Code's diff dialog; the `action` also+ presses each from the prompt by the person's chord for the+ diff panel's file list (ctrl+β and ctrl+β by default). */}+ <Button+ key="next"+ plain+ hotkey="j"+ action="app:diffFileListDown"+ label="next file"+ onPress={() => move($, 1)}+ />+ <Button+ key="prev"+ plain+ hotkey="k"+ action="app:diffFileListUp"+ label="previous"+ onPress={() => move($, -1)}+ />+ {/* The keys above reach the pane only while it holds the keyboard. */}+ <Text dimColor>+ {e.props.isFocused ? 'ββ scroll Β· esc: prompt' : 'ctrl+x tab: focus'}+ </Text>+ </Box>+ {view === undefined && <Text dimColor>Loadingβ¦</Text>}+ {view?.isTruncated === true && (+ <Text color="warning">+ The diff passed 4 MiB; the files after these are not shown.+ </Text>+ )}+ {view !== undefined && view.error !== null && (+ <Text color="error">{view.error}</Text>+ )}+ {view !== undefined && view.error === null && files.length === 0 && (+ <Text dimColor>No changes since the merge base.</Text>+ )}+ {files.map((file, index) => (+ <Button+ key={`file:${file.path}`}+ plain+ dimColor={index !== at}+ onPress={() => jump($, index, file.path)}+ >+ {glyph(file)} {file.path}{' '}+ <Text color="diffAdded">+{file.added}</Text>{' '}+ <Text color="diffRemoved">-{file.deleted}</Text>+ </Button>+ ))}+ {files.map((file, index) => (+ <Box key={`box:${file.path}`} flexDirection="column" marginTop={1}>+ <Button+ key={`hunk:${file.path}`}+ plain+ onPress={() => backToTop($)}+ >+ <Text bold>+ {glyph(file)} {file.path}+ </Text>{' '}+ <Text dimColor>+ {index + 1}/{files.length}+ {file.note === null ? '' : ` Β· ${file.note}`} Β· β top+ </Text>+ </Button>+ {file.hunks === '' ? (+ <Text dimColor>+ {file.status === 'binary' ? 'Binary file.' : 'No line changes.'}+ </Text>+ ) : drawn.get(index) === undefined ? (+ <Text dimColor>+ {file.added + file.deleted} lines not drawn; select the file to draw it.+ </Text>+ ) : (+ <Box flexDirection="column">+ <Code source={drawn.get(index) ?? ''} format="diff" path={file.path} />+ {drawn.get(index) !== file.hunks && (+ <Text dimColor>The rest of this file is past what one drawing holds.</Text>+ )}+ </Box>+ )}+ </Box>+ ))}+ </Box>+ )}+ </Box>+ )+ })+}++async function locate($: EngineInterface, dir: string): Promise<Located | null> {+ const known = located.get(dir)+ if (known !== undefined) {+ return known+ }+ // A directory deleted since it was noted is answered for by its nearest+ // ancestor that still exists.+ let at = dir+ while (at !== '/' && (await $.fs.stat(at).catch(() => undefined))?.kind !== 'dir') {+ at = parentOf(at)+ }+ const ran = await $.process+ .run([+ 'git',+ '-C',+ at,+ 'rev-parse',+ '--path-format=absolute',+ '--show-toplevel',+ '--git-common-dir',+ ])+ .catch(() => null)+ const [root, commonDir] = ran?.exitCode === 0 ? ran.stdout.trim().split('\n') : []+ const found = root && commonDir ? { root, commonDir } : null+ located.set(dir, found)+ return found+}++// Notes directories the session worked in, most recent last; no process runs.+// Directories already the latest noted are left as they are, so a run of calls+// in one place writes nothing.+async function note($: EngineInterface, dirs: readonly string[]) {+ const fresh = [...new Set(dirs)]+ const latest = (await read($, seen)).slice(-fresh.length).map(one => one.dir)+ if (fresh.every(dir => latest.includes(dir))) {+ return+ }+ const now = await $.clock.now()+ await update($, seen, list => [+ ...list.filter(one => !fresh.includes(one.dir)),+ ...fresh.map(dir => ({ dir, lastAt: now })),+ ])+}++// Notes the session's own directory. Call only from a hook of the main loop,+// or a press.+async function noteHere($: EngineInterface): Promise<string> {+ const cwd = await $.session.cwd()+ await update($, here, () => cwd)+ return cwd+}++// The worktrees of the noted directories, each by its most recent sighting,+// and the one the session's directory is in.+async function resolveSeen($: EngineInterface) {+ const [list, cwd] = await Promise.all([read($, seen), read($, here)])+ const found = await Promise.all(list.map(one => locate($, one.dir)))+ const byRoot = new Map<string, Touched>()+ list.forEach((one, index) => {+ const at = found[index]+ if (at == null) {+ return+ }+ const known = byRoot.get(at.root)+ if (known === undefined || known.lastAt < one.lastAt) {+ byRoot.set(at.root, { ...at, lastAt: one.lastAt })+ }+ })+ await update($, touched, () => [...byRoot.values()])+ const root = cwd === null ? null : ((await locate($, cwd))?.root ?? null)+ await update($, current, () => root)+}++// One refresh at a time; a request during one runs after it.+function refresh($: EngineInterface): Promise<void> {+ refreshTimer?.cancel()+ refreshing = refreshing.then(async () => {+ if (!(await isPaneOpen($))) {+ return+ }+ // The diff is what the pane shows first, so it doesn't wait on `wt list`.+ const root = await read($, selected)+ await Promise.all([+ resolveSeen($).then(() => refreshRows($)),+ root === null ? null : refreshDiff($, root),+ ])+ })+ return refreshing+}++async function isPaneOpen($: EngineInterface): Promise<boolean> {+ return (await $.ui.panes()).some(pane => pane.id === PANE)+}++async function refreshRows($: EngineInterface) {+ const list = await read($, touched)+ const repos = new Map<string, string[]>()+ for (const one of list) {+ repos.set(one.commonDir, [...(repos.get(one.commonDir) ?? []), one.root])+ }+ const found: Row[] = []+ for (const roots of repos.values()) {+ // Any worktree of the repository lists them all; a removed one fails.+ for (const one of roots) {+ const ran = await $.process+ .run(['wt', '-C', one, ...LIST_JSON], { timeoutMs: 60_000 })+ .catch(() => null)+ if (ran !== null && ran.exitCode === 0) {+ found.push(...readRows(ran.stdout, roots))+ break+ }+ }+ }+ await update($, rows, () => found)+}++async function refreshDiff($: EngineInterface, root: string) {+ const ran = await $.process+ .run(+ [+ 'wt',+ '-C',+ root,+ 'step',+ 'diff',+ '--',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ ],+ // Unquoted paths, so a name like `cafΓ©.txt` reads as written.+ { timeoutMs: 60_000, env: QUOTE_PATH_OFF },+ )+ .catch((error: unknown) => ({+ exitCode: -1,+ stdout: '',+ stderr: String(error),+ isStdoutTruncated: false,+ }))+ const isTruncated = ran.exitCode === 0 && ran.isStdoutTruncated === true+ const files = ran.exitCode === 0 ? parsePatch(ran.stdout) : []+ const view: DiffView = {+ fetchedAt: await $.clock.now(),+ // The last file of a cut patch may end mid-hunk.+ files: isTruncated ? files.slice(0, -1) : files,+ isTruncated,+ error:+ ran.exitCode === 0+ ? null+ : printable(stripAnsi(ran.stderr).trim()) || `wt step diff exited ${ran.exitCode}`,+ }+ await update($, diffs, all => ({ ...all, [root]: view }))+}++async function reload($: EngineInterface) {+ await note($, [await noteHere($)])+ await refresh($)+}++async function select($: EngineInterface, root: string) {+ await update($, selected, () => root)+ await update($, cursor, () => -1)+}++// A pick in the pane also brings the new worktree's top into view, before+// the refresh, so a scroll the person makes while it runs stands.+async function pick($: EngineInterface, root: string) {+ await select($, root)+ await $.ui.scroll({ to: 'start', in: PANE })+ await refresh($)+}++async function move($: EngineInterface, by: number) {+ const root = await read($, selected)+ const files = root === null ? [] : ((await read($, diffs))[root]?.files ?? [])+ if (files.length === 0) {+ return+ }+ // `k` from the first file goes back to the top.+ const at = await update($, cursor, n => Math.min(files.length - 1, Math.max(-1, n + by)))+ const file = files[at]+ await $.ui.scroll(+ file === undefined+ ? { to: 'start', in: PANE }+ : { to: { key: `hunk:${file.path}` }, in: PANE, block: 'start' },+ )+}++async function jump($: EngineInterface, index: number, path: string) {+ await update($, cursor, () => index)+ await $.ui.scroll({ to: { key: `hunk:${path}` }, in: PANE, block: 'start' })+}++async function backToTop($: EngineInterface) {+ await update($, cursor, () => -1)+ await $.ui.scroll({ to: 'start', in: PANE })+}++/** The worktree root of `branch` in the repository at `cwd`, from `wt list`. */+async function worktreeOf(+ $: EngineInterface,+ cwd: string,+ branch: string,+): Promise<string | null> {+ const ran = await $.process+ .run(['wt', '-C', cwd, ...LIST_JSON], { timeoutMs: 60_000 })+ .catch(() => null)+ if (ran === null || ran.exitCode !== 0) {+ return null+ }+ try {+ const parsed = JSON.parse(ran.stdout) as {+ items?: { branch?: string | null; worktree?: { path?: string } }[]+ }+ return parsed.items?.find(item => item.branch === branch)?.worktree?.path ?? null+ } catch {+ return null+ }+}++/**+ * The hunks each file draws within the budget, by index: the file at `at`+ * first, cut to its whole hunks that fit (or the start of its first, when even+ * that does not), then every other file that fits whole.+ */+function drawnFiles(files: readonly FileDiff[], at: number): Map<number, string> {+ const drawn = new Map<number, string>()+ const selected = files[at]+ if (selected !== undefined) {+ let kept = ''+ for (const hunk of selected.hunks.split(/\n(?=@@)/)) {+ const next = kept === '' ? hunk : `${kept}\n${hunk}`+ if (next.length > BUDGET) {+ kept = kept === '' ? hunkStart(hunk, BUDGET) : kept+ break+ }+ kept = next+ }+ drawn.set(at, kept)+ }+ let used = drawn.get(at)?.length ?? 0+ files.forEach((file, index) => {+ if (!drawn.has(index) && used + file.hunks.length <= BUDGET) {+ drawn.set(index, file.hunks)+ used += file.hunks.length+ }+ })+ return drawn+}++/**+ * The lines of `hunk` that fit in `room` characters, under a header recounted+ * to them so the start still parses as a hunk; a first line longer than the+ * room is cut short.+ */+function hunkStart(hunk: string, room: number): string {+ const [header = '', ...lines] = hunk.split('\n')+ const kept: string[] = []+ let size = header.length+ for (const line of lines) {+ if (size + 1 + line.length > room) {+ if (kept.length === 0) {+ kept.push(line.slice(0, Math.max(1, room - size - 1)))+ }+ break+ }+ kept.push(line)+ size += 1 + line.length+ }+ const before = kept.filter(line => /^[ -]/.test(line)).length+ const after = kept.filter(line => /^[ +]/.test(line)).length+ return [+ header.replace(/^@@ -(\d+)(,\d+)? \+(\d+)(,\d+)? @@/, `@@ -$1,${before} +$3,${after} @@`),+ ...kept,+ ].join('\n')+}++function glyph(file: FileDiff): string {+ return { added: 'A', deleted: 'D', renamed: 'R', modified: 'M', binary: 'B' }[file.status]+}++function sum(files: readonly FileDiff[], key: 'added' | 'deleted'): number {+ return files.reduce((total, file) => total + file[key], 0)+}++function summary(row: Row): string {+ const parts: string[] = []+ if (row.isMain) {+ parts.push('main worktree')+ }+ if (row.ahead > 0 || row.behind > 0) {+ parts.push(`β${row.ahead} β${row.behind}`)+ }+ const { committed: c, uncommitted: u } = row+ if (c.added + c.deleted > 0) {+ parts.push(`committed +${c.added} -${c.deleted}`)+ }+ if (u.added + u.deleted > 0) {+ parts.push(`uncommitted +${u.added} -${u.deleted}`)+ }+ return parts.join(' Β· ')+}++/** The rows of `wt list --format=json` output for the worktrees at `roots`. */+function readRows(json: string, roots: readonly string[]): Row[] {+ type Item = {+ branch?: string | null+ worktree?: {+ path?: string+ main?: boolean+ changes?: { diff?: { added?: number; deleted?: number } }+ }+ default_branch?: {+ ahead?: number+ behind?: number+ diff?: { added?: number; deleted?: number }+ }+ }+ let parsed: { repo?: { default_branch?: string }; items?: Item[] }+ try {+ parsed = JSON.parse(json)+ } catch {+ return []+ }+ const target = parsed.repo?.default_branch ?? null+ return (parsed.items ?? []).flatMap(item => {+ const path = item.worktree?.path+ if (path === undefined || !roots.includes(path)) {+ return []+ }+ const uncommitted = item.worktree?.changes?.diff+ const committed = item.default_branch?.diff+ return [+ {+ root: path,+ branch: item.branch ?? null,+ target,+ ahead: item.default_branch?.ahead ?? 0,+ behind: item.default_branch?.behind ?? 0,+ committed: { added: committed?.added ?? 0, deleted: committed?.deleted ?? 0 },+ uncommitted: { added: uncommitted?.added ?? 0, deleted: uncommitted?.deleted ?? 0 },+ isMain: item.worktree?.main === true,+ },+ ]+ })+}++/** The absolute paths a Bash call changed, where the engine recorded them. */+function changedFiles(result: unknown): string[] {+ const paths = (result as { bashEditDiff?: { changedFiles?: unknown } } | undefined)+ ?.bashEditDiff?.changedFiles+ return Array.isArray(paths) ? paths.filter(p => typeof p === 'string') : []+}++function parentOf(path: string): string {+ return path.replace(/\/[^/]*\/?$/, '') || '/'+}++function baseName(path: string): string {+ return path.replace(/\/$/, '').replace(/^.*\//, '')+}++function stripAnsi(text: string): string {+ // CSI sequences, and OSC 8 hyperlinks ending in ESC \.+ return text.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u001b]*\u001b\\/g, '')+}diff --git a/plugins/worktrunk/skills/worktrunk/reference/claude-code.md b/plugins/worktrunk/skills/worktrunk/reference/claude-code.mdindex ac51c7f44..4f286a961 100644--- a/plugins/worktrunk/skills/worktrunk/reference/claude-code.md+++ b/plugins/worktrunk/skills/worktrunk/reference/claude-code.md@@ -8,6 +8,7 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de| Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β || Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |+| `/wt-diff` pane | β | | | | | |The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly.@@ -138,6 +139,24 @@ Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktClaude Code asks for confirmation before a session enters an existing worktree by path outside `.claude/worktrees/`, which in worktrunk's default layout is every worktree. The plugin's `PermissionRequest` hook answers yes for a worktree of the repository the session is working in that sits where `worktree-path` puts its branch, so a background session doesn't stop at that prompt. Entering any other worktree still asks.+## `/wt-diff` pane (Claude Code only)++`/wt-diff` opens a pane beside the conversation that lists the worktrees the session has worked in, with the selected one's [`wt step diff`](https://worktrunk.dev/step/#wt-step-diff) below: everything since the branch left the default branch, committed, uncommitted, and untracked. `/wt-diff <branch>` selects another worktree.++A worktree joins the list when the session starts or moves into it, or when the session or one of its subagents edits a file there or runs a command there that isn't read-only. Until the pane first opens, the pane only notes those directories, without running `git` or `wt`.++| Key | Action |+|---|---|+| `1`β`9` | Select a worktree |+| `j` / `k` | Next or previous file |+| `ctrl+β` / `ctrl+β` | Next or previous file, from the prompt |+| `r` | Refresh |+| β β, PageUp, PageDown | Scroll |++The other keys work while the pane has the keyboard, which it takes when it opens. Running `/wt-diff` again gives it back, as does `ctrl+x tab`, which moves focus from the prompt to the line above it when another plugin draws one, then to the pane. `esc` returns to the prompt.++The pane needs a Claude Code release that loads plugin hooks modules; earlier releases load the rest of the plugin without it.+## Statusline (Claude Code only)`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. Claude Code runs it in the background, which is what makes the occasional 1β2 second CI fetch invisible.diff --git a/plugins/worktrunk/tests/diff.test.tsx b/plugins/worktrunk/tests/diff.test.tsxnew file mode 100644index 000000000..6486158f0--- /dev/null+++ b/plugins/worktrunk/tests/diff.test.tsx@@ -0,0 +1,353 @@+import { expect, mock, test } from 'claude-code/testing'+import type { On } from 'claude-code'++import { parsePatch } from '../hooks/patch'++const PATCH = [+ 'diff --git a/src/lib.rs b/src/lib.rs',+ 'index 1111111..2222222 100644',+ '--- a/src/lib.rs',+ '+++ b/src/lib.rs',+ '@@ -1,2 +1,2 @@',+ ' fn a() {}',+ '-fn b() {}',+ '+fn c() {}',+ 'diff --git a/new.txt b/new.txt',+ 'new file mode 100644',+ 'index 0000000..3333333',+ '--- /dev/null',+ '+++ b/new.txt',+ '@@ -0,0 +1 @@',+ '+hello\r',+ 'diff --git a/old.txt b/old.txt',+ 'deleted file mode 100644',+ 'index 4444444..0000000',+ '--- a/old.txt',+ '+++ /dev/null',+ '@@ -1 +0,0 @@',+ '-bye',+ 'diff --git a/logo.png b/logo.png',+ 'index 5555555..6666666 100644',+ 'Binary files a/logo.png and b/logo.png differ',+ 'diff --git a/x.md b/y.md',+ 'similarity index 100%',+ 'rename from x.md',+ 'rename to y.md',+ 'diff --git a/my file.txt b/my file.txt',+ 'index 7777777..8888888 100644',+ '--- a/my file.txt\t',+ '+++ b/my file.txt\t',+ '@@ -1,2 +1,2 @@',+ ' a',+ '-b',+ '+c',+ 'diff --git a/run.sh b/run.sh',+ 'old mode 100644',+ 'new mode 100755',+ // Names git still quotes under `core.quotePath=false`.+ 'diff --git "a/q\\"uote.png" "b/q\\"uote.png"',+ 'index f584f40..6bf43ff 100644',+ 'Binary files "a/q\\"uote.png" and "b/q\\"uote.png" differ',+ 'diff --git "a/tab\\tname.txt" "b/tab\\tname.txt"',+ 'index 587be6b..975fbec 100644',+ '--- "a/tab\\tname.txt"',+ '+++ "b/tab\\tname.txt"',+ '@@ -1 +1 @@',+ '-x',+ '+y',+ '',+].join('\n')++test('a patch splits into its files', async () => {+ const files = parsePatch(PATCH)+ expect(files.map(f => [f.path, f.status, f.added, f.deleted])).toEqual([+ ['src/lib.rs', 'modified', 1, 1],+ ['new.txt', 'added', 1, 0],+ ['old.txt', 'deleted', 0, 1],+ ['logo.png', 'binary', 0, 0],+ ['y.md', 'renamed', 0, 0],+ ['my file.txt', 'modified', 1, 1],+ ['run.sh', 'modified', 0, 0],+ ['q"uote.png', 'binary', 0, 0],+ ['tab\tname.txt', 'modified', 1, 1],+ ])+ expect(files.map(f => f.note)).toEqual([+ null,+ null,+ null,+ null,+ 'from x.md',+ null,+ 'mode 100644 β 100755',+ null,+ null,+ ])+ // A CRLF file's carriage return is no control character a drawing takes.+ expect(files[1]?.hunks).toBe('@@ -0,0 +1 @@\n+helloοΏ½')+ expect(files[3]?.hunks).toBe('')+})++const HERE = '/r/wt'+const OTHER = '/r/wt.feature'++const LIST = JSON.stringify({+ schema: 1,+ repo: { default_branch: 'main' },+ items: [+ {+ branch: 'main',+ worktree: { path: HERE, main: true, changes: { diff: { added: 0, deleted: 0 } } },+ },+ {+ branch: 'feature',+ worktree: { path: OTHER, main: false, changes: { diff: { added: 2, deleted: 1 } } },+ default_branch: { ahead: 3, behind: 0, diff: { added: 40, deleted: 5 } },+ },+ { branch: 'unrelated', worktree: { path: '/r/wt.unrelated', main: false } },+ ],+})++const OPEN_PANE = {+ id: 'wt-diff',+ title: 'wt step diff',+ isShown: true,+ isFocused: true,+ isPlaced: true,+}++// What the engine stamps on a command the person typed.+const TYPED = {+ origin: { kind: 'composer' },+ presentation: { isFullscreen: true, columns: 160 },+} as const++const PANE = {+ plugin: 'worktrunk',+ component: 'Pane',+ requestId: 'wt-diff',+ props: {+ title: 'wt step diff',+ isFocused: true,+ bodyColumns: 80,+ placement: 'dock',+ scroll: { offset: 0, bodyRows: 40 },+ view: {},+ },+} as const++type Ran = { exitCode: number; stdout: string; stderr: string; isStdoutTruncated: boolean }++// Stands for the engine and the host: git and wt answer from fixtures, and+// `step` stands in for what `wt step diff` answers.+function host(on: On, runs: string[][], step: Partial<Ran> = {}) {+ mock.clock(on)+ on('command.register', () => ({ value: { command: 'wt-diff' } }))+ let isOpen = false+ on('ui.open', () => {+ isOpen = true+ return { value: { isPlaced: true } }+ })+ on('ui.panes', () => ({ value: isOpen ? [OPEN_PANE] : [] }))+ on('session.start', (_, e) => ({ cwd: e.cwd }))+ on('session.cwd', () => ({ value: HERE }))+ // Every directory exists but those under a `gone` one, deleted since.+ on('fs.stat', (_, e) => {+ if (e.path.includes('/gone')) {+ throw new Error(`ENOENT: ${e.path}`)+ }+ return { value: { kind: 'dir', size: 0, mtimeMs: 0, isLink: false } }+ })+ on('tool.call', () => ({ result: {} }))+ on('turn.complete', () => ({ text: '' }))+ on('process.run', (_, e) => {+ const argv = [...e.argv]+ runs.push(argv)+ const dir = argv[2] ?? ''+ const answer = (stdout: string) => ({+ value: { exitCode: 0, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false },+ })+ if (argv[0] === 'git') {+ return answer(`${dir.startsWith(OTHER) ? OTHER : HERE}\n${HERE}/.git\n`)+ }+ if (argv[3] === 'step') {+ return { value: { ...answer(PATCH).value, ...step } }+ }+ return answer(LIST)+ })+}++test('until /wt-diff runs, a session spawns no process and draws nothing', async ($, on) => {+ const runs: string[][] = []+ host(on, runs)++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.tool.call({+ tool: 'Edit',+ file_path: `${OTHER}/src/lib.rs`,+ old_string: 'b',+ new_string: 'c',+ })+ await $.tool.call({ tool: 'Bash', command: 'cargo test' })+ await $.turn.complete({+ answer: '',+ durationMs: 1,+ isAborted: false,+ turnId: 't1',+ reason: 'answer',+ })++ expect(runs).toEqual([])+})++test('the pane lists the worktrees the session worked in, and draws one diff', async ($, on) => {+ const runs: string[][] = []+ host(on, runs)++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.tool.call({+ tool: 'Edit',+ file_path: `${OTHER}/src/lib.rs`,+ old_string: 'b',+ new_string: 'c',+ })+ await $.command.run({ command: 'wt-diff', args: 'feature', ...TYPED })++ for (const surface of ['terminal', 'desktop'] as const) {+ const ui = await $.ui.mount({ ...PANE, surface })++ // Both worktrees the session touched, and not the one it never did.+ expect(await ui.find({ key: `wt:${HERE}` })).toBeDefined()+ const feature = await ui.find({ key: `wt:${OTHER}` })+ expect(feature?.text).toMatch(/feature.*β3 β0 Β· committed \+40 -5 Β· uncommitted \+2 -1/)+ expect(await ui.find({ key: 'wt:/r/wt.unrelated' })).toBeUndefined()++ // The selected worktree's files, each drawn as a diff unless it has no hunks.+ expect((await ui.find({ key: 'file:src/lib.rs' }))?.text).toMatch(/M src\/lib\.rs \+1 -1/)+ const codes = await ui.findAll({ type: 'Code' })+ expect(codes.length).toBe(5)+ expect(await ui.find({ type: 'Text', text: 'Binary file.' })).toBeDefined()+ await ui.unmount()+ }++ // The rows came in the envelope the pane reads, whatever the person's config.+ expect(runs).toContainEqual([+ 'wt',+ '-C',+ HERE,+ '--config-set',+ 'list.json-schema=2',+ 'list',+ '--format=json',+ ])+ // The diff came from Worktrunk, rooted at the selected worktree.+ expect(runs).toContainEqual([+ 'wt',+ '-C',+ OTHER,+ 'step',+ 'diff',+ '--',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ ])+})++test('a worktree is still listed after the directory edited in it is deleted', async ($, on) => {+ const runs: string[][] = []+ host(on, runs)++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.tool.call({+ tool: 'Write',+ file_path: `${OTHER}/gone/a/b/c/d/e/new.rs`,+ content: 'x',+ })+ await $.command.run({ command: 'wt-diff', args: '', ...TYPED })++ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })+ expect(await ui.find({ key: `wt:${OTHER}` })).toBeDefined()+ await ui.unmount()+ expect(runs).toContainEqual([+ 'git',+ '-C',+ OTHER,+ 'rev-parse',+ '--path-format=absolute',+ '--show-toplevel',+ '--git-common-dir',+ ])+})++test('a worktree whose diff fails shows why', async ($, on) => {+ host(on, [], {+ exitCode: 1,+ stdout: '',+ stderr: '\u001b[31mβ\u001b[39m No common ancestor with target branch',+ })++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'wt-diff', args: '', ...TYPED })+ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })+ expect((await ui.find({ type: 'Text', text: /common ancestor/ }))?.text).toBe(+ 'β No common ancestor with target branch',+ )+ await ui.unmount()+})++test('a patch past what a run captures drops its last file and says so', async ($, on) => {+ host(on, [], { isStdoutTruncated: true })++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'wt-diff', args: '', ...TYPED })+ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })+ expect(await ui.find({ type: 'Text', text: /passed 4 MiB/ })).toBeDefined()+ expect(await ui.find({ key: 'file:run.sh' })).toBeDefined()+ expect(await ui.find({ key: 'file:tab\tname.txt' })).toBeUndefined()+ await ui.unmount()+})++test('the selected file draws its first hunks even past the budget', async ($, on) => {+ const hunk = (at: number) =>+ [`@@ -${at},1 +${at},1 @@`, `-${'a'.repeat(50_000)}`, '+b'].join('\n')+ const big = [+ 'diff --git a/big.txt b/big.txt',+ '--- a/big.txt',+ '+++ b/big.txt',+ hunk(1),+ hunk(9),+ ]+ host(on, [], { stdout: `${big.join('\n')}\n` })++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'wt-diff', args: '', ...TYPED })+ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })+ const code = await ui.find({ type: 'Code' })+ expect(code?.text).toMatch(/^@@ -1,1 \+1,1 @@/)+ expect(code?.text).not.toMatch(/@@ -9,1/)+ expect(await ui.find({ type: 'Text', text: /rest of this file/ })).toBeDefined()+ await ui.unmount()+})++test('a hunk past the budget draws its start, under a recounted header', async ($, on) => {+ const minified = [+ 'diff --git a/min.js b/min.js',+ 'new file mode 100644',+ '--- /dev/null',+ '+++ b/min.js',+ '@@ -0,0 +1,2 @@',+ `+${'x'.repeat(120_000)}`,+ '+y',+ ]+ host(on, [], { stdout: `${minified.join('\n')}\n` })++ await $.session.start({ cwd: HERE, surface: 'terminal', isInteractive: true })+ await $.command.run({ command: 'wt-diff', args: '', ...TYPED })+ const ui = await $.ui.mount({ ...PANE, surface: 'terminal' })+ const code = await ui.find({ type: 'Code' })+ expect(code?.text).toMatch(/^@@ -0,0 \+1,1 @@\n\+x+$/)+ expect(code?.text.length).toBeLessThanOrEqual(80_000)+ expect(await ui.find({ type: 'Text', text: /rest of this file/ })).toBeDefined()+ await ui.unmount()+})diff --git a/plugins/worktrunk/tsconfig.json b/plugins/worktrunk/tsconfig.jsonnew file mode 100644index 000000000..8681ec01d--- /dev/null+++ b/plugins/worktrunk/tsconfig.json@@ -0,0 +1,3 @@+{+ "extends": "./.claude-plugin/types/tsconfig.json"+}diff --git a/plugins/worktrunk/types/index.d.ts b/plugins/worktrunk/types/index.d.tsnew file mode 100644index 000000000..660e458c5--- /dev/null+++ b/plugins/worktrunk/types/index.d.ts@@ -0,0 +1,67 @@+/** A directory the session worked in, as the hooks saw it: resolved to a worktree only once the pane opens. */+export type Seen = { dir: string; lastAt: number }++/** A worktree the session worked in, by its root. */+export type Touched = {+ root: string+ /** The repository's common git dir: worktrees sharing it share one `wt list`. */+ commonDir: string+ lastAt: number+}++/** Lines added and deleted. */+export type Lines = { added: number; deleted: number }++/** What `wt list --format=json` says of one worktree, as the pane shows it. */+export type Row = {+ root: string+ branch: string | null+ target: string | null+ /** Commits ahead of and behind the default branch. */+ ahead: number+ behind: number+ /** `mainβ¦Β±`: committed changes since the merge base. */+ committed: Lines+ /** `HEADΒ±`: uncommitted changes, untracked files included. */+ uncommitted: Lines+ isMain: boolean+}++/** One file of a `wt step diff`. */+export type FileDiff = {+ path: string+ status: 'added' | 'deleted' | 'renamed' | 'modified' | 'binary'+ added: number+ deleted: number+ /** What the hunks don't show: `from <path>` for a rename, a mode change. */+ note: string | null+ /** The file's hunks from its first `@@`, empty for a binary or mode-only change. */+ hunks: string+}++/** One worktree's `wt step diff`, or why there is none. */+export type DiffView = {+ fetchedAt: number+ files: FileDiff[]+ /** Whether the patch passed what `$.process.run` captures, its last file dropped. */+ isTruncated: boolean+ error: string | null+}++declare module 'claude-code' {+ interface PluginState {+ worktrunk: {+ seen: Shaped<Seen[]>+ /** The session's own directory, as a hook of the main loop last read it. */+ here: string | null+ touched: Shaped<Touched[]>+ rows: Shaped<Row[]>+ /** The root of the worktree `here` is in. */+ current: string | null+ selected: string | null+ diffs: Shaped<Record<string, DiffView>>+ /** The file `j` and `k` last moved to, by index into the selected diff; -1 at the top. */+ cursor: number+ }+ }+}diff --git a/skills/worktrunk/reference/claude-code.md b/skills/worktrunk/reference/claude-code.mdindex ac51c7f44..4f286a961 100644--- a/skills/worktrunk/reference/claude-code.md+++ b/skills/worktrunk/reference/claude-code.md@@ -8,6 +8,7 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de| Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β || Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |+| `/wt-diff` pane | β | | | | | |The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly.@@ -138,6 +139,24 @@ Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktClaude Code asks for confirmation before a session enters an existing worktree by path outside `.claude/worktrees/`, which in worktrunk's default layout is every worktree. The plugin's `PermissionRequest` hook answers yes for a worktree of the repository the session is working in that sits where `worktree-path` puts its branch, so a background session doesn't stop at that prompt. Entering any other worktree still asks.+## `/wt-diff` pane (Claude Code only)++`/wt-diff` opens a pane beside the conversation that lists the worktrees the session has worked in, with the selected one's [`wt step diff`](https://worktrunk.dev/step/#wt-step-diff) below: everything since the branch left the default branch, committed, uncommitted, and untracked. `/wt-diff <branch>` selects another worktree.++A worktree joins the list when the session starts or moves into it, or when the session or one of its subagents edits a file there or runs a command there that isn't read-only. Until the pane first opens, the pane only notes those directories, without running `git` or `wt`.++| Key | Action |+|---|---|+| `1`β`9` | Select a worktree |+| `j` / `k` | Next or previous file |+| `ctrl+β` / `ctrl+β` | Next or previous file, from the prompt |+| `r` | Refresh |+| β β, PageUp, PageDown | Scroll |++The other keys work while the pane has the keyboard, which it takes when it opens. Running `/wt-diff` again gives it back, as does `ctrl+x tab`, which moves focus from the prompt to the line above it when another plugin draws one, then to the pane. `esc` returns to the prompt.++The pane needs a Claude Code release that loads plugin hooks modules; earlier releases load the rest of the plugin without it.+## Statusline (Claude Code only)`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. Claude Code runs it in the background, which is what makes the occasional 1β2 second CI fetch invisible.