Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.
TypeScript
diff: run git when the built-in panel would, never at the session's start (#94594)
Alice T'Poteat7dd06361110d
diff --git a/mods/diff/README.md b/mods/diff/README.mdindex ee047cc3..7e660973 100644--- a/mods/diff/README.md+++ b/mods/diff/README.md@@ -11,11 +11,11 @@ click puts that file's hunks at the top; the list also scrolls under thebuilt-in's list keys (`ctrl+up`/`ctrl+down`, `opt+up`/`opt+down`), and`ctrl+x b` moves the comparison base on, as the built-in's chord does: boththrough Buttons that declare the engine's own actions. The pane refreshes-as Claude edits, runs shell commands and finishes turns, and while it is-open it polls the repository's HEAD so a commit or checkout made elsewhere-shows too. The first successful edit of a session opens the pane by itself-where the terminal is wide enough (144 columns when the person never chose,-110 when they kept it open before; a person who closed it is left alone).+as Claude edits and runs shell commands, and while it is open it polls+the repository's HEAD so a commit or checkout made elsewhere shows too.+The first successful edit of a session opens the pane by itself where the+terminal is wide enough (144 columns when the person never chose, 110 when+they kept it open before; a person who closed it is left alone).Under the fullscreen layout a terminal under 110 columns gets thebuilt-in's line asking for a wider one and nothing opens. Without that@@ -36,10 +36,20 @@ the default branch; the base line under the header names a base other thanthe session's, and the choice is kept per repository in the plugin's store.A picker shows one earlier turn's edits instead of the working tree, readfrom the session's messages. Files that changed before the session started-(by their timestamp, among the paths already dirty at the start), and noise-(lockfiles, generated and test files), are listed apart and folded until-asked for; a rename lists as git prints it. Outside a git repository-`/diff` says so and does nothing else.+(by their timestamp, among the paths already dirty when the pane first+read the repository), and noise (lockfiles, generated and test files), are+listed apart and folded until asked for; a rename lists as git prints it.+Outside a git repository `/diff` says so and does nothing else.++Git runs when the built-in panel's would: nothing at the session's start;+one `git rev-parse`, in the directory the session started in, when `/diff`+or the first edit a pane has room to open on first needs the repository+(an answer of no repository is kept too, until `/clear` or `/resume`+forgets it); and the working tree is read only by a fetch for a pane that+is open, after an edit that landed or a shell command that ran. The one+read the built-in has no counterpart for is a `git status` at a pane's+first fetch, which stands in for the change time the built-in dates a+moved file by.`hooks/register.ts` is the module; everything under `hooks/` is its parts.@@ -47,17 +57,16 @@ asked for; a rename lists as git prints it. Outside a git repository| event | what the hook does || --- | --- |-| `session.start` | Binds the engine once, registers `/diff` (a session where another `/diff` is listed leaves the plugin idle), and pins the repository. |+| `session.start` | Binds the engine once and registers `/diff` (a session where another `/diff` is listed leaves the plugin idle); asks nothing of the repository, which `/diff` or the first edit pins when it comes. || `ui.render` of `PromptHint` | Reads the terminal's width, which decides whether the first edit opens the pane. || `ui.render` of `Pane` | Draws the pane: docked, the header, base line, source picker, file list and toggles over the window of hunks; inline, the dialog. |-| `command.run` of `diff` | Opens or closes the pane (focused and closing on Escape without the fullscreen layout), says which, and remembers the choice. |+| `command.run` of `diff` | Pins the repository when none is, opens or closes the pane (focused and closing on Escape without the fullscreen layout), says which, and remembers the choice. || `ui.close` of the pane | Backs out of the dialog's detail view instead of closing; else remembers the person's close as `/diff`'s. || `ui.scroll` of the pane | Docked, moves the hunks under the pinned header and list (three rows a wheel tick, a page a page key), or the list when the wheel is over it, and keeps the engine's window still. || `ui.focus` in the pane | In the dialog's list, selects the file the ring lands on, re-centres the five rows on it, and lands the ring where that row now sits. |-| `command.run` of `clear`, `resume` | Closes the pane and forgets the session's state. |-| `tool.call` of `Edit`, `Write`, `NotebookEdit` | After the edit, refreshes an open pane; the session's first successful edit opens it. |-| `tool.call` of `Bash`, `PowerShell` | After the command, refreshes an open pane. |-| `turn.complete` | Refreshes an open pane. |+| `command.run` of `clear`, `resume` | Closes the pane and forgets the session's state, the pinned repository with it. |+| `tool.call` of `Edit`, `Write`, `NotebookEdit` | After an edit that landed (not refused, not failed), refreshes an open pane; the session's first such edit opens it, pinning the repository then if the terminal has the room. |+| `tool.call` of `Bash`, `PowerShell` | After a command that was not refused, failed and interrupted ones too, refreshes an open pane. || `prompt.submit` | Adds the armed file's hunks to the prompt's context and disarms. |## What it calls on `$`diff --git a/mods/diff/hooks/git/git-backend-of.ts b/mods/diff/hooks/git/git-backend-of.tsindex 57da1213..fb4a65ba 100644--- a/mods/diff/hooks/git/git-backend-of.ts+++ b/mods/diff/hooks/git/git-backend-of.ts@@ -15,7 +15,7 @@ import type Types from './types'** Each child runs with `--git-dir`, `--work-tree` and cwd the top, under* the C locale and the fetch's timeout (the built-in's execPinnedGit); the- * paths dirty at the start are read once, first (Probes.dirtyPathsOf).+ * first fetch reads the paths dirty then, once (Probes.dirtyPathsOf).** @param host the bound host's runner and probes* @returns the backend, or null outside a git working tree@@ -47,15 +47,16 @@ export async function gitBackendOf(}const run = runOf(repository)- const baseline = await Probes.dirtyPathsOf(run)- const depsOf = (): Types.GitDeps => ({+ let baseline: Promise<ReadonlySet<string> | null> | null = null++ const depsOf = (dirty: ReadonlySet<string> | null): Types.GitDeps => ({run,repository,mtimeOf: host.mtimeOf,entryKindsOf: host.entryKindsOf,sessionStartMs: host.sessionStartMsOf(),- baseline,+ baseline: dirty,onBranchBase: host.onBranchBase,})@@ -63,9 +64,16 @@ export async function gitBackendOf(repository,baseModes: GIT_BASE_MODES,words: GIT_WORDS,- fetchDiff: mode => fetchDiff(depsOf(), mode),+ fetchDiff: async mode => {+ baseline ??= Probes.dirtyPathsOf(run)++ return fetchDiff(depsOf(await baseline), mode)+ },fetchFileHunks: (data, file) => fetchFileHunks(run, data, file),headKeyOf: () =>- Probes.headKeyOf({ ...depsOf(), readFile: host.readFile }, repository),+ Probes.headKeyOf(+ { ...depsOf(null), readFile: host.readFile },+ repository,+ ),}}diff --git a/mods/diff/hooks/git/probes/dirty-paths-of/dirty-paths-of.ts b/mods/diff/hooks/git/probes/dirty-paths-of/dirty-paths-of.tsindex b5e80d90..a92e6f3b 100644--- a/mods/diff/hooks/git/probes/dirty-paths-of/dirty-paths-of.ts+++ b/mods/diff/hooks/git/probes/dirty-paths-of/dirty-paths-of.ts@@ -7,9 +7,9 @@ import { STATUS_PATH_OFFSET } from './status-path-offset'* Every path dirty in the working tree right now, tracked changes and* untracked files alike, as `git status -z` lists them; null unread.*- * Read once when the backend is pinned, so a fetch can tell a path that- * was already dirty when the session began from one that turned up since- * (GitDeps `baseline`). Renames are not paired: each side is its own path.+ * Read once, by the backend's first fetch (it walks the whole tree), so a+ * later fetch can tell a path that was dirty then from one that turned up+ * since (GitDeps `baseline`). Renames unpaired: each side is its own path.** @param run runs git against the pinned repository* @returns the paths, root-relative, or null on a failed or cut listingdiff --git a/mods/diff/hooks/git/probes/was-dirty-at-start/was-dirty-at-start.ts b/mods/diff/hooks/git/probes/was-dirty-at-start/was-dirty-at-start.tsindex ebab19bd..5472cc1a 100644--- a/mods/diff/hooks/git/probes/was-dirty-at-start/was-dirty-at-start.ts+++ b/mods/diff/hooks/git/probes/was-dirty-at-start/was-dirty-at-start.ts@@ -2,7 +2,7 @@ import type Types from '../../types'/*** Whether a path may predate the session at all: it was dirty when the- * session began, or nothing says otherwise (no baseline was read).+ * baseline was read (the first fetch), or nothing says otherwise (none was).** A path missing from the baseline turned up since, so its old timestamp* (a rename keeps the file's, a move keeps the source's) does not date it,@@ -12,7 +12,5 @@ import type Types from '../../types'* @param path the root-relative path* @returns false only when a baseline exists and lacks the path*/-export const wasDirtyAtStart = (- context: Types.DatingContext,- path: string,-): boolean => context.deps.baseline?.has(path) ?? true+export const wasDirtyAtStart = (context: Types.DatingContext, path: string) =>+ context.deps.baseline?.has(path) ?? truediff --git a/mods/diff/hooks/git/types/git-deps/git-deps.ts b/mods/diff/hooks/git/types/git-deps/git-deps.tsindex 7a9df428..103c63d7 100644--- a/mods/diff/hooks/git/types/git-deps/git-deps.ts+++ b/mods/diff/hooks/git/types/git-deps/git-deps.ts@@ -33,11 +33,11 @@ export type GitDeps = {sessionStartMs: number/**- * The paths dirty when the backend was pinned, at the session's start- * (Probes.dirtyPathsOf); null when unlisted, absent where none is kept.+ * The paths dirty when the backend first fetched (Probes.dirtyPathsOf),+ * read then and kept; null when unlisted, absent where none is kept.*- * A path absent from it turned up during the session (a rename's new- * name, a file moved in), whatever timestamp it carries.+ * A path absent from it turned up since (a rename's new name, a file+ * moved in), whatever timestamp it carries.*/baseline?: ReadonlySet<string> | nulldiff --git a/mods/diff/hooks/register.ts b/mods/diff/hooks/register.tsindex c2cd48a7..54d9095c 100644--- a/mods/diff/hooks/register.ts+++ b/mods/diff/hooks/register.ts@@ -29,9 +29,9 @@ import Views from './views'* Registers the diff pane: `/diff` once the built-in stands down, the* pane's drawing and refresh, its opening on Claude's first edit, the ask.*- * `session.start` registers `/diff`, binds the host every pinned backend- * reads through (currentOf: the latest start's, the engine only before- * bind()), and pins the backend (backendOf), asked again on `/diff`.+ * Git runs when the built-in's would: `session.start` binds the host and+ * registers `/diff`; `/diff` or the first edit with room pins the backend+ * where the session started, until `/clear`; an open pane alone fetches.** @param on the engine's registrar*/@@ -56,6 +56,7 @@ export function register(on: On) {const bodyLoads = new Map<string, Promise<Git.FileHunks | null>>()const polled = { toplevel: '', headKey: '' }+ const pin = { cwd: '', isEmpty: false, epoch: 0 }let model: PaneState.PaneModel = PaneState.INITIAL_MODEL@@ -65,7 +66,11 @@ export function register(on: On) {const currentOf = (engine: Host): Host => host ?? engineconst backendHostOf = (engine: Host): Backend.BackendHost => ({- run: (argv, init) => currentOf(engine).run(argv, init),+ run: (argv, init) =>+ currentOf(engine).run(+ argv,+ pin.cwd === '' ? init : { cwd: pin.cwd, ...init },+ ),readFile: path => currentOf(engine).readFile(path),mtimeOf: path => mtimeOf(currentOf(engine))(path),entryKindsOf: dir => entryKindsOf(currentOf(engine))(dir),@@ -95,7 +100,7 @@ export function register(on: On) {})function pinBackend(engine: Host): Promise<boolean> {- if (backend) {+ if (backend || pin.isEmpty) {return Promise.resolve(true)}@@ -109,6 +114,7 @@ export function register(on: On) {async function probeBackend(engine: Host): Promise<boolean> {const asked = { isAnswered: true }const probeHost = backendHostOf(engine)+ const { epoch } = pinconst probed = await Backend.backendOf({@@ -124,7 +130,12 @@ export function register(on: On) {Backend.INSTALLED_BACKEND_PROBES,)+ if (epoch !== pin.epoch) {+ return false+ }+backend ??= probed+ pin.isEmpty = backend === null && asked.isAnsweredif (!probed || backend !== probed) {return asked.isAnswered || backend !== null@@ -148,6 +159,16 @@ export function register(on: On) {return true}+ function unpin() {+ backend = null+ pin.isEmpty = false+ pin.epoch += 1+ polled.toplevel = ''+ polled.headKey = ''+ timers.get('poll')?.cancel()+ timers.delete('poll')+ }+function dialogPane(): PaneOpenArgs {return {id: Names.PANE_ID,@@ -423,23 +444,25 @@ export function register(on: On) {}const preference = await engine.storeGet(Names.STORE_OPEN_KEY)-- await pinBackend(engine)-const isKeptOpen = preference === trueconst floor = isKeptOpen? Limits.OPEN_MIN_COLUMNS: Limits.AUTO_OPEN_MIN_COLUMNS- const isEligible =+ const hasRoom =preference !== false &&model.isFullscreen !== false &&columns !== null &&- columns >= floor &&- backend !== null+ columns >= floor- if (!isEligible || isTaken()) {+ if (!hasRoom || isTaken()) {+ return+ }++ await pinBackend(engine)++ if (!backend || isTaken()) {return}@@ -551,8 +574,9 @@ export function register(on: On) {redraw(engine)}- async function bind(engine: Host): Promise<void> {+ async function bind(engine: Host, cwd: string): Promise<void> {sessionStartMs = await engine.now()+ pin.cwd = cwdtry {await engine.registerCommand(COMMAND_SPEC)@@ -563,35 +587,34 @@ export function register(on: On) {if (!Names.BUILTIN_HOLDS_PATTERN.test(reason)) {engine.uiLog(Names.registerFailedTextOf(Views.sanitizeName(reason)))}-- return}-- await pinBackend(engine)}on('session.start', async ($, e, next) => {- await bind({- now: () => $.clock.now(),- after: (ms, fn) => $.clock.after(ms, fn),- every: (ms, fn) => $.clock.every(ms, fn),- run: (argv, init) => $.process.run(argv, init),- stat: path => $.fs.stat(path),- listDir: path => $.fs.list(path),- readFile: path => $.fs.read(path),- storeGet: key => $.store.get(key),- storeSet: (key, value) => $.store.set(key, value),- messages: () => $.session.messages(),- invalidate: () => $.ui.invalidate('ui.render'),- status: text => $.ui.status(text),- uiLog: text => $.ui.log(text),- openPane: pane => $.ui.open(pane),- closePane: pane => $.ui.close(pane),- registerCommand: spec => $.command.register(spec),- sessionId: () => $.session.id(),- mark: entry => $.telemetry.mark(entry),- log: entry => $.telemetry.log(entry),- })+ await bind(+ {+ now: () => $.clock.now(),+ after: (ms, fn) => $.clock.after(ms, fn),+ every: (ms, fn) => $.clock.every(ms, fn),+ run: (argv, init) => $.process.run(argv, init),+ stat: path => $.fs.stat(path),+ listDir: path => $.fs.list(path),+ readFile: path => $.fs.read(path),+ storeGet: key => $.store.get(key),+ storeSet: (key, value) => $.store.set(key, value),+ messages: () => $.session.messages(),+ invalidate: () => $.ui.invalidate('ui.render'),+ status: text => $.ui.status(text),+ uiLog: text => $.ui.log(text),+ openPane: pane => $.ui.open(pane),+ closePane: pane => $.ui.close(pane),+ registerCommand: spec => $.command.register(spec),+ sessionId: () => $.session.id(),+ mark: entry => $.telemetry.mark(entry),+ log: entry => $.telemetry.log(entry),+ },+ e.cwd,+ )return next(e)})@@ -773,6 +796,7 @@ export function register(on: On) {await closePane(host).catch(() => undefined)}+ unpin()hasAutoOpened = falsebodyStamp = nullbodyBase = null@@ -784,45 +808,49 @@ export function register(on: On) {return result})- on('tool.call', { tool: [...Tools.EDITING_TOOLS] }, async ($, e, next) => {- let result: ResultOf['tool.call'] | undefined-- try {- result = await next(e)+ function afterTool(+ engine: Host,+ tool: string,+ result: ResultOf['tool.call'] | undefined,+ ) {+ const isEdit = Tools.EDITING_TOOLS.some(name => name === tool)- return result- } finally {- if (host) {- if (isPaneOpen) {- scheduleRefresh(host)- }+ const hasEdited =+ isEdit &&+ result !== undefined &&+ result.deny === undefined &&+ result.isError !== true- const isEditDone = result !== undefined && !('deny' in result)+ const isStale =+ isPaneOpen &&+ (isEdit ? hasEdited : result === undefined || result.deny === undefined)- if (isEditDone) {- void openOnFirstEdit(host).catch(() => undefined)- }- }+ if (isStale) {+ scheduleRefresh(engine)}- })- on('tool.call', { tool: [...Tools.SHELL_TOOLS] }, async ($, e, next) => {- try {- return await next(e)- } finally {- if (host && isPaneOpen) {- scheduleRefresh(host)- }+ if (hasEdited) {+ void openOnFirstEdit(engine).catch(() => undefined)}- })+ }- on('turn.complete', ($, e, next) => {- if (host && isPaneOpen) {- scheduleRefresh(host)- }+ on(+ 'tool.call',+ { tool: [...Tools.EDITING_TOOLS, ...Tools.SHELL_TOOLS] },+ async ($, e, next) => {+ let result: ResultOf['tool.call'] | undefined- return next(e)- })+ try {+ result = await next(e)++ return result+ } finally {+ if (host) {+ afterTool(host, e.tool, result)+ }+ }+ },+ )on('prompt.submit', async ($, e, next) => {const asked = armeddiff --git a/mods/diff/tests/backend/backend-of.test.ts b/mods/diff/tests/backend/backend-of.test.tsindex d90ca3ab..8103c7d1 100644--- a/mods/diff/tests/backend/backend-of.test.ts+++ b/mods/diff/tests/backend/backend-of.test.ts@@ -13,10 +13,10 @@ describe('backend-of', () => {expect((await Backend.backendOf(inGit.host, []))?.words.lister).toBe('git')expect(await Backend.backendOf(outside.host, [])).toBeNull()- expect([inGit.programs, outside.programs]).toEqual([- ['git', 'git'],- ['git'],- ])+ expect(+ [inGit.programs, outside.programs],+ 'pinning spawns the one rev-parse and walks nothing',+ ).toEqual([['git'], ['git']])})test('a declining probe leaves a git working tree to git', async () => {@@ -27,7 +27,7 @@ describe('backend-of', () => {expect(backend?.words.lister).toBe('git')expect(backend?.baseModes).toEqual(['session', 'uncommitted', 'branch'])expect(declining.asked).toEqual([inGit.host])- expect(inGit.programs).toEqual(['git', 'git'])+ expect(inGit.programs).toEqual(['git'])})test('a probe that answers pins before git is asked', async () => {diff --git a/mods/diff/tests/fixtures/git-word-of.ts b/mods/diff/tests/fixtures/git-word-of.tsnew file mode 100644index 00000000..d8a06509--- /dev/null+++ b/mods/diff/tests/fixtures/git-word-of.ts@@ -0,0 +1,36 @@+/**+ * One git invocation named by what it asks: its subcommand, and its kind.+ *+ * For a `diff` what kind (`--shortstat`, `--numstat`, or the path its body+ * is asked for), for a `rev-parse` whether it finds the repository+ * (`--show-toplevel`) or reads `HEAD` (the poll's fallback where no file+ * answers), so a test reads a session's spawns as the built-in's list.+ *+ * @param argv the invocation, program first, any pinned lead after it+ * @returns `rev-parse --show-toplevel`, `status`, `diff --numstat`, ...+ */+export function gitWordOf(argv: readonly string[]) {+ const [subcommand = '?'] = argv.filter(+ (word, at) => at > 0 && !word.startsWith('-') && argv[at - 1] !== '-c',+ )++ const dashes = argv.indexOf('--')++ if (subcommand === 'rev-parse') {+ return argv.includes('--show-toplevel')+ ? 'rev-parse --show-toplevel'+ : 'rev-parse HEAD'+ }++ if (subcommand !== 'diff') {+ return subcommand+ }++ if (dashes !== -1) {+ return `diff -- ${argv.slice(dashes + 1).join(' ')}`+ }++ const stat = argv.find(word => word === '--shortstat' || word === '--numstat')++ return stat ? `diff ${stat}` : 'diff'+}diff --git a/mods/diff/tests/fixtures/index.ts b/mods/diff/tests/fixtures/index.tsindex 1fb054e1..27c2b669 100644--- a/mods/diff/tests/fixtures/index.ts+++ b/mods/diff/tests/fixtures/index.ts@@ -15,6 +15,7 @@ export * from './edit-patch-of.js'export * from './fetch-diff'export * from './git-hung.js'export * from './git-in.js'+export * from './git-word-of.js'export * from './head-key-of'export * from './header-totals-of'export * from './hint.js'@@ -35,6 +36,7 @@ export * from './old-files.js'export * from './pane.js'export * from './pane-view'export * from './parse-file-diff'+export * from './poll-word.js'export * from './renamed.js'export * from './repository.js'export * from './repository-of'diff --git a/mods/diff/tests/fixtures/poll-word.ts b/mods/diff/tests/fixtures/poll-word.tsnew file mode 100644index 00000000..5e725c10--- /dev/null+++ b/mods/diff/tests/fixtures/poll-word.ts@@ -0,0 +1,7 @@+/**+ * The open pane's HEAD poll as gitWordOf names it where no file answers.+ *+ * On disk the poll stats `.git/HEAD` and spawns nothing, so a test that+ * lists the session's spawns as the built-in's lets this word by.+ */+export const POLL_WORD = 'rev-parse HEAD'diff --git a/mods/diff/tests/git.test.ts b/mods/diff/tests/git.test.tsindex 78582f46..ff9f3c44 100644--- a/mods/diff/tests/git.test.ts+++ b/mods/diff/tests/git.test.ts@@ -20,7 +20,12 @@ describe('git', () => {const diffs = pinned.filter(run => run.argv.includes('diff'))expect(discovery?.argv).toContain('--show-toplevel')- expect(discovery?.init?.cwd).toBeUndefined()++ expect(+ discovery?.init?.cwd,+ "found where the session started, wherever Claude's shell has gone",+ ).toBe('/main/wt')+expect(diffs.length).toBeGreaterThanOrEqual(3)for (const run of world.runs) {@@ -38,6 +43,34 @@ describe('git', () => {expect(world.runs.some(run => run.argv.includes('config'))).toBe(false)})+ test('the working tree is walked once, by the first fetch', async ($, on) => {+ const world = Fixtures.inRepository(on)++ const walks = () =>+ world.runs.filter(run => Fixtures.gitWordOf(run.argv) === 'status')++ const fetches = () =>+ world.runs.filter(+ run => Fixtures.gitWordOf(run.argv) === 'diff --numstat',+ )++ on('tool.call', () => ({ result: 'ran' }))++ await $.session.start(Fixtures.SESSION)+ await $.command.run(Fixtures.DIFF)+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(walks(), 'the first fetch walked').toHaveLength(1)+ expect(fetches()).toHaveLength(1)++ await $.tool.call({ tool: 'Bash', command: 'make' })+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(fetches(), 'the command fetched again').toHaveLength(2)+ expect(walks(), 'and read the walk it had').toHaveLength(1)+ expect(walks()[0]?.init?.cwd, 'pinned like every child').toBe('/work')+ })+test('a file moved in since the start is session work', async ($, on) => {const clock = Fixtures.startsSession(on, Fixtures.SETTLE_MS)diff --git a/mods/diff/tests/register.test.ts b/mods/diff/tests/register.test.tsindex 7713a5c5..db708b29 100644--- a/mods/diff/tests/register.test.ts+++ b/mods/diff/tests/register.test.ts@@ -1,4 +1,4 @@-import type { Args } from 'claude-code'+import type { Args, ResultOf } from 'claude-code'import { describe, expect, mock, test, tier } from 'claude-code/testing'import Limits from '../hooks/limits'@@ -8,7 +8,120 @@ import Fixtures from './fixtures'tier('builtin')describe('register', () => {- test('/diff at boot joins the boot probe, then asks again', async ($, on) => {+ test('the start asks nothing of git and registers /diff', async ($, on) => {+ const world = Fixtures.inRepository(on)++ await $.session.start(Fixtures.SESSION)++ expect(world.runs, "no git, as the built-in's start runs none").toEqual([])++ expect(await $.command.run(Fixtures.DIFF), '/diff was registered').toEqual({+ text: 'Diff panel shown',+ })+ })++ test("git runs at the built-in's moments and no others", async ($, on) => {+ const world = Fixtures.inRepository(on)++ let read = 0++ function spawnedSince(): string[] {+ const words = world.runs+ .slice(read)+ .map(run => Fixtures.gitWordOf(run.argv))+ .filter(word => word !== Fixtures.POLL_WORD)++ read = world.runs.length++ return words+ }++ const edit = () =>+ $.tool.call({+ tool: 'Edit',+ file_path: '/work/app.ts',+ old_string: '1',+ new_string: '2',+ })++ on('tool.call', () => ({ result: 'done' }))+ on('turn.complete', ($, e) => ({ text: e.answer }))+ on('command.run', { command: 'clear' }, () => ({}))++ await $.session.start(Fixtures.SESSION)+ await $.ui.render(Fixtures.hintAt(Limits.AUTO_OPEN_MIN_COLUMNS - 1))+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), 'the start and the footer: nothing').toEqual([])++ await edit()+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(+ spawnedSince(),+ 'an edit with no room for a pane: nothing, the width is read first',+ ).toEqual([])++ await $.command.run(Fixtures.DIFF)+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), '/diff: found, then one fetch for the pane').toEqual(+ [+ 'rev-parse --show-toplevel',+ 'status',+ 'diff --shortstat',+ 'diff --numstat',+ 'ls-files',+ 'diff -- app.ts',+ ],+ )++ await edit()+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), 'an edit, the pane open: one fetch').toEqual([+ 'diff --shortstat',+ 'diff --numstat',+ 'ls-files',+ 'diff -- app.ts',+ ])++ await $.tool.call({ tool: 'Bash', command: 'make' })+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), 'a shell command, the pane open: one fetch').toEqual(+ ['diff --shortstat', 'diff --numstat', 'ls-files', 'diff -- app.ts'],+ )++ await $.turn.complete({+ answer: 'done',+ durationMs: 1,+ isAborted: false,+ turnId: 't1',+ reason: 'answer',+ })++ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), "a turn's end: nothing").toEqual([])++ await $.command.run(Fixtures.DIFF)+ await edit()+ await $.tool.call({ tool: 'Bash', command: 'make' })+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince(), 'the pane closed by hand: nothing').toEqual([])++ await $.command.run(Fixtures.CLEAR)+ await $.command.run(Fixtures.DIFF)+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(spawnedSince()[0], '/clear forgot the repository').toBe(+ 'rev-parse --show-toplevel',+ )+ })++ test('/diff whose probe never answers probes once more', async ($, on) => {const probes: (readonly string[])[] = []const clock = Fixtures.startsSession(on)@@ -24,24 +137,40 @@ describe('register', () => {return { value: Fixtures.NOT_A_REPOSITORY }})- const booting = $.session.start(Fixtures.SESSION)-- await clock.settle()+ await $.session.start(Fixtures.SESSION)const ran = $.command.run(Fixtures.DIFF)await clock.settle()- expect(probes, 'the boot probe, which /diff joined').toHaveLength(1)+ expect(probes, "this /diff's probe, unanswered yet").toHaveLength(1)await clock.advance(Limits.GIT_TIMEOUT_MS)- await bootingexpect(await ran).toEqual({text: expect.stringContaining("isn't in a git repository"),})- expect(probes, 'then one more of its own').toHaveLength(2)+ expect(probes, 'then one more, which answered').toHaveLength(2)+ })++ test('two /diff typed together probe the repository once', async ($, on) => {+ const world = Fixtures.inRepository(on)++ await $.session.start(Fixtures.SESSION)++ const [first, second] = await Promise.all([+ $.command.run(Fixtures.DIFF),+ $.command.run(Fixtures.DIFF),+ ])++ const probes = world.runs.filter(run =>+ run.argv.includes('--show-toplevel'),+ )++ expect(first.text).toMatch(/^Diff panel (shown|hidden)$/)+ expect(second.text).toMatch(/^Diff panel (shown|hidden)$/)+ expect(probes, 'the second joined the probe in flight').toHaveLength(1)})test('outside a repository /diff says so, opens nothing', async ($, on) => {@@ -77,11 +206,19 @@ describe('register', () => {test('when the built-in holds /diff, the mod stands down', async ($, on) => {const logged: string[] = []+ const runs: Args<'process.run'>[] = []mock.clock(on)on('session.start', ($, e) => ({ cwd: e.cwd }))on('command.register', () => ({ deny: Fixtures.BUILTIN_HOLDS }))on('command.run', () => ({ text: 'the built-in /diff ran' }))+ on('tool.call', () => ({ result: 'edited' }))++ on('process.run', ($, e) => {+ runs.push(e)++ return { value: Fixtures.gitIn(e.argv) }+ })on('ui.log', ($, e) => {logged.push(e.text)@@ -95,7 +232,15 @@ describe('register', () => {text: 'the built-in /diff ran',})+ await $.tool.call({+ tool: 'Edit',+ file_path: '/work/app.ts',+ old_string: '1',+ new_string: '2',+ })+expect(logged).toEqual([])+ expect(runs, 'idle: no git for /diff or the edit').toEqual([])})test('a refusal the built-in did not cause is said aloud', async ($, on) => {@@ -127,10 +272,16 @@ describe('register', () => {await $.session.start(Fixtures.SESSION)+ expect(world.runs, 'the start ran nothing').toEqual([])+expect(await $.command.run(Fixtures.DIFF)).toEqual({text: 'Diff panel shown',})+ expect(world.runs[0]?.argv, '/diff found the repository first').toContain(+ '--show-toplevel',+ )+expect(world.opened).toEqual([{ id: 'diff', title: 'Diff', holdToasts: true },])@@ -197,6 +348,42 @@ describe('register', () => {expect(world.opened.map(pane => pane.id)).toEqual(['diff'])})+ test('an edit that failed or was refused opens nothing', async ($, on) => {+ const world = Fixtures.inRepository(on)++ const answers: ResultOf['tool.call'][] = [+ { isError: true, result: 'no such text' },+ { deny: 'not allowed' },+ ]++ const edit = () =>+ $.tool.call({+ tool: 'Edit',+ file_path: '/work/app.ts',+ old_string: '1',+ new_string: '2',+ })++ on('tool.call', () => answers.shift() ?? { result: 'edited' })++ await $.session.start(Fixtures.SESSION)+ await $.ui.render(Fixtures.HINT)+ await edit()+ await edit()+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(world.opened, 'neither edit landed').toEqual([])+ expect(world.runs, 'so nothing asked after the repository').toEqual([])++ await edit()+ await world.clock.advance(Fixtures.SETTLE_MS)++ expect(+ world.opened.map(pane => pane.id),+ 'the third did',+ ).toEqual(['diff'])+ })+test('/clear closes the pane it finds open', async ($, on) => {const world = Fixtures.inRepository(on)@@ -290,19 +477,29 @@ describe('register', () => {).toContain('uncommitted (vs HEAD)')})- test('a repository made later is pinned once, on /diff', async ($, on) => {+ test('no repository is an answer kept until /clear', async ($, on) => {const { 'rev-parse --path-format=absolute': worktree = '', ...notYet } =Fixtures.oneSecret()const script: Record<string, string> = notYetconst world = Fixtures.inRepository(on, script)+ const probesOf = () =>+ world.runs.filter(run => run.argv.includes('--show-toplevel')).length++ on('command.run', { command: 'clear' }, () => ({}))+await $.session.start(Fixtures.WORKTREE_SESSION)const before = await $.command.run(Fixtures.DIFF)script['rev-parse --path-format=absolute'] = worktree+ const again = await $.command.run(Fixtures.DIFF)+ const probesKept = probesOf()++ await $.command.run(Fixtures.CLEAR)+const after = await $.command.run(Fixtures.DIFF)await world.clock.advance(Fixtures.SETTLE_MS)@@ -315,14 +512,16 @@ describe('register', () => {await world.clock.advance(Fixtures.SETTLE_MS)await third- const probes = world.runs.filter(run =>- run.argv.includes('--show-toplevel'),+ expect(before.text).toContain("isn't in a git repository")++ expect(again.text, "kept, as the built-in's answer is").toContain(+ "isn't in a git repository",)- expect(before.text).toContain("isn't in a git repository")- expect(after.text).toBe('Diff panel shown')+ expect(probesKept, 'one probe answered both').toBe(1)+ expect(after.text, '/clear forgot it').toBe('Diff panel shown')expect(world.opened[0]?.id).toBe('diff')- expect(probes).toHaveLength(3)+ expect(probesOf(), 'then one more, pinned from there on').toBe(2)expect(world.runs.some(run => run.argv.includes('--git-dir=/else/.git')),@@ -380,7 +579,7 @@ describe('register', () => {const probes = runs.filter(run => run.argv.includes('--show-toplevel'))expect(text).toContain("isn't in a git repository")- expect(probes, "the boot's, then this /diff's; no retry").toHaveLength(2)+ expect(probes, "this /diff's alone; no retry").toHaveLength(1)})test('/diff on a narrow terminal: the resize line', async ($, on) => {