Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add unified diff to switch picker (#3865)
Maximilian Roos5a870224d1d3
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.mdindex 71c556987..cf25466f6 100644--- a/benches/CLAUDE.md+++ b/benches/CLAUDE.md@@ -116,8 +116,10 @@ Setting `WORKTRUNK_PREVIEW_BENCH=1` runs `wt switch`'s interactive picker preludend-to-end — collect, speculative spawn, skeleton, initial pre-compute, deferredpre-compute — and exits immediately after `PreviewOrchestrator::wait_for_idle()`,before skim launches and before any JSON serialization or stderr drain. Used by-`picker_preview` benchmarks to measure the preview pool workload without standing-up a PTY. Bypasses the picker's TTY check, like `WORKTRUNK_PICKER_DRY_RUN=1`.+`picker_preview` benchmarks to measure the skeleton-time preview pool workload+without standing up a PTY. Off-screen worktrees are demand-loaded only after skim+starts and are intentionally outside this benchmark. Bypasses the picker's TTY+check, like `WORKTRUNK_PICKER_DRY_RUN=1`.The hot path inside the env-gated block is identical to the dry-run path; only thepost-drain output (cache JSON dump + stashed-warning drain) is conditional. Keep newdiff --git a/benches/picker_preview.rs b/benches/picker_preview.rsindex d8d361b6a..353bc8351 100644--- a/benches/picker_preview.rs+++ b/benches/picker_preview.rs@@ -8,13 +8,14 @@//// What this measures// -------------------// `wt switch` (interactive picker) submits one preview-compute task per row-// (worktree/branch) into the global rayon pool. Each task gathers the data-// that fills the picker's preview pane — diff stats, log lines, ahead/behind-// — and stores it in the in-memory preview cache. The user-visible quantity-// to optimize is "time from picker launch to all previews ready": that's-// the responsiveness window where j/k navigation should land on warm-// content.+// `wt switch` (interactive picker) submits every local preview for the landing+// row and the cheap, cacheable default preview for each branch-only row into+// its rayon pool. Off-screen worktrees are demand-loaded when selected so their+// untracked-inclusive diff cannot delay row collection. The user-visible+// quantity to optimize here is the skeleton-time preview workload before skim+// launches. The demand path this defers work onto is not measured anywhere:+// `preview_miss_is_served_by_demand_worker` asserts that path is+// correct, not that it is fast, and no bench covers selected-row latency.//// We measure that wall clock headlessly by spawning `wt` with// `WORKTRUNK_PREVIEW_BENCH=1`, which runs the full picker prelude (collect,@@ -24,7 +25,7 @@// (option 2 from the task: "spawn → first interactive-ready point") would// require a TTY harness; the documented nextest/SIGTTOU pain on// `shell-integration-tests` (see project `CLAUDE.md`) makes that a follow-up-// rather than a prerequisite. The headless path captures the full pool+// rather than a prerequisite. The headless path captures the initial pool// workload, which is the variable the optimization work in #2662 / #2683 /// #2685 / #2704 actually pushes on.//diff --git a/docs/content/config.md b/docs/content/config.mdindex 2946339e1..bc89bd56f 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -1025,7 +1025,7 @@ View or drop worktrunk's regenerable caches in one place. Everything here is reb- **CI status** — GitHub/GitLab CI per branch (30–60s TTL), shown in [`wt list`](@/list.md#ci-status), plus the largest PR/MR number seen (sizes the CI column)- **Summaries** — LLM-generated branch summaries (`wt list --full`, `wt switch` preview)-- **Git commands** — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Git commands** — cached merge-tree, ancestry, diff-stat, and `wt switch` preview results- **Hints** — one-time hints already shown in this repo- **Previous branch** — the `wt switch -` target, re-recorded on the next switchdiff --git a/docs/content/faq.md b/docs/content/faq.mdindex ab03c2f4e..db62be087 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -145,7 +145,7 @@ Fish and Nushell wrappers live at a path named after the command, so install wri### 4. Metadata in `.git/` (automatic)-Worktrunk stores small amounts of cache and log data in the repository's `.git/` directory:+Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|@@ -162,11 +162,15 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`None of this is tracked by git or pushed to remotes.-**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.+**To remove:** `wt config state clear` removes all repository data: config keys, caches, markers, hints, variables, logs, and stale trash.++### 5. Temporary files (automatic)++Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.### What Worktrunk does NOT create-- No files outside `.git/`, config directories, or worktree directories+- No files outside `.git/`, config directories, worktree directories, or the system temporary directory- No global git hooks- No modifications to `~/.gitconfig`- No long-running background processes or daemons@@ -277,7 +281,9 @@ To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% e## Installation fails with C compilation errors-Errors related to tree-sitter or C compilation (C99 mode, `le16toh` undefined) can be avoided by installing without syntax highlighting:+Worktrunk requires Git 2.34 or newer.++Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:{{ terminal(cmd="cargo install worktrunk --no-default-features --features cli") }}diff --git a/docs/content/switch.md b/docs/content/switch.mdindex b95ac0f03..32f1d9d2d 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -84,8 +84,8 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Alt-o` | Open the selected row's PR/MR URL in the browser || `Alt-r` | Refresh the list (pick up worktrees created elsewhere) || `Esc` | Cancel |-| `Alt-1`–`Alt-7` | Jump to a preview tab |-| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |+| `Alt-1`–`Alt-8` | Jump to a preview tab |+| `Tab`/`Shift-Tab` | Cycle available preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -99,13 +99,16 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `**Preview tabs:**-1. **HEAD±** — Diff of uncommitted changes-2. **log** — Recent commits; commits already on the default branch have dimmed hashes-3. **main…±** — Diff of changes since the merge-base with the default branch-4. **remote⇅** — Ahead/behind diff vs upstream tracking branch-5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)-6. **pr** — The selected row's PR/MR, for any row whose branch has one-7. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one+1. **diff** — One net diff from the comparison base through the current worktree: committed, staged, unstaged, and untracked changes+2. **working** — Staged, unstaged, and untracked changes against `HEAD`+3. **committed** — Committed changes since the comparison base+4. **log** — Recent commits; commits already on the default branch have dimmed hashes+5. **remote⇅** — Ahead/behind diff vs upstream tracking branch+6. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)+7. **pr** — The selected row's PR/MR, for any row whose branch has one+8. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one++The comparison base is the merge-base with the default branch, or with its upstream when the local default branch lags. The picker opens on **diff** for local rows and **pr** for a PR/MR listed by `--prs` but not available locally. `Tab` and `Shift-Tab` skip tabs without content; `Alt-1` through `Alt-8` open any tab directly. After you choose a tab, that choice stays active while you navigate.On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex b2f585769..2ddb87553 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -1064,7 +1064,7 @@ View or drop worktrunk's regenerable caches in one place. Everything here is reb- **CI status** — GitHub/GitLab CI per branch (30–60s TTL), shown in [`wt list`](https://worktrunk.dev/list/#ci-status), plus the largest PR/MR number seen (sizes the CI column)- **Summaries** — LLM-generated branch summaries (`wt list --full`, `wt switch` preview)-- **Git commands** — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Git commands** — cached merge-tree, ancestry, diff-stat, and `wt switch` preview results- **Hints** — one-time hints already shown in this repo- **Previous branch** — the `wt switch -` target, re-recorded on the next switchdiff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex 89b331e8f..b8b9dd357 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -138,7 +138,7 @@ Fish and Nushell wrappers live at a path named after the command, so install wri### 4. Metadata in `.git/` (automatic)-Worktrunk stores small amounts of cache and log data in the repository's `.git/` directory:+Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|@@ -155,11 +155,15 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`None of this is tracked by git or pushed to remotes.-**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.+**To remove:** `wt config state clear` removes all repository data: config keys, caches, markers, hints, variables, logs, and stale trash.++### 5. Temporary files (automatic)++Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.### What Worktrunk does NOT create-- No files outside `.git/`, config directories, or worktree directories+- No files outside `.git/`, config directories, worktree directories, or the system temporary directory- No global git hooks- No modifications to `~/.gitconfig`- No long-running background processes or daemons@@ -270,7 +274,9 @@ To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% e## Installation fails with C compilation errors-Errors related to tree-sitter or C compilation (C99 mode, `le16toh` undefined) can be avoided by installing without syntax highlighting:+Worktrunk requires Git 2.34 or newer.++Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:```bashcargo install worktrunk --no-default-features --features clidiff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.mdindex 235b26c4d..97e59a156 100644--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md@@ -80,8 +80,8 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Alt-o` | Open the selected row's PR/MR URL in the browser || `Alt-r` | Refresh the list (pick up worktrees created elsewhere) || `Esc` | Cancel |-| `Alt-1`–`Alt-7` | Jump to a preview tab |-| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |+| `Alt-1`–`Alt-8` | Jump to a preview tab |+| `Tab`/`Shift-Tab` | Cycle available preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -95,13 +95,16 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `**Preview tabs:**-1. **HEAD±** — Diff of uncommitted changes-2. **log** — Recent commits; commits already on the default branch have dimmed hashes-3. **main…±** — Diff of changes since the merge-base with the default branch-4. **remote⇅** — Ahead/behind diff vs upstream tracking branch-5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)-6. **pr** — The selected row's PR/MR, for any row whose branch has one-7. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one+1. **diff** — One net diff from the comparison base through the current worktree: committed, staged, unstaged, and untracked changes+2. **working** — Staged, unstaged, and untracked changes against `HEAD`+3. **committed** — Committed changes since the comparison base+4. **log** — Recent commits; commits already on the default branch have dimmed hashes+5. **remote⇅** — Ahead/behind diff vs upstream tracking branch+6. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)+7. **pr** — The selected row's PR/MR, for any row whose branch has one+8. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one++The comparison base is the merge-base with the default branch, or with its upstream when the local default branch lags. The picker opens on **diff** for local rows and **pr** for a PR/MR listed by `--prs` but not available locally. `Tab` and `Shift-Tab` skip tabs without content; `Alt-1` through `Alt-8` open any tab directly. After you choose a tab, that choice stays active while you navigate.On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex b2f585769..2ddb87553 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -1064,7 +1064,7 @@ View or drop worktrunk's regenerable caches in one place. Everything here is reb- **CI status** — GitHub/GitLab CI per branch (30–60s TTL), shown in [`wt list`](https://worktrunk.dev/list/#ci-status), plus the largest PR/MR number seen (sizes the CI column)- **Summaries** — LLM-generated branch summaries (`wt list --full`, `wt switch` preview)-- **Git commands** — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Git commands** — cached merge-tree, ancestry, diff-stat, and `wt switch` preview results- **Hints** — one-time hints already shown in this repo- **Previous branch** — the `wt switch -` target, re-recorded on the next switchdiff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 89b331e8f..b8b9dd357 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -138,7 +138,7 @@ Fish and Nushell wrappers live at a path named after the command, so install wri### 4. Metadata in `.git/` (automatic)-Worktrunk stores small amounts of cache and log data in the repository's `.git/` directory:+Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|@@ -155,11 +155,15 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`None of this is tracked by git or pushed to remotes.-**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.+**To remove:** `wt config state clear` removes all repository data: config keys, caches, markers, hints, variables, logs, and stale trash.++### 5. Temporary files (automatic)++Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.### What Worktrunk does NOT create-- No files outside `.git/`, config directories, or worktree directories+- No files outside `.git/`, config directories, worktree directories, or the system temporary directory- No global git hooks- No modifications to `~/.gitconfig`- No long-running background processes or daemons@@ -270,7 +274,9 @@ To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% e## Installation fails with C compilation errors-Errors related to tree-sitter or C compilation (C99 mode, `le16toh` undefined) can be avoided by installing without syntax highlighting:+Worktrunk requires Git 2.34 or newer.++Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:```bashcargo install worktrunk --no-default-features --features clidiff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.mdindex 235b26c4d..97e59a156 100644--- a/skills/worktrunk/reference/switch.md+++ b/skills/worktrunk/reference/switch.md@@ -80,8 +80,8 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Alt-o` | Open the selected row's PR/MR URL in the browser || `Alt-r` | Refresh the list (pick up worktrees created elsewhere) || `Esc` | Cancel |-| `Alt-1`–`Alt-7` | Jump to a preview tab |-| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |+| `Alt-1`–`Alt-8` | Jump to a preview tab |+| `Tab`/`Shift-Tab` | Cycle available preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -95,13 +95,16 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `**Preview tabs:**-1. **HEAD±** — Diff of uncommitted changes-2. **log** — Recent commits; commits already on the default branch have dimmed hashes-3. **main…±** — Diff of changes since the merge-base with the default branch-4. **remote⇅** — Ahead/behind diff vs upstream tracking branch-5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)-6. **pr** — The selected row's PR/MR, for any row whose branch has one-7. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one+1. **diff** — One net diff from the comparison base through the current worktree: committed, staged, unstaged, and untracked changes+2. **working** — Staged, unstaged, and untracked changes against `HEAD`+3. **committed** — Committed changes since the comparison base+4. **log** — Recent commits; commits already on the default branch have dimmed hashes+5. **remote⇅** — Ahead/behind diff vs upstream tracking branch+6. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)+7. **pr** — The selected row's PR/MR, for any row whose branch has one+8. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one++The comparison base is the merge-base with the default branch, or with its upstream when the local default branch lags. The picker opens on **diff** for local rows and **pr** for a PR/MR listed by `--prs` but not available locally. `Tab` and `Shift-Tab` skip tabs without content; `Alt-1` through `Alt-8` open any tab directly. After you choose a tab, that choice stays active while you navigate.On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.diff --git a/src/cli/config.rs b/src/cli/config.rsindex ee7076676..190535587 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -765,7 +765,7 @@ pub enum StateCommand {- **Vars**: Custom variables per branch- **CI status**: Cached GitHub/GitLab CI status per branch (30-60s TTL), plus the largest PR/MR number seen (sizes the `wt list` CI column)- **Summaries**: Cached LLM-generated branch summaries (shown in `wt list --full` and `wt switch` preview)-- **Git commands cache**: SHA-keyed disk caches — merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Git commands cache**: Cached merge-tree, ancestry, diff-stat, and `wt switch` preview results- **Hints**: One-time hints that have been shown- **Log files**: Operation and debug logs- **Trash**: Staged worktree directories awaiting background deletion@@ -808,7 +808,7 @@ untouched."#)]- **CI status** — GitHub/GitLab CI per branch (30–60s TTL), shown in [`wt list`](@/list.md#ci-status), plus the largest PR/MR number seen (sizes the CI column)- **Summaries** — LLM-generated branch summaries (`wt list --full`, `wt switch` preview)-- **Git commands** — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Git commands** — cached merge-tree, ancestry, diff-stat, and `wt switch` preview results- **Hints** — one-time hints already shown in this repo- **Previous branch** — the `wt switch -` target, re-recorded on the next switchdiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 587cbae6f..6c6b519d7 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -689,8 +689,8 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Alt-o` | Open the selected row's PR/MR URL in the browser || `Alt-r` | Refresh the list (pick up worktrees created elsewhere) || `Esc` | Cancel |-| `Alt-1`–`Alt-7` | Jump to a preview tab |-| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |+| `Alt-1`–`Alt-8` | Jump to a preview tab |+| `Tab`/`Shift-Tab` | Cycle available preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -704,13 +704,16 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `**Preview tabs:**-1. **HEAD±** — Diff of uncommitted changes-2. **log** — Recent commits; commits already on the default branch have dimmed hashes-3. **main…±** — Diff of changes since the merge-base with the default branch-4. **remote⇅** — Ahead/behind diff vs upstream tracking branch-5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)-6. **pr** — The selected row's PR/MR, for any row whose branch has one-7. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one+1. **diff** — One net diff from the comparison base through the current worktree: committed, staged, unstaged, and untracked changes+2. **working** — Staged, unstaged, and untracked changes against `HEAD`+3. **committed** — Committed changes since the comparison base+4. **log** — Recent commits; commits already on the default branch have dimmed hashes+5. **remote⇅** — Ahead/behind diff vs upstream tracking branch+6. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)+7. **pr** — The selected row's PR/MR, for any row whose branch has one+8. **comments** — The PR/MR's comment thread, fetched from the forge for any row whose branch has one++The comparison base is the merge-base with the default branch, or with its upstream when the local default branch lags. The picker opens on **diff** for local rows and **pr** for a PR/MR listed by `--prs` but not available locally. `Tab` and `Shift-Tab` skip tabs without content; `Alt-1` through `Alt-8` open any tab directly. After you choose a tab, that choice stays active while you navigate.On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 055ed8cdf..04d818d84 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -17,7 +17,7 @@ use ratatui::style::{Color, Modifier};use ratatui::text::{Line, Span};use skim::prelude::*;use worktrunk::git::Repository;-use worktrunk::styling::{HINT_SYMBOL, INFO_SYMBOL, visual_width};+use worktrunk::styling::{HINT_SYMBOL, INFO_SYMBOL, WARNING_SYMBOL, visual_width};use super::super::list::ci_status::{PrRef, PrStatus, ReviewState};use super::super::list::model::ListItem;@@ -340,62 +340,18 @@ impl SkimItem for HeaderSkimItem {}}-/// Render a `git diff` preview body (stat header, then the colored diff):-/// `Some` when the diff is non-empty, `None` when it's empty (or the stat-/// command failed). Callers render their own empty-state headline — the-/// headline names the row's branch, which must stay out of the SHA-keyed-/// disk cache (see [`preview_cache::BranchDiffCacheEntry`]), so this helper-/// only ever produces the name-free body.-///-/// `prefix` is the command through the `diff` subcommand (e.g. `["diff"]` or-/// `["-C", path, "diff"]`); `revs` are the positional revisions. Both commands-/// use `--no-optional-locks` to avoid index lock contention, as `wt list`'s-/// `git status` does: a preview runs on a background thread against a worktree-/// the user may be working in, and can be signalled mid-run by-/// [`worktrunk::shell_exec::cancel_background_commands`].-///-/// The diff options precede an `--end-of-options` sentinel, which fences the-/// positional `revs` so a ref that looks like a flag (a branch literally named-/// `-x` or `--foo`) can't be misparsed as an option. Today's callers pass-/// resolved SHAs and `HEAD`, but the fence keeps the helper safe for any future-/// caller that passes a raw name.-fn compute_diff_preview(- repo: &Repository,- prefix: &[&str],- revs: &[&str],- width: usize,-) -> Option<String> {- let stat_width_arg = format!("--stat-width={width}");-- // Check stat output first.- let mut stat_args = vec!["--no-optional-locks"];- stat_args.extend_from_slice(prefix);- stat_args.extend([- "--stat",- "--color=always",- stat_width_arg.as_str(),- "--end-of-options",- ]);- stat_args.extend_from_slice(revs);-- let stat = repo.run_command(&stat_args).ok()?;- if stat.trim().is_empty() {- return None;- }-- let mut output = stat;-- // Build diff args with color.- let mut diff_args = vec!["--no-optional-locks"];- diff_args.extend_from_slice(prefix);- diff_args.extend(["--color=always", "--end-of-options"]);- diff_args.extend_from_slice(revs);-- if let Ok(diff) = repo.run_command(&diff_args) {- output.push_str(&diff);- }-- Some(output)+/// What the shared porcelain snapshot says about the worktree diff path.+/// Only an untracked file requires the temporary-index path; tracked-only+/// changes can use ordinary `git diff` without copying or updating an index.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WorktreeDiffState {+ Clean,+ TrackedOnly,+ HasUntracked,+ /// Status is an optimization hint, not the authority for rendering. If it+ /// fails, use the inclusive path and let the actual diff report success or+ /// failure rather than incorrectly declaring the tree clean.+ Unknown,}/// Wrapper to implement SkimItem for ListItem.@@ -470,29 +426,24 @@ pub(super) struct PickerRow {pub output_token: String,/// Shared cache for pre-computed previews (all modes)pub preview_cache: PreviewCache,- /// PR/MR status for the `pr`/`comments` tabs and the folded matcher tokens.- /// LIVE for a worktree row — primed from the CI cache and overwritten as the- /// `CiStatus` task streams in (so the `pr` tab reflects the live fetch);- /// PRE-FILLED and STATIC for a `--prs` row (from `PrEntry::display_status`,- /// never mutated within a row's life; a rebuild re-renders the `(pr:N, Pr)`- /// memo — see `prs::listed_pr_row`).+ /// PR/MR status for the `pr`/`comments` tabs and matcher tokens. Live for a+ /// local row, pre-filled and static for a listed `--prs` row.pub pr_status: PrStatusSlot,/// Surfaces a background preview fill without a keystroke. `preview()`/// records the row's awaited `(preview_key, mode)` here on every render; the/// orchestrator pokes a repaint when that key's compute lands (see/// [`PreviewNotifier`]).pub notifier: Arc<PreviewNotifier>,- /// Local-checkout data — `Some` for a worktree row, `None` for a listed- /// `--prs` row (whose head branch isn't checked out, so it has no working- /// tree, diffs, or local `ListItem`). Its presence is the single axis the- /// preview/output paths branch on.+ /// Local-branch data — `Some` for a local worktree or branch-only row,+ /// `None` for a listed `--prs` row (whose head isn't available as a local+ /// `ListItem`). Its presence is the single axis the preview/output paths+ /// branch on.pub local: Option<LocalCheckout>,}-/// The worktree-backed half of a [`PickerRow`]: present only when the row's-/// branch is checked out locally. A listed `--prs` row carries `None` and-/// renders its local-checkout tabs (working-tree, branch-diff, upstream,-/// summary) as placeholders.+/// The local-git-backed half of a [`PickerRow`]: present for local worktree and+/// branch-only rows. A listed `--prs` row carries `None` and renders its local+/// diff/summary tabs as placeholders.pub(super) struct LocalCheckout {/// The row's snapshot `ListItem`, for the demand worker: a `preview()`/// cache miss on a local-git tab sends this item to [`PreviewDemand`] so@@ -509,21 +460,15 @@ pub(super) struct LocalCheckout {/// re-seed the just-cleared cache from its frozen `item` (see the/// orchestrator's *Spawn generations* docs).pub spawn_gen: SpawnGeneration,- /// Whether this branch has an upstream tracking ref, for the tab-4- /// (remote⇅) empty state. A SYNCHRONOUS skeleton-time fact read from- /// `Repository::local_branches()` at construction — never from the async- /// `item.upstream`, which is `None` until the row pipeline lands and would- /// lock the tab bar into a stale state (see `TabAvailability`).+ /// Whether this branch has an upstream tracking ref. Read synchronously+ /// from `Repository::local_branches()` at construction, never from the+ /// async `item.upstream`: that field is `None` until the row pipeline lands+ /// and would otherwise lock the tab bar into a stale state.pub has_upstream: bool,- /// Whether `[commit.generation]` summaries are configured, for the tab-5- /// (summary) empty state. A process-wide static fact (`llm_command.is_some()`).+ /// Whether `[commit.generation]` summaries are configured.pub summaries_enabled: bool,- /// Live diff-content signals for the `working_tree` / `branch_diff` /- /// `upstream` tabs, shared with the collect handler. The frozen `item`- /// snapshot can't carry these (its `counts` / `upstream` /- /// `working_tree_status` are `None` at skeleton and never update), so the- /// handler mirrors them here as the pipeline lands — letting those tabs dim- /// once their diff is known empty (see [`LocalContent`]).+ /// Live diff-content signals shared with the collect handler. The frozen+ /// `item` snapshot cannot carry updates that land after the skeleton.pub local_content: LocalContentSlot,/// Set when an `alt-x` removal kept this row's branch and morphed the row to/// `/ branch` in place: [`PickerRow::output`] then yields the bare branch@@ -598,7 +543,16 @@ impl SkimItem for PickerRow {// (it's per-process picker state); everything else is derived in// `render_preview`, which takes the mode explicitly so it's testable// without touching that global state.- let mode = PreviewStateData::read_mode();+ let default_mode = if self.local.is_some() {+ PreviewMode::UnifiedDiff+ } else {+ PreviewMode::Pr+ };+ let mut mode = PreviewStateData::read_mode_for(default_mode);+ if let Some(forward) = PreviewStateData::take_cycle_request() {+ mode = self.tab_availability().cycle_from(mode, forward);+ PreviewStateData::select_mode(mode);+ }// Record what this (selected) row is showing *before* reading the cache,// so a background fill that lands right after a miss still finds the key// set and pokes a repaint (see `PreviewNotifier`). Keyed by `preview_key`@@ -674,6 +628,16 @@ pub(super) fn pr_presence(pr_status: &Option<Option<PrStatus>>) -> PrPresence {}}+/// Whether the PR-backed tabs have content for the current live status. They+/// stay available while loading and dim together once the fetch reports no PR.+fn pr_tab_available(pr_status: &PrStatusSlot) -> bool {+ match &*pr_status.lock().unwrap() {+ None => true,+ Some(None) => false,+ Some(Some(status)) => status.number.is_some(),+ }+}+/// Whether two live `pr_status` slot values render the *same* `pr` pane. Equal/// under the `PrStatus` derive means identical; the pane ignores two fields —/// `is_priming` (a list-cell dim hint [`render_pr_pane_body`] never reads) and@@ -701,24 +665,30 @@ pub(super) fn pr_status_pane_eq(}/// Live, content-aware availability for the local-checkout tabs whose pane is a-/// diff — `working_tree`, `branch_diff`, and `upstream`. Each tab dims once its+/// diff — `unified_diff`, `working_tree`, `branch_diff`, and `upstream`. Each tab dims once its/// diff is *known* empty, the same way the `pr` tab dims once the fetch reports-/// no PR (see [`PickerRow::pr_tab_available`]).+/// no PR (see [`pr_tab_available`]).////// The diff emptiness is async (the `counts` / `upstream` / `working_tree_status`/// fields are `None` at skeleton and land via the list pipeline), so each signal/// is `Option<bool>`: `None` while loading, `Some(has_content)` once known. A tab/// stays available while its signal is `None` — we don't dim before we know it's-/// empty — and dims when the signal resolves to "no content". Each predicate-/// mirrors exactly what its pane renders, so a dimmed number never contradicts a-/// non-empty pane.+/// empty — and dims when the signal resolves to "no content". Working,+/// committed, remote, and summary signals mirror their panes. The complete+/// diff uses the conservative union of working + committed signals: opposing+/// changes can cancel in its net diff, but we never dim a potentially non-empty+/// pane before computing it.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub(super) struct LocalContent {- /// `working_tree`: tracked uncommitted changes exist. Matches the pane's- /// `git diff HEAD` — staged/modified/renamed/deleted, NOT untracked (which- /// `git diff HEAD` doesn't show). `Some(false)` for a branch-only row (no- /// working tree to diff).+ /// `working_tree`: staged, unstaged, or untracked changes exist. Matches the+ /// pane's temporary-index `git diff HEAD`. `Some(false)` for a branch-only+ /// row (no working tree to diff).working_tree: Option<bool>,+ /// Tracked working-tree changes exist. The Summary pane's existing+ /// combined-diff source uses ordinary `git diff HEAD`, which intentionally+ /// excludes untracked files, so its availability must not reuse the+ /// untracked-inclusive `working_tree` signal above.+ summary_working_tree: Option<bool>,/// `branch_diff`: the branch has commits ahead of the mainline tip/// (`counts.ahead > 0`), or it is an orphan (no merge base — see/// [`Self::from_item`]). `counts` is `AheadBehindTask`'s answer, measured@@ -740,17 +710,21 @@ impl LocalContent {/// Read the content signals off a row's `ListItem`. Called from the collect/// handler each time a row updates, then stored in the row's live slot.pub(super) fn from_item(item: &ListItem) -> Self {- let working_tree = match item.worktree_data() {- // A real worktree: tracked changes per the porcelain status (matches- // the pane's `git diff HEAD`, which excludes untracked files).- Some(data) => data- .working_tree_status- .map(|s| s.staged || s.modified || s.renamed || s.deleted),+ let (working_tree, summary_working_tree) = match item.worktree_data() {+ // A real worktree: every change the temporary-index pane includes,+ // plus the tracked-only subset the Summary pane consumes.+ Some(data) => (+ data.working_tree_status+ .map(|s| s.staged || s.modified || s.renamed || s.deleted || s.untracked),+ data.working_tree_status+ .map(|s| s.staged || s.modified || s.renamed || s.deleted),+ ),// Branch-only row: no working tree, so nothing to diff.- None => Some(false),+ None => (Some(false), Some(false)),};Self {working_tree,+ summary_working_tree,// Commits ahead of the upstream-aware comparison base (see the// `branch_diff` field doc). An orphan has no merge base with the// default, so its three-dot diff is ill-defined — keep the tab@@ -774,6 +748,7 @@ impl LocalContent {/// the difference reads as a data fact rather than a row-type policy.#[derive(Debug, Clone, Copy, Default)]struct LocalTabs {+ unified_diff: bool,working_tree: bool,branch_diff: bool,upstream: bool,@@ -781,24 +756,28 @@ struct LocalTabs {}impl LocalTabs {- /// A worktree-backed row. The diff tabs (`working_tree`, `branch_diff`,+ /// A local row. The subsidiary diff tabs (`working_tree`, `branch_diff`,/// `upstream`) follow the live [`LocalContent`] signals — available while- /// loading, dim once their diff is known empty; `upstream` also requires the+ /// loading, dim once their diff is known empty; `unified_diff` dims only+ /// when both component signals are empty because their net changes can+ /// cancel. `upstream` also requires the/// synchronous `has_upstream` floor (no tracking ref → dim with no loading/// window). `summary` requires the process-wide `[commit.generation]` flag/// *and* something to summarize: its pane is generated from the combined diff/// (`crate::summary::compute_combined_diff` = commits ahead of the comparison- /// base + working-tree changes), so it reuses the `branch_diff` and- /// `working_tree` signals that gate tabs 3 and 1 — dimming in concert with- /// them once both are known empty, not only when summaries are disabled.+ /// base + tracked working-tree changes), so it uses `branch_diff` and the+ /// tracked-only `summary_working_tree` signal — dimming in concert with its+ /// actual input rather than the untracked-inclusive working pane.fn worktree(content: LocalContent, has_upstream: bool, summaries_enabled: bool) -> Self {let working_tree = content.working_tree.unwrap_or(true);+ let summary_working_tree = content.summary_working_tree.unwrap_or(true);let branch_diff = content.branch_diff.unwrap_or(true);Self {+ unified_diff: working_tree || branch_diff,working_tree,branch_diff,upstream: has_upstream && content.upstream_diverged.unwrap_or(true),- summary: summaries_enabled && (working_tree || branch_diff),+ summary: summaries_enabled && (summary_working_tree || branch_diff),}}}@@ -810,22 +789,23 @@ impl LocalTabs {/// `loading_placeholder`). Two genuine axes drive availability, and `--prs`/// touches neither — it only decides whether a PR row is *listed* at all:///-/// - The local-checkout tabs ([`LocalTabs`]): the three diff tabs+/// - The local-checkout tabs ([`LocalTabs`]): the three subsidiary diff tabs/// (`working_tree` / `branch_diff` / `upstream`) follow the row's live-/// [`LocalContent`] — available while their diff is still loading, dim once-/// it's known empty (a clean working tree, no commits ahead, up to date with-/// upstream), the same loading-then-dim shape as the `pr` tab. `upstream` also+/// [`LocalContent`] exactly; `unified_diff` uses their conservative union,+/// since opposing working and committed changes can cancel only after its+/// net diff is computed. Tabs stay available while loading and dim once+/// known empty, the same shape as the `pr` tab. `upstream` also/// carries a synchronous `has_upstream` floor (`Repository::local_branches()`),/// so a branch with no tracking ref dims immediately with no loading window./// `summary` requires the process-wide `[commit.generation]` flag *and* a-/// non-empty combined diff — its pane's content source — so it reuses the-/// `branch_diff` / `working_tree` signals and dims alongside the "no changes-/// to summarize" pane, not only when summaries are disabled. A `--prs` row has-/// no local checkout, so all four are empty.+/// non-empty combined diff — its pane's content source — so it uses the+/// `branch_diff` plus tracked-working signals and dims alongside the "no+/// changes to summarize" pane, not only when summaries are disabled. A `--prs` row has+/// no local checkout, so all five local tabs are empty./// - The PR-backed tabs: `pr` and `comments` are available together, gated by/// `has_pr`. On a worktree row that's the live status slot (primed from the CI/// cache, then refreshed by the `CiStatus` task — see-/// [`PickerRow::pr_tab_available`]): it dims once the fetch reports no+/// [`pr_tab_available`]): it dims once the fetch reports no/// PR, and stays available while loading or with a PR. A `--prs` row always/// has a PR, so both are available.///@@ -836,6 +816,7 @@ impl LocalTabs {/// `--prs` row).#[derive(Debug, Clone, Copy)]pub(super) struct TabAvailability {+ unified_diff: bool,working_tree: bool,log: bool,branch_diff: bool,@@ -853,6 +834,7 @@ impl TabAvailability {/// row and a listed-PR row.fn from_axes(local: LocalTabs, has_pr: bool) -> Self {Self {+ unified_diff: local.unified_diff,working_tree: local.working_tree,log: true,branch_diff: local.branch_diff,@@ -866,7 +848,7 @@ impl TabAvailability {/// A worktree-backed row: the local-checkout tabs follow [`LocalTabs`]/// (diff tabs gated by the live [`LocalContent`] + the `has_upstream` floor);/// the PR-backed tabs follow the live PR status (see- /// [`PickerRow::pr_tab_available`]).+ /// [`pr_tab_available`]).pub(super) fn worktree(content: LocalContent,has_upstream: bool,@@ -887,6 +869,38 @@ impl TabAvailability {pub(super) fn listed_pr() -> Self {Self::from_axes(LocalTabs::default(), true)}++ /// Whether `mode` has content for this row. Empty tabs remain directly+ /// selectable with Alt-N, but sequential cycling skips them.+ fn contains(self, mode: PreviewMode) -> bool {+ match mode {+ PreviewMode::UnifiedDiff => self.unified_diff,+ PreviewMode::WorkingTree => self.working_tree,+ PreviewMode::BranchDiff => self.branch_diff,+ PreviewMode::Log => self.log,+ PreviewMode::UpstreamDiff => self.upstream,+ PreviewMode::Summary => self.summary,+ PreviewMode::Pr => self.pr,+ PreviewMode::Comments => self.comments,+ }+ }++ /// The next available tab in the requested direction. `log` is always+ /// available, so the bounded walk always finds a tab.+ pub(super) fn cycle_from(self, current: PreviewMode, forward: bool) -> PreviewMode {+ let mut candidate = current;+ for _ in 0..8 {+ candidate = if forward {+ candidate.next()+ } else {+ candidate.prev()+ };+ if self.contains(candidate) {+ return candidate;+ }+ }+ current+ }}/// One preview tab's identity: its `alt-N` digit, label, and whether it's the@@ -916,7 +930,7 @@ struct Tab {/// **Width adaptation.** skim renders previews with wrapping off (its default),/// so a tab bar wider than `width` would truncate on the right — and the `pr` //// `comments` tabs, exactly the ones with content on a `--prs` row, sit at that-/// end. When the seven full-form tabs don't fit, the bar falls back to a compact+/// end. When the eight full-form tabs don't fit, the bar falls back to a compact/// form (`1 2: log 3 …`): every accelerator digit stays visible, but only the/// active tab keeps its label. The two style signals survive — empty digits dim,/// the active digit+label bolds — so navigation works at any width. `width` is@@ -931,42 +945,48 @@ pub(super) fn render_preview_tabs(let tabs = [Tab {number: 1,- label: "HEAD±",- is_active: mode == PreviewMode::WorkingTree,- has_content: avail.working_tree,+ label: "diff",+ is_active: mode == PreviewMode::UnifiedDiff,+ has_content: avail.unified_diff,},Tab {number: 2,- label: "log",- is_active: mode == PreviewMode::Log,- has_content: avail.log,+ label: "working",+ is_active: mode == PreviewMode::WorkingTree,+ has_content: avail.working_tree,},Tab {number: 3,- label: "main…±",+ label: "committed",is_active: mode == PreviewMode::BranchDiff,has_content: avail.branch_diff,},Tab {number: 4,+ label: "log",+ is_active: mode == PreviewMode::Log,+ has_content: avail.log,+ },+ Tab {+ number: 5,label: "remote⇅",is_active: mode == PreviewMode::UpstreamDiff,has_content: avail.upstream,},Tab {- number: 5,+ number: 6,label: "summary",is_active: mode == PreviewMode::Summary,has_content: avail.summary,},Tab {- number: 6,+ number: 7,label: "pr",is_active: mode == PreviewMode::Pr,has_content: avail.pr,},Tab {- number: 7,+ number: 8,label: "comments",is_active: mode == PreviewMode::Comments,has_content: avail.comments,@@ -987,7 +1007,7 @@ pub(super) fn render_preview_tabs(// into the query); Tab/shift-tab cycle the same tabs.//// Order: primary action (Enter), preview navigation (ctrl-u/d scroll, then- // the Tab/alt-1…7 accelerators), then row actions, with Esc last.+ // the Tab/alt-1…8 accelerators), then row actions, with Esc last.//// The controls line is intentionally NOT width-managed: skim clips it on the// right on a narrow pane, but it's only a reminder. Note the trade-off of@@ -996,7 +1016,7 @@ pub(super) fn render_preview_tabs(// managed) tab bar above — so on a narrow pane the only on-screen reminder of// them can clip away.let controls = cformat!(- "<dim,cyan>Enter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel</>"+ "<dim,cyan>Enter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel</>");// Each tab/segment already ends with a full reset (so styling never bleeds@@ -1103,29 +1123,7 @@ impl PickerRow {/// the `pr` tab's `render_pr_pane` call — is testable with a given mode/// rather than the process-wide picker mode.fn render_preview(&self, mode: PreviewMode, width: usize, height: usize) -> String {- // Build preview: tabs header + content. `has_upstream` and- // `summaries_enabled` are synchronous skeleton-time facts (see- // `TabAvailability`); the diff tabs' live emptiness (`local_content`) and- // `pr` (`pr_tab_available`) read the row's live slots, refreshed as the- // list pipeline / `CiStatus` task stream in, so they can change between- // selections — a tab dims once its diff (or PR) is known empty, and stays- // available while still loading. The `summary` tab rides the same- // `local_content` signal: its content source is the combined diff, so it- // dims once both `branch_diff` and `working_tree` are known empty. Both- // reads are cheap (no body clone); the panes themselves are rendered once- // and memoized.- let avail = match &self.local {- Some(local) => TabAvailability::worktree(- self.local_content(),- local.has_upstream,- local.summaries_enabled,- self.pr_tab_available(),- ),- // A listed `--prs` row: the local-checkout tabs are empty (no- // working tree to diff) and the `pr` tab always has content (the- // static slot carries a `number`), matching `pr_tab_available`.- None => TabAvailability::listed_pr(),- };+ let avail = self.tab_availability();let mut result = render_preview_tabs(mode, avail, width);result.push_str(&match mode {// The PR-backed tabs read the same `pr_status` slot for both row@@ -1133,8 +1131,8 @@ impl PickerRow {// thread when the row has a PR (always, for a `--prs` row).PreviewMode::Pr => self.render_pr_pane_cached(width),PreviewMode::Comments => self.render_comments_pane(),- // The local-checkout tabs (working-tree/log/branch-diff/upstream/- // summary) compute locally for a worktree row; a `--prs` row has no+ // The local-checkout tabs (complete diff/working-tree/log/+ // branch-diff/upstream/summary) compute locally for a local row; a `--prs` row has no// checkout, so its `log` loads from the forge and the rest point at// the `pr` tab (see `render_listed_pr_mode`)._ => match &self.local {@@ -1161,32 +1159,19 @@ impl PickerRow {}}- /// Whether the PR-backed tabs (`pr` and `comments`) have content for this- /// row — they dim together only once the live fetch reports no PR. A cheap- /// discriminant read of the `pr_status` slot (no `PrStatus` clone, unlike- /// [`Self::pr_preview`]), so the tab bar can be drawn on every `preview()`- /// call without re-cloning the possibly-large body that- /// [`Self::render_pr_pane_cached`] already memoizes.- fn pr_tab_available(&self) -> bool {- match &*self.pr_status.lock().unwrap() {- None => true, // still fetching- Some(None) => false, // fetch reported no PR- Some(Some(status)) => status.number.is_some(), // a bare branch workflow is "no PR"+ /// The same live availability used by the tab bar and sequential cycling.+ fn tab_availability(&self) -> TabAvailability {+ match &self.local {+ Some(local) => TabAvailability::worktree(+ *local.local_content.lock().unwrap(),+ local.has_upstream,+ local.summaries_enabled,+ pr_tab_available(&self.pr_status),+ ),+ None => TabAvailability::listed_pr(),}}- /// Snapshot the row's live diff-content signals for the `working_tree` /- /// `branch_diff` / `upstream` tabs (see [`LocalContent`]). A cheap copy of- /// three `Option<bool>`s; the collect handler overwrites the slot as the list- /// pipeline lands. A listed `--prs` row has no checkout, so it reports the- /// default (all-`None`) signals — its diff tabs render placeholders anyway.- fn local_content(&self) -> LocalContent {- self.local- .as_ref()- .map(|l| *l.local_content.lock().unwrap())- .unwrap_or_default()- }-/// Render the `pr` pane, memoized in the shared `preview_cache` so repeated/// `preview()` calls (every keystroke while the tab is active) don't re-run/// the markdown render of the body. The other modes are pre-computed into@@ -1265,7 +1250,7 @@ impl PickerRow {/// Non-PR-tab content for a listed `--prs` row (no local checkout): the/// `log` tab loads commits in the background and reads from the cache; the- /// local-only tabs (working-tree, branch-diff, upstream, summary) have no+ /// local-only tabs (complete diff, working-tree, branch-diff, upstream, summary) have no/// PR equivalent, so they point the user at the `pr` tab.fn render_listed_pr_mode(&self, mode: PreviewMode) -> String {match mode {@@ -1307,9 +1292,10 @@ impl PickerRow {/// — so the placeholder just states what's loading.pub(super) fn loading_placeholder(mode: PreviewMode) -> String {let (verb, label) = match mode {+ PreviewMode::UnifiedDiff => ("Loading", "complete diff"),PreviewMode::WorkingTree => ("Loading", "working-tree diff"),- PreviewMode::Log => ("Loading", "log"),PreviewMode::BranchDiff => ("Loading", "branch diff"),+ PreviewMode::Log => ("Loading", "log"),PreviewMode::UpstreamDiff => ("Loading", "upstream diff"),PreviewMode::Summary => ("Generating", "summary"),// `preview()` routes the PR-backed tabs around this path: `pr` renders@@ -1341,6 +1327,10 @@ impl PickerRow {height: usize,) -> (String, bool) {match mode {+ PreviewMode::UnifiedDiff => (+ Self::page_diff(Self::compute_unified_diff_preview(repo, item, width), width),+ false,+ ),PreviewMode::WorkingTree => (Self::page_diff(Self::compute_working_tree_preview(repo, item, width), width),false,@@ -1375,7 +1365,91 @@ impl PickerRow {}}- /// Compute Tab 1: Working tree preview (uncommitted changes vs HEAD)+ fn worktree_diff_state(repo: &Repository, path: &std::path::Path) -> WorktreeDiffState {+ let Ok(status) = repo.worktree_at(path).status_porcelain_cached() else {+ return WorktreeDiffState::Unknown;+ };+ if status.trim().is_empty() {+ WorktreeDiffState::Clean+ } else if status.lines().any(|line| line.starts_with("?? ")) {+ WorktreeDiffState::HasUntracked+ } else {+ WorktreeDiffState::TrackedOnly+ }+ }++ /// Compute a live worktree diff. Porcelain selects the cheapest path, but+ /// never supplies the diff itself: tracked-only changes use ordinary+ /// `git diff`, while untracked or unknown state uses a temporary index so+ /// untracked files are included without touching the real index.+ fn compute_live_worktree_diff(+ repo: &Repository,+ path: &std::path::Path,+ base: &str,+ width: usize,+ state: WorktreeDiffState,+ ) -> anyhow::Result<Option<String>> {+ let worktree = repo.worktree_at(path);+ let diff = match state {+ WorktreeDiffState::Clean => return Ok(None),+ WorktreeDiffState::TrackedOnly => worktree.prepare_diff([base]),+ WorktreeDiffState::HasUntracked | WorktreeDiffState::Unknown => {+ worktree.prepare_diff_with_untracked([base])?+ }+ };+ diff.capture_stat_and_patch(width)+ }++ fn unavailable_diff(branch: &str, label: &str) -> String {+ let reset = Reset;+ cformat!(+ "{WARNING_SYMBOL}{reset} Could not load the {label} for <bold>{branch}</>{reset}\n"+ )+ }++ /// Compute Tab 1: one net diff from the comparison base to the worktree,+ /// including committed, staged, unstaged, and untracked changes.+ fn compute_unified_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {+ let branch = item.branch_name();+ let Some(wt_info) = item.worktree_data() else {+ // A branch-only row has no mutable worktree state, so its complete+ // diff is exactly the committed diff and can reuse that disk cache.+ return Self::compute_branch_diff_preview(repo, item, width);+ };+ // Collection asks for this same cached status. If the worktree is clean,+ // the complete view is exactly the committed view, so reuse its SHA-keyed+ // disk cache and skip the temporary index. A status failure falls through+ // to the diff itself, which may still succeed and is the better authority.+ let worktree_state = Self::worktree_diff_state(repo, &wt_info.path);+ if worktree_state == WorktreeDiffState::Clean {+ return Self::compute_branch_diff_preview(repo, item, width);+ }+ let reset = Reset;+ let Some(spec) = repo.branch_diff_spec(item.head()) else {+ return cformat!(+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no comparison base for a complete diff\n"+ );+ };+ let Some(base) = spec.working_base.as_deref() else {+ return Self::unavailable_diff(branch, "complete diff");+ };++ match Self::compute_live_worktree_diff(repo, &wt_info.path, base, width, worktree_state) {+ Ok(Some(diff)) => diff,+ Ok(None) => {+ let base_name = &spec.base_name;+ cformat!(+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no changes vs <bold>{base_name}</>{reset}\n"+ )+ }+ Err(error) => {+ log::debug!("Could not compute complete diff for {branch}: {error:#}");+ Self::unavailable_diff(branch, "complete diff")+ }+ }+ }++ /// Compute Tab 2: staged, unstaged, and untracked changes vs HEAD.fn compute_working_tree_preview(repo: &Repository, item: &ListItem, width: usize) -> String {let branch = item.branch_name();let Some(wt_info) = item.worktree_data() else {@@ -1385,12 +1459,23 @@ impl PickerRow {);};- let path = wt_info.path.display().to_string();-let reset = Reset;- compute_diff_preview(repo, &["-C", &path, "diff"], &["HEAD"], width).unwrap_or_else(|| {- cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no uncommitted changes\n")- })+ let worktree_state = Self::worktree_diff_state(repo, &wt_info.path);+ if worktree_state == WorktreeDiffState::Clean {+ return cformat!(+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no working-tree changes\n"+ );+ }+ match Self::compute_live_worktree_diff(repo, &wt_info.path, "HEAD", width, worktree_state) {+ Ok(Some(diff)) => diff,+ Ok(None) => cformat!(+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no working-tree changes\n"+ ),+ Err(error) => {+ log::debug!("Could not compute working-tree diff for {branch}: {error:#}");+ Self::unavailable_diff(branch, "working-tree diff")+ }+ }}/// Compute Tab 3: Branch diff preview (line diffs vs the comparison base)@@ -1434,15 +1519,22 @@ impl PickerRow {return render(&cached);}- let revs: Vec<&str> = spec.revs.iter().map(String::as_str).collect();- let entry = preview_cache::BranchDiffCacheEntry {- body: compute_diff_preview(repo, &["diff"], &revs, width),+ let body = match repo+ .prepare_diff(spec.revs.iter().cloned())+ .capture_stat_and_patch(width)+ {+ Ok(body) => body,+ Err(error) => {+ log::debug!("Could not compute committed diff for {branch}: {error:#}");+ return Self::unavailable_diff(branch, "committed diff");+ }};+ let entry = preview_cache::BranchDiffCacheEntry { body };preview_cache::write_branch_diff(repo, &spec.cache_sha, item.head(), width, &entry);render(&entry)}- /// Compute Tab 4: Upstream diff preview (ahead/behind vs tracking branch)+ /// Compute Tab 5: Upstream diff preview (ahead/behind vs tracking branch)////// Independent of `item.upstream` — `git rev-parse {branch}@{{u}}`/// probes existence (non-zero exit when `@{{u}}` is unresolvable) and@@ -1535,7 +1627,13 @@ impl PickerRow {} else {format!("{}...{upstream_sha}", item.head())};- compute_diff_preview(repo, &["diff"], &[&range], width)+ match repo.prepare_diff([range]).capture_stat_and_patch(width) {+ Ok(body) => body,+ Err(error) => {+ log::debug!("Could not compute upstream diff for {branch}: {error:#}");+ return Self::unavailable_diff(branch, "upstream diff");+ }+ }};let entry = preview_cache::UpstreamDiffCacheEntry {@@ -1888,22 +1986,24 @@ mod tests {}}- /// Width at which all seven full-form tabs fit, so the snapshots capture the+ /// Width at which all eight full-form tabs fit, so the snapshots capture the/// full bar (the compact fallback has its own test).const WIDE: usize = 200;- /// A worktree row whose three diff tabs (working-tree, branch-diff, upstream)- /// all have content — every diff signal known and non-empty.+ /// A worktree row whose diff tabs all have content — every diff signal known+ /// and non-empty.const CONTENT_FULL: LocalContent = LocalContent {working_tree: Some(true),+ summary_working_tree: Some(true),branch_diff: Some(true),upstream_diverged: Some(true),};- /// A worktree row whose three diff tabs are all *known* empty — a clean+ /// A worktree row whose diff tabs are all *known* empty — a clean/// working tree, no commits ahead, and up to date with a present upstream.const CONTENT_EMPTY: LocalContent = LocalContent {working_tree: Some(false),+ summary_working_tree: Some(false),branch_diff: Some(false),upstream_diverged: Some(false),};@@ -1912,16 +2012,17 @@ mod tests {fn test_render_preview_tabs() {// Each mode active, on a worktree row whose diffs all have content// (uncommitted changes, commits ahead, diverged from upstream) with- // summaries enabled but no PR (tabs 1-5 available; tabs 6 pr and 7+ // summaries enabled but no PR (tabs 1-6 available; tabs 7 pr and 8// comments dim). The active mode's label is bold, inactive available- // labels dim, and on the `pr` iteration tab 6 is active-but-empty —+ // labels dim, and on the `pr` iteration tab 7 is active-but-empty —// exercising the rule that emptiness dims even the active tab. Verifies// labels and structure.let wt = TabAvailability::worktree(CONTENT_FULL, true, true, false);for (name, mode) in [+ ("unified_diff", PreviewMode::UnifiedDiff),("working_tree", PreviewMode::WorkingTree),- ("log", PreviewMode::Log),("branch_diff", PreviewMode::BranchDiff),+ ("log", PreviewMode::Log),("upstream_diff", PreviewMode::UpstreamDiff),("summary", PreviewMode::Summary),("pr", PreviewMode::Pr),@@ -1930,15 +2031,15 @@ mod tests {}// Empty states. Three rows:- // - `empty_upstream_and_summary`: diffs still loading (so tabs 1 and 3+ // - `empty_upstream_and_summary`: diffs still loading (so tabs 1–3// read as available), no upstream ref, summaries disabled, no PR — dims- // tabs 4, 5, 6, and 7.+ // tabs 5, 6, 7, and 8.// - `empty_all_local_diffs`: every diff *known* empty (clean working tree,// no commits ahead, up to date with a present upstream) — dims tabs 1,- // 3, 4, plus 5/6/7, leaving only `log`. This is the behavior the diff+ // 2, 3, 5, plus 6/7/8, leaving only `log`. This is the behavior the diff// tabs gained: a dimmed number once the diff is known empty.- // - `pr_row`: a listed-PR row dims the working-tree/branch-diff/upstream/- // summary tabs but keeps log/pr/comments.+ // - `pr_row`: a listed-PR row dims the complete/working/committed/+ // upstream/summary tabs but keeps log/pr/comments.assert_snapshot!("empty_upstream_and_summary",render_preview_tabs(@@ -1961,6 +2062,39 @@ mod tests {);}+ #[test]+ fn tab_cycles_only_through_tabs_with_content() {+ let listed_pr = TabAvailability::listed_pr();+ assert_eq!(+ listed_pr.cycle_from(PreviewMode::Pr, true),+ PreviewMode::Comments+ );+ assert_eq!(+ listed_pr.cycle_from(PreviewMode::Pr, false),+ PreviewMode::Log,+ "shift-tab skips every empty local tab"+ );++ let clean_local = TabAvailability::worktree(CONTENT_EMPTY, true, false, false);+ assert_eq!(+ clean_local.cycle_from(PreviewMode::UnifiedDiff, true),+ PreviewMode::Log,+ "a clean row advances to its only available tab"+ );+ assert_eq!(+ clean_local.cycle_from(PreviewMode::Log, true),+ PreviewMode::Log,+ "cycling a one-tab row stays on that tab"+ );++ let changed_local = TabAvailability::worktree(CONTENT_FULL, true, true, false);+ assert_eq!(+ changed_local.cycle_from(PreviewMode::Summary, true),+ PreviewMode::UnifiedDiff,+ "cycling wraps past empty PR-backed tabs"+ );+ }+/// `LocalContent::from_item` reads each diff tab's emptiness off the row's/// `ListItem`, matching exactly what the corresponding pane renders.#[test]@@ -2032,8 +2166,8 @@ mod tests {"no remote configured is empty");- // `working_tree` matches `git diff HEAD`: tracked changes count, untracked- // alone does not (the pane wouldn't show them).+ // `working_tree` matches the temporary-index diff: tracked and untracked+ // changes both count.let worktree_with = |status: WorkingTreeStatus| {let mut item = ListItem::new_branch("abc".into(), "feature".into());item.kind = ItemKind::Worktree(Box::new(WorktreeData {@@ -2048,11 +2182,12 @@ mod tests {Some(true),"modified is tracked content");- // untracked only → `git diff HEAD` is empty.+ // untracked only is content too: the preview registers it with+ // intent-to-add in a temporary index.assert_eq!(worktree_with(WorkingTreeStatus::new(false, false, true, false, false)),- Some(false),- "untracked alone is not shown by `git diff HEAD`"+ Some(true),+ "untracked alone is shown by the working-tree diff");// A worktree whose status task hasn't landed yet stays loading.let mut pending = ListItem::new_branch("abc".into(), "feature".into());@@ -2066,7 +2201,14 @@ mod tests {/// before (or despite) the live ahead/behind signal.#[test]fn diff_tabs_dim_only_once_known_empty() {- let has = |avail: TabAvailability| (avail.working_tree, avail.branch_diff, avail.upstream);+ let has = |avail: TabAvailability| {+ (+ avail.unified_diff,+ avail.working_tree,+ avail.branch_diff,+ avail.upstream,+ )+ };// Loading (default): every diff tab available — we don't dim before we know.assert_eq!(@@ -2076,28 +2218,28 @@ mod tests {false,false)),- (true, true, true),+ (true, true, true, true),"loading → available");// Known empty + a present upstream: all three dim.assert_eq!(has(TabAvailability::worktree(CONTENT_EMPTY, true, false, false)),- (false, false, false),+ (false, false, false, false),"known empty → dim");// Known non-empty: all three available.assert_eq!(has(TabAvailability::worktree(CONTENT_FULL, true, false, false)),- (true, true, true),+ (true, true, true, true),"known content → available");// No tracking ref: the upstream tab dims regardless of the live signal —// the synchronous floor wins over a (stale or loading) divergence read.assert!(- !has(TabAvailability::worktree(CONTENT_FULL, false, false, false)).2,+ !has(TabAvailability::worktree(CONTENT_FULL, false, false, false)).3,"no upstream ref → dim despite a 'diverged' signal");}@@ -2130,11 +2272,13 @@ mod tests {// Only one diff has content → still something to summarize → available.let working_only = LocalContent {working_tree: Some(true),+ summary_working_tree: Some(true),branch_diff: Some(false),upstream_diverged: Some(false),};let branch_only = LocalContent {working_tree: Some(false),+ summary_working_tree: Some(false),branch_diff: Some(true),upstream_diverged: Some(false),};@@ -2144,6 +2288,17 @@ mod tests {);assert!(summary(branch_only, true), "commits ahead → available");+ let untracked_only = LocalContent {+ working_tree: Some(true),+ summary_working_tree: Some(false),+ branch_diff: Some(false),+ upstream_diverged: Some(false),+ };+ assert!(+ !summary(untracked_only, true),+ "untracked-only work is absent from the summary pane's combined diff"+ );+// Still loading (both unknown) → available; don't dim before we know.assert!(summary(LocalContent::default(), true),@@ -2160,14 +2315,14 @@ mod tests {// A --prs row with the `pr` tab active, in a narrow pane.let compact = render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), 40);let plain = compact.lines().next().unwrap().ansi_strip().to_string();- // Every digit 1-7 is present; only the active tab keeps its label.- for n in 1..=7 {+ // Every digit 1-8 is present; only the active tab keeps its label.+ for n in 1..=8 {assert!(plain.contains(&n.to_string()),"digit {n} present: {plain:?}");}- assert!(plain.contains("6: pr"), "active tab labeled: {plain:?}");+ assert!(plain.contains("7: pr"), "active tab labeled: {plain:?}");assert!(!plain.contains("comments"),"inactive label dropped: {plain:?}"@@ -2179,7 +2334,7 @@ mod tests {// The same row in a wide pane uses the full bar (labels for all tabs).let full = render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), WIDE);assert!(- full.contains("7: ") && full.contains("comments"),+ full.contains("8: ") && full.contains("comments"),"wide pane keeps full labels");@@ -2310,9 +2465,10 @@ mod tests {fn test_loading_placeholder_all_modes() {// Verifies wording and refresh-key hint per mode.for (name, mode) in [+ ("unified_diff", PreviewMode::UnifiedDiff),("working_tree", PreviewMode::WorkingTree),- ("log", PreviewMode::Log),("branch_diff", PreviewMode::BranchDiff),+ ("log", PreviewMode::Log),("upstream_diff", PreviewMode::UpstreamDiff),("summary", PreviewMode::Summary),// `Pr` isn't backed by the preview cache — it renders from the@@ -2662,14 +2818,14 @@ mod tests {// In Pr mode, `render_preview` assembles the tab bar plus the worktree PR// pane — the dispatch arm `SkimItem::preview` reaches once the picker-state- // file selects mode 6. The pane shows the title and the markdown body.- let pr_pane = row.render_preview(PreviewMode::Pr, 80, 24);+ // state selects mode 7. The pane shows the title and the markdown body.+ let pr_pane = row.render_preview(PreviewMode::Pr, WIDE, 24);// Strip ANSI before checking the tab labels: the active `pr` tab is bold,- // so `6: pr` is split by an SGR escape in the raw string (the bar's own+ // so `7: pr` is split by an SGR escape in the raw string (the bar's own// test, `test_render_preview_tabs`, snapshots the styled form).let bar = pr_pane.ansi_strip().to_string();- assert!(bar.contains("6: pr"), "pr tab: {bar:?}");- assert!(bar.contains("7: comments"), "comments tab: {bar:?}");+ assert!(bar.contains("7: pr"), "pr tab: {bar:?}");+ assert!(bar.contains("8: comments"), "comments tab: {bar:?}");assert!(pr_pane.contains("Fix the flaky retry"),"title: {pr_pane:?}"@@ -2683,10 +2839,12 @@ mod tests {"description body rendered: {pr_pane:?}");- // `SkimItem::preview` reads the default in-memory mode (WorkingTree, since- // no tab switch happens in this test) and delegates to `render_preview`,- // exercising the wrapper and the non-pr dispatch arm (cache miss → loading- // placeholder).+ // `SkimItem::preview` reads the default in-memory mode (UnifiedDiff,+ // since no tab switch happens in this test) and delegates to+ // `render_preview`, exercising the wrapper and the non-pr dispatch arm+ // (cache miss → loading placeholder).+ let _state =+ super::super::preview::PreviewState::new(super::super::preview::PreviewLayout::Right);let ctx = PreviewContext {query: "",cmd_query: "",@@ -2700,9 +2858,9 @@ mod tests {let ItemPreview::AnsiText(text) = row.preview(ctx) else {panic!("expected AnsiText preview");};- assert!(text.contains("HEAD"), "tab bar present: {text:?}");+ assert!(text.contains("diff"), "tab bar present: {text:?}");assert!(- text.contains("Loading working-tree diff"),+ text.contains("Loading complete diff"),"non-pr arm placeholder: {text:?}");}@@ -2827,6 +2985,98 @@ mod tests {);}+ #[test]+ fn unified_diff_is_net_change_and_subsidiary_diffs_include_untracked() {+ use crate::commands::list::model::{ItemKind, WorktreeData};++ let (t, repo) = repo_with_main();+ let shared = t.path().join("shared.txt");+ std::fs::write(&shared, "base\n").unwrap();+ repo.run_command(&["add", "shared.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "add shared file"])+ .unwrap();++ repo.run_command(&["checkout", "-b", "feature"]).unwrap();+ std::fs::write(&shared, "committed\n").unwrap();+ repo.run_command(&["add", "shared.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "change shared file"])+ .unwrap();++ // Reverse the committed edit in the working tree, so the complete diff+ // must cancel it while each subsidiary pane still shows its side.+ std::fs::write(&shared, "base\n").unwrap();+ std::fs::write(t.path().join("untracked.txt"), "loose\n").unwrap();+ repo.run_command(&["config", "status.showUntrackedFiles", "no"])+ .unwrap();++ let mut item = item_at(&repo, "feature");+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {+ path: t.path().to_path_buf(),+ ..Default::default()+ }));++ let real_index = repo.current_worktree().git_dir().unwrap().join("index");+ let index_before = std::fs::read(&real_index).unwrap();+ let unified = PickerRow::compute_unified_diff_preview(&repo, &item, 80);+ let working = PickerRow::compute_working_tree_preview(&repo, &item, 80);+ let committed = PickerRow::compute_branch_diff_preview(&repo, &item, 80);+ let index_after = std::fs::read(&real_index).unwrap();++ assert!(+ unified.contains("untracked.txt"),+ "complete diff includes untracked files: {unified:?}"+ );+ assert!(+ !unified.contains("shared.txt"),+ "opposing committed and working changes cancel in the net diff: {unified:?}"+ );+ assert!(+ working.contains("shared.txt") && working.contains("untracked.txt"),+ "working pane shows both the reversal and untracked file: {working:?}"+ );+ assert!(+ committed.contains("shared.txt") && !committed.contains("untracked.txt"),+ "committed pane excludes worktree-only content: {committed:?}"+ );+ assert_eq!(+ index_after, index_before,+ "preview computation must leave the real index byte-identical"+ );+ }++ #[test]+ fn worktree_diff_surfaces_full_diff_command_failure() {+ use crate::commands::list::model::{ItemKind, WorktreeData};++ let (t, repo) = repo_with_main();+ std::fs::write(t.path().join(".gitattributes"), "*.txt diff=explode\n").unwrap();+ std::fs::write(t.path().join("tracked.txt"), "base\n").unwrap();+ repo.run_command(&["add", ".gitattributes", "tracked.txt"])+ .unwrap();+ repo.run_command(&["commit", "-m", "add textconv fixture"])+ .unwrap();+ repo.run_command(&["config", "diff.explode.textconv", "false"])+ .unwrap();+ std::fs::write(t.path().join("tracked.txt"), "changed\n").unwrap();++ let mut item = item_at(&repo, "main");+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {+ path: t.path().to_path_buf(),+ ..Default::default()+ }));++ let unified = PickerRow::compute_unified_diff_preview(&repo, &item, 80);+ let working = PickerRow::compute_working_tree_preview(&repo, &item, 80);+ assert!(+ unified.contains("Could not load the complete diff"),+ "a failed full diff must not leave a plausible stat-only pane: {unified:?}"+ );+ assert!(+ working.contains("Could not load the working-tree diff"),+ "working pane must report the failed full diff: {working:?}"+ );+ }+#[test]fn branch_diff_orphan_shows_full_content() {// An orphan branch shares no history with the comparison base, so its@@ -2938,7 +3188,10 @@ mod tests {repo.run_command(&["update-ref", "refs/heads/-weird", head.trim()]).unwrap();- let out = compute_diff_preview(&repo, &["diff"], &[root.trim(), "-weird"], 80)+ let out = repo+ .prepare_diff([root.trim(), "-weird"])+ .capture_stat_and_patch(80)+ .expect("diff commands succeed").expect("non-empty diff between the two refs");assert!(out.contains("fenced.txt"),@@ -2961,7 +3214,7 @@ mod tests {let output = PickerRow::compute_working_tree_preview(&repo, &item, 80);assert!(- output.contains("main") && output.contains("has no uncommitted changes"),+ output.contains("main") && output.contains("has no working-tree changes"),"expected clean-worktree headline, got: {output:?}");}@@ -2971,7 +3224,7 @@ mod tests {// Pre-populate the disk cache with a sentinel value, then call// compute — a hit must return the sentinel verbatim instead of// running git diff. Proves the SHA + width key is the lookup path- // and that a hit short-circuits before `compute_diff_preview`.+ // and that a hit short-circuits before preparing or running a diff.let (t, repo) = repo_with_main();repo.run_command(&["checkout", "-b", "feature"]).unwrap();std::fs::write(t.path().join("real.txt"), "real\n").unwrap();@@ -3324,7 +3577,7 @@ mod tests {// The per-tab `{reset}` is appended in the full bar regardless of a// tab's internal styling, so the reset/divider counts hold whether a tab// is active (bold label), inactive-available (dim label), or empty (dim- // number + label — here tabs 6 pr and 7 comments). WIDE forces the full+ // number + label — here tabs 7 pr and 8 comments). WIDE forces the full// (not compact) bar.let output = render_preview_tabs(PreviewMode::WorkingTree,@@ -3339,13 +3592,13 @@ mod tests {// This prevents bold/dim from bleeding into the " | " dividerslet full_reset = "\x1b[0m";- // Count resets - should have one after each of the 7 tabs- assert_eq!(first_line.matches(full_reset).count(), 7);+ // Count resets - should have one after each of the 8 tabs+ assert_eq!(first_line.matches(full_reset).count(), 8);// The sequence should be: style + text + [22m + [0m + divider// Check that dividers come after full resetslet parts: Vec<&str> = first_line.split(" | ").collect();- assert_eq!(parts.len(), 7);+ assert_eq!(parts.len(), 8);assert!(parts.iter().all(|part| part.ends_with(full_reset)));// Controls line should end with full reset to ensure clean state for preview contentdiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex bf19c21ed..c8fa78e64 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1670,7 +1670,7 @@ pub fn handle_picker(_ => (80, 24),};- // Reset the preview tab to working-tree and select the layout from the+ // Reset the preview tab to the complete diff and select the layout from the// terminal size.let state = PreviewState::new(PreviewLayout::for_dimensions(term_width as f64,@@ -1684,7 +1684,8 @@ pub fn handle_picker(// and `root()`, and is also short-circuited when `collect::collect` calls// `repo.url_template()` → `load_project_config()` → `project_config_path()`// (which runs `prewarm_info` again — now a cache hit).- let _ = repo.current_worktree().prewarm_info();+ let current_worktree = repo.current_worktree();+ let _ = current_worktree.prewarm_info();// Preview cache is created up-front so the speculative first-item// preview can run in parallel with `collect::collect` below. Tasks@@ -1714,16 +1715,22 @@ pub fn handle_picker(let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);// Speculative warm-up: the picker sorts the current worktree first, and- // the default tab (WorkingTree = `git diff HEAD` in that worktree) is- // what skim will render first. Kicking this off before `collect::collect`- // overlaps preview compute with list collection.+ // the default tab (UnifiedDiff = comparison base through the worktree,+ // including untracked files) is what skim will render first. Kicking this+ // off before `collect::collect` overlaps preview compute with list+ // collection.// The real spawn later skips this key via `contains_key`.- if let (Ok(Some(branch)), Ok(path)) = (- repo.current_worktree().branch(),- repo.current_worktree().root(),+ if let (Ok(Some(branch)), Ok(path), Ok(Some(head))) = (+ current_worktree.branch(),+ current_worktree.root(),+ current_worktree.head_sha(),) {use super::list::model::{ItemKind, ListItem, WorktreeData};- let mut item = ListItem::new_branch(String::new(), branch);+ // UnifiedDiff resolves its comparison base from the row's HEAD. An+ // empty placeholder would let this speculative producer cache an+ // error before collection's real row gets a chance to fill the same+ // key, so the warm-up only runs with a resolved commit.+ let mut item = ListItem::new_branch(head, branch);item.kind = ItemKind::Worktree(Box::new(WorktreeData {path,..Default::default()@@ -1736,7 +1743,7 @@ pub fn handle_picker(orchestrator.spawn_preview(&orchestrator.generation(),Arc::new(item),- PreviewMode::WorkingTree,+ PreviewMode::UnifiedDiff,dims,);}@@ -1984,10 +1991,10 @@ pub fn handle_picker(.color("fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108").cmd_collector(Rc::new(RefCell::new(collector)) as Rc<RefCell<dyn CommandCollector>>).bind(vec![- // Preview-tab switching (alt-1..alt-7 jump to a tab; tab / shift-tab+ // Preview-tab switching (alt-1..alt-8 jump to a tab; tab / shift-tab// cycle) is installed natively below via `install_preview_tab_keybindings`// rather than here — those keys run Rust callbacks, not shell commands.- // Bare digits 1-7 stay unbound so they flow to the query input (a PR+ // Bare digits 1-8 stay unbound so they flow to the query input (a PR// number, or digits within a branch name).//// Create new worktree with query as branch name (alt-c for "create")@@ -2197,12 +2204,12 @@ pub fn handle_picker(Ok(())}-/// Install the preview-tab switches into skim's keymap: alt-1…alt-7 jump to a+/// Install the preview-tab switches into skim's keymap: alt-1…alt-8 jump to a/// tab, tab / shift-tab cycle forward / backward.////// skim's string bind API only maps keys to its built-in actions, so these go-/// in as `Action::Custom` callbacks that set the process-wide-/// [`PreviewStateData`] mode and return `Event::RunPreview` to repaint. They're+/// in as `Action::Custom` callbacks that update [`PreviewStateData`] and return+/// `Event::RunPreview` to repaint. They're/// native rather than `execute-silent` shell commands, so they behave/// identically everywhere — the previous `echo`/`tr`/`mv` keybind bodies ran/// through skim's shell, which on Windows is cmd.exe and has neither `tr` nor@@ -2219,19 +2226,21 @@ fn install_preview_tab_keybindings(keymap: &mut skim::binds::KeyMap) {// alt-N jumps to tab N (1-indexed, matching PreviewMode's discriminant).let switch_to = |mode: PreviewMode| {Action::Custom(ActionCallback::new_sync(move |_app| {- PreviewStateData::set_mode(mode);+ PreviewStateData::select_mode(mode);Ok(vec![Event::RunPreview])}))};- for digit in 1..=7u8 {+ for digit in 1..=8u8 {if let Ok(key) = parse_key(&format!("alt-{digit}")) {keymap.insert(key, vec![switch_to(PreviewMode::from_u8(digit))]);}}let cycle = |forward: bool| {- Action::Custom(ActionCallback::new_sync(move |_app| {- PreviewStateData::rotate(forward);+ Action::Custom(ActionCallback::new_sync(move |app| {+ if app.item_list.selected().is_some() {+ PreviewStateData::request_cycle(forward);+ }Ok(vec![Event::RunPreview])}))};@@ -2620,7 +2629,7 @@ pub mod tests {let mut keymap = KeyMap::default();install_preview_tab_keybindings(&mut keymap);- let mut specs: Vec<String> = (1..=7).map(|d| format!("alt-{d}")).collect();+ let mut specs: Vec<String> = (1..=8).map(|d| format!("alt-{d}")).collect();specs.extend(["tab", "btab", "shift-btab", "shift-tab"].map(String::from));for spec in specs {let key = parse_key(&spec).expect("known key spec parses");diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex 29c28dfb6..11ef10a00 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -3,67 +3,69 @@//! Tracks the active preview tab (in process memory) and selects the preview//! layout for the interactive selector.-use std::sync::atomic::{AtomicU8, Ordering};+use std::sync::atomic::{AtomicI8, AtomicU8, Ordering};/// Preview modes for the interactive selector////// Each mode shows a different aspect of the selected row:-/// 1. WorkingTree: Uncommitted changes (git diff HEAD --stat)-/// 2. Log: Commit history since diverging from the default branch (git log with merge-base)-/// 3. BranchDiff: Line diffs since the merge-base with the default branch (git diff --stat DEFAULT…)-/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)-/// 5. Summary: LLM-generated branch summary (requires [commit.generation] config)-/// 6. Pr: The selected row's PR/MR, rendered from already-fetched data (no network)-/// 7. Comments: The PR/MR's comment thread (background forge fetch on any row+/// 1. UnifiedDiff: Committed and working-tree changes in one diff, including untracked files+/// 2. WorkingTree: Staged, unstaged, and untracked changes against HEAD+/// 3. BranchDiff: Committed changes since the comparison base+/// 4. Log: Commit history since diverging from the default branch (git log with merge-base)+/// 5. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)+/// 6. Summary: LLM-generated branch summary (requires [commit.generation] config)+/// 7. Pr: The selected row's PR/MR, rendered from already-fetched data (no network)+/// 8. Comments: The PR/MR's comment thread (background forge fetch on any row/// whose branch has an open PR — worktree row or `--prs` row alike)////// A mode whose content is structurally absent for the current row is rendered/// de-emphasized in the tab bar (see `TabAvailability` / `render_preview_tabs`):-/// tab 4 when the branch has no upstream, tab 5 when summaries are disabled or-/// the branch has nothing to summarize, the working-tree/branch-diff/upstream/-/// summary tabs on a `--prs` row (no local worktree), and the PR-backed tabs 6-/// (pr) and 7 (comments) when the row's branch has no PR. The PR-backed tabs are+/// tab 5 when the branch has no upstream, tab 6 when summaries are disabled or+/// the branch has nothing to summarize, the unified/working-tree/branch-diff/+/// upstream/summary tabs on a `--prs` row (no local worktree), and the PR-backed tabs 7+/// (pr) and 8 (comments) when the row's branch has no PR. The PR-backed tabs are/// available together, by the same rule, on every row — `--prs` only decides/// whether a PR row is listed, not how these tabs behave.////// Loosely aligned with `wt list` columns, though not a perfect match:-/// - Tab 1 corresponds to "HEAD±" column-/// - Tab 2 shows commits (related to "main↕" counts)-/// - Tab 3 corresponds to "main…±" column-/// - Tab 4 corresponds to "Remote⇅" column-/// - Tab 6 corresponds to the "CI" column's PR/MR+/// - Tabs 1–3 decompose all changes into working-tree and committed diffs+/// - Tab 4 shows commits (related to "main↕" counts)+/// - Tab 5 corresponds to "Remote⇅" column+/// - Tab 7 corresponds to the "CI" column's PR/MR#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(super) enum PreviewMode {- WorkingTree = 1,- Log = 2,+ UnifiedDiff = 1,+ WorkingTree = 2,BranchDiff = 3,- UpstreamDiff = 4,- Summary = 5,- Pr = 6,- Comments = 7,+ Log = 4,+ UpstreamDiff = 5,+ Summary = 6,+ Pr = 7,+ Comments = 8,}impl PreviewMode {pub(super) fn from_u8(n: u8) -> Self {match n {- 2 => Self::Log,+ 2 => Self::WorkingTree,3 => Self::BranchDiff,- 4 => Self::UpstreamDiff,- 5 => Self::Summary,- 6 => Self::Pr,- 7 => Self::Comments,- _ => Self::WorkingTree,+ 4 => Self::Log,+ 5 => Self::UpstreamDiff,+ 6 => Self::Summary,+ 7 => Self::Pr,+ 8 => Self::Comments,+ _ => Self::UnifiedDiff,}}- /// The next tab, wrapping `Comments` → `WorkingTree` (tab key).+ /// The next tab, wrapping `Comments` → `UnifiedDiff` (tab key).pub(super) fn next(self) -> Self {- Self::from_u8(if self as u8 >= 7 { 1 } else { self as u8 + 1 })+ Self::from_u8(if self as u8 >= 8 { 1 } else { self as u8 + 1 })}- /// The previous tab, wrapping `WorkingTree` → `Comments` (shift-tab key).+ /// The previous tab, wrapping `UnifiedDiff` → `Comments` (shift-tab key).pub(super) fn prev(self) -> Self {- Self::from_u8(if self as u8 <= 1 { 7 } else { self as u8 - 1 })+ Self::from_u8(if self as u8 <= 1 { 8 } else { self as u8 - 1 })}/// Whether this tab is in [`LOCAL_GIT_MODES`].@@ -72,16 +74,17 @@ impl PreviewMode {}}-/// The four tabs computed from local git alone — the one canonical set both+/// The five tabs computed from local git alone — the one canonical set both/// preview producers consume: the orchestrator precomputes exactly these/// (plus summaries), and the demand worker serves them on a cache miss (see/// `PreviewDemand`), so the two can't drift. Summary is excluded (an LLM/// call on tab navigation would be a surprise cost); Pr and Comments/// render/fetch through their own paths.-pub(super) const LOCAL_GIT_MODES: [PreviewMode; 4] = [+pub(super) const LOCAL_GIT_MODES: [PreviewMode; 5] = [+ PreviewMode::UnifiedDiff,PreviewMode::WorkingTree,- PreviewMode::Log,PreviewMode::BranchDiff,+ PreviewMode::Log,PreviewMode::UpstreamDiff,];@@ -233,7 +236,7 @@ impl PreviewLayout {/// One picker runs per process, so a single process-wide value is the source of/// truth: `PickerRow::preview` reads it to choose/// what to render, and the keymap's `Action::Custom` callbacks (installed in-/// `super::install_preview_tab_keybindings`) write it on alt-1…alt-7 / tab /+/// `super::install_preview_tab_keybindings`) write it on alt-1…alt-8 / tab //// shift-tab, then re-run the preview.////// It lives in memory rather than on disk. Tab switching used to write a digit@@ -242,45 +245,65 @@ impl PreviewLayout {/// way to react to a keypress. The native `Action::Custom` path removes that/// constraint — and with it the file, whose `tr`/`mv` commands skim's Windows/// shell (cmd.exe) cannot run.-static PREVIEW_MODE: AtomicU8 = AtomicU8::new(PreviewMode::WorkingTree as u8);+/// `0` means the caller-supplied automatic choice; `1..=8` is an explicit+/// [`PreviewMode`]. Keeping both states in one atomic prevents an impossible+/// "explicit flag + unrelated configured mode" combination.+static PREVIEW_SELECTION: AtomicU8 = AtomicU8::new(0);+/// A Tab keypress is resolved by the selected row when `RunPreview` renders it,+/// because that row already owns the live availability data.+static PENDING_CYCLE: AtomicI8 = AtomicI8::new(0);pub(super) struct PreviewStateData;impl PreviewStateData {- /// The active preview tab.- pub(super) fn read_mode() -> PreviewMode {- PreviewMode::from_u8(PREVIEW_MODE.load(Ordering::Relaxed))+ /// Active mode for a row. Until the user chooses a tab, local rows open on+ /// the unified diff while forge-only rows open on their PR details. Once a+ /// tab is chosen, that explicit mode stays sticky across row navigation.+ pub(super) fn read_mode_for(default_mode: PreviewMode) -> PreviewMode {+ effective_mode(PREVIEW_SELECTION.load(Ordering::Relaxed), default_mode)}- /// Jump to a specific tab (alt-1…alt-7).- pub(super) fn set_mode(mode: PreviewMode) {- PREVIEW_MODE.store(mode as u8, Ordering::Relaxed);+ /// Jump to a specific tab (alt-1…alt-8), making the choice sticky.+ pub(super) fn select_mode(mode: PreviewMode) {+ PREVIEW_SELECTION.store(mode as u8, Ordering::Relaxed);}- /// Cycle to the next (`forward`) / previous tab, wrapping around (tab /- /// shift-tab). Runs on skim's single event-loop thread, so the- /// load-then-store needs no compare-and-swap.- pub(super) fn rotate(forward: bool) {- let current = Self::read_mode();- Self::set_mode(if forward {- current.next()- } else {- current.prev()- });+ pub(super) fn request_cycle(forward: bool) {+ PENDING_CYCLE.store(if forward { 1 } else { -1 }, Ordering::Relaxed);+ }++ pub(super) fn take_cycle_request() -> Option<bool> {+ match PENDING_CYCLE.swap(0, Ordering::Relaxed) {+ 1 => Some(true),+ -1 => Some(false),+ _ => None,+ }+ }++ fn reset() {+ PREVIEW_SELECTION.store(0, Ordering::Relaxed);+ PENDING_CYCLE.store(0, Ordering::Relaxed);+ }+}++fn effective_mode(selection: u8, default_mode: PreviewMode) -> PreviewMode {+ match selection {+ 0 => default_mode,+ explicit => PreviewMode::from_u8(explicit),}}/// Per-session preview state: the initial layout (selected once from the/// terminal size in `handle_picker`). Constructing it also resets-/// [`PreviewStateData`] to the working-tree tab so every picker opens on the-/// same tab.+/// [`PreviewStateData`] to automatic mode so local rows open on the unified+/// diff and forge-only rows open on PR details.pub(super) struct PreviewState {pub(super) initial_layout: PreviewLayout,}impl PreviewState {pub(super) fn new(initial_layout: PreviewLayout) -> Self {- PreviewStateData::set_mode(PreviewMode::WorkingTree);+ PreviewStateData::reset();Self { initial_layout }}}@@ -291,16 +314,31 @@ mod tests {#[test]fn test_preview_mode_from_u8() {- assert_eq!(PreviewMode::from_u8(1), PreviewMode::WorkingTree);- assert_eq!(PreviewMode::from_u8(2), PreviewMode::Log);+ assert_eq!(PreviewMode::from_u8(1), PreviewMode::UnifiedDiff);+ assert_eq!(PreviewMode::from_u8(2), PreviewMode::WorkingTree);assert_eq!(PreviewMode::from_u8(3), PreviewMode::BranchDiff);- assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);- assert_eq!(PreviewMode::from_u8(5), PreviewMode::Summary);- assert_eq!(PreviewMode::from_u8(6), PreviewMode::Pr);- assert_eq!(PreviewMode::from_u8(7), PreviewMode::Comments);- // Invalid values default to WorkingTree- assert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);- assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);+ assert_eq!(PreviewMode::from_u8(4), PreviewMode::Log);+ assert_eq!(PreviewMode::from_u8(5), PreviewMode::UpstreamDiff);+ assert_eq!(PreviewMode::from_u8(6), PreviewMode::Summary);+ assert_eq!(PreviewMode::from_u8(7), PreviewMode::Pr);+ assert_eq!(PreviewMode::from_u8(8), PreviewMode::Comments);+ // Invalid values default to UnifiedDiff+ assert_eq!(PreviewMode::from_u8(0), PreviewMode::UnifiedDiff);+ assert_eq!(PreviewMode::from_u8(99), PreviewMode::UnifiedDiff);+ }++ #[test]+ fn test_automatic_mode_uses_the_rows_default() {+ assert_eq!(+ effective_mode(0, PreviewMode::UnifiedDiff),+ PreviewMode::UnifiedDiff+ );+ assert_eq!(effective_mode(0, PreviewMode::Pr), PreviewMode::Pr);+ assert_eq!(+ effective_mode(PreviewMode::WorkingTree as u8, PreviewMode::Pr),+ PreviewMode::WorkingTree,+ "an explicit choice stays sticky on a forge-only row"+ );}#[test]@@ -448,28 +486,29 @@ mod tests {#[test]fn test_preview_mode_rotation() {- // tab cycles forward through all seven tabs and wraps; shift-tab is the+ // tab cycles forward through all eight tabs and wraps; shift-tab is the// exact inverse. These drive the tab / shift-tab keybindings.let forward: Vec<PreviewMode> =- std::iter::successors(Some(PreviewMode::WorkingTree), |m| {+ std::iter::successors(Some(PreviewMode::UnifiedDiff), |m| {let next = m.next();- (next != PreviewMode::WorkingTree).then_some(next)+ (next != PreviewMode::UnifiedDiff).then_some(next)}).collect();assert_eq!(forward,vec![+ PreviewMode::UnifiedDiff,PreviewMode::WorkingTree,- PreviewMode::Log,PreviewMode::BranchDiff,+ PreviewMode::Log,PreviewMode::UpstreamDiff,PreviewMode::Summary,PreviewMode::Pr,PreviewMode::Comments,]);- assert_eq!(PreviewMode::Comments.next(), PreviewMode::WorkingTree);- assert_eq!(PreviewMode::WorkingTree.prev(), PreviewMode::Comments);+ assert_eq!(PreviewMode::Comments.next(), PreviewMode::UnifiedDiff);+ assert_eq!(PreviewMode::UnifiedDiff.prev(), PreviewMode::Comments);for mode in forward {assert_eq!(mode.next().prev(), mode);}diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex 7742fcbc7..8a2375106 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -28,16 +28,20 @@//! **On-disk** — content-addressed, cross-session, consulted only on an//! in-memory miss. [`super::preview_cache`] holds Log / BranchDiff ///! UpstreamDiff keyed by git SHA(s) + dimensions; [`crate::summary`] holds-//! summaries keyed by a hash of the diff. WorkingTree, Pr, and Comments have no-//! disk tier. Because these keys *are* content-addressed, moved content yields a-//! fresh key and a natural miss — the disk tier is never stale, which is what-//! makes clearing the in-memory tier above it cheap (an unchanged branch-//! re-reads disk; only changed content recomputes).+//! summaries keyed by a hash of the diff. UnifiedDiff reuses BranchDiff's disk+//! entry for a clean worktree or branch-only row; a dirty UnifiedDiff and every+//! WorkingTree preview are live-only. Pr and Comments have no general disk tier+//! (GitHub comments use their own `updatedAt` cache below). Because the stable+//! keys *are* content-addressed, moved content yields a fresh key and a natural+//! miss — the disk tier is never stale, which is what makes clearing the+//! in-memory tier above it cheap (an unchanged branch re-reads disk; only+//! changed content recomputes).//!//! # What backs an in-memory miss, per mode//!//! | Mode | Disk tier | Recompute on miss |//! |------|-----------|-------------------|+//! | UnifiedDiff | BranchDiff cache when clean / branch-only; none when dirty | cached committed diff or live net worktree diff |//! | WorkingTree | none (a dirty tree has no stable hash) | live `git diff HEAD` |//! | Log / BranchDiff / UpstreamDiff | [`super::preview_cache`], SHA-keyed | `git`, then write disk |//! | Summary | [`crate::summary`], diff-hash-keyed | LLM, then write disk |@@ -50,9 +54,9 @@//! `(branch, Pr)` entry when a row's live status changes, `--prs` rows drop//! theirs on rebuild, and a corrected PR number drops the stale `Comments`//! thread (see [`super::progressive_handler`]).-//! - **WorkingTree / Log / BranchDiff / UpstreamDiff / Summary** have *no*-//! per-event in-memory invalidation. Within a session they are reconciled with-//! moved content only by a refresh.+//! - **UnifiedDiff / WorkingTree / Log / BranchDiff / UpstreamDiff / Summary**+//! have *no* per-event in-memory invalidation. Within a session they are+//! reconciled with moved content only by a refresh.//! - **Refresh (`alt-r`)** calls [`PreviewOrchestrator::refresh`] (from//! `PipelineFactory::spawn`, gated on `rebuild_repo`), which supersedes the//! prior spawn's producers, rebinds the compute repo to the rebuilt spawn's,@@ -107,10 +111,12 @@//! choke point: it inserts into the cache and pokes [`super::preview_notify`] so a//! compute that lands after skim already drew the pane repaints without a//! keystroke. Precompute is tiered — [`PreviewOrchestrator::spawn_initial_precompute`]-//! at skeleton time (item 0 × the four local modes + summary, plus every row's-//! default tab) and [`PreviewOrchestrator::spawn_deferred_precompute`] after the-//! row drain (the rest); Pr and Comments are never precomputed. Both tiers re-run-//! on every spawn, including a refresh (after its clear). `spawn_preview` and+//! at skeleton time (item 0 × the five local modes + summary, plus the default+//! tab for cheap branch-only rows) and [`PreviewOrchestrator::spawn_deferred_summaries`]+//! after the row drain (summaries for the remaining rows). Off-screen worktree+//! panes are demand-loaded instead of speculatively duplicating live worktree+//! I/O; Pr and Comments are never precomputed. Both tiers re-run on every spawn,+//! including a refresh (after its clear). `spawn_preview` and//! `spawn_compute` short-circuit on an in-memory hit, so a refresh must clear//! first or their recompute is a no-op; `spawn_summary` has no such guard and//! always recomputes — cheap, since `crate::summary` is gated by its own@@ -157,14 +163,12 @@ use super::summary;use crate::commands::list::collect::COLLECT_POOL;use crate::commands::list::model::ListItem;-/// The picker's initial preview tab — `WorkingTree`, shown when the-/// picker opens. Pre-computed for every row at skeleton time so j/k-/// navigation lands on warm content without paying the 4-mode bulk cost-/// per row during the row-fill window. The remaining [`LOCAL_GIT_MODES`]-/// for items 1..N are deferred until `spawn_deferred_precompute` fires-/// (after row drain); for the landing row they fire at skeleton time so-/// tab-cycling is responsive immediately.-const INITIAL_MODE: PreviewMode = PreviewMode::WorkingTree;+/// The picker's initial preview tab — `UnifiedDiff`, shown when the picker+/// opens. Precomputed for the landing row and cheap branch-only rows; off-screen+/// worktrees use the dedicated demand worker when selected so an untracked-heavy+/// tree cannot compete with initial row collection. For the landing row, every+/// local mode fires at skeleton time so tab-cycling is responsive immediately.+const INITIAL_MODE: PreviewMode = PreviewMode::UnifiedDiff;struct PendingGuard(Arc<AtomicUsize>);@@ -216,12 +220,8 @@ impl Default for SpawnGeneration {/// dedicated worker thread.////// Precompute alone leaves a gap: `SkimItem::preview` never computes (it only-/// reads the in-memory cache), so a tab whose precompute hasn't landed sits on-/// its loading placeholder until the background queue reaches it — behind the-/// row pipeline, its network tail (`COLLECT_POOL` workers park on blocking-/// `gh` subprocesses, and rayon has no task priorities), and the mode-major-/// deferred tier. In a large repo with many worktrees that's several seconds-/// of queue for a tab the user is staring at. The demand worker closes the+/// reads the in-memory cache), so a tab without precompute would otherwise sit+/// on its loading placeholder. The demand worker closes the/// gap: `preview()` routes a cache miss on a local-git tab here/// ([`PreviewMode::is_local_git`]), and the worker computes exactly that key,/// off `COLLECT_POOL` entirely — so the looked-at tab costs one disk-cache@@ -705,16 +705,17 @@ impl PreviewOrchestrator {/// Spawn the skeleton-time pre-compute tier.///- /// Fires at `on_skeleton`. Two layers of priority:- /// - First item × all 4 modes + first item summary — the user lands on+ /// Fires at `on_skeleton`. Two layers of work:+ /// - First item × all 5 modes + first item summary — the user lands on/// row 0 and frequently tab-cycles modes there.- /// - Items 1..N × [`INITIAL_MODE`] only — pre-warms the default tab- /// for every row so quick j/k navigation hits cached content,- /// bounded contention with the row pipeline (~N tasks).+ /// - Branch-only items 1..N × [`INITIAL_MODE`] — pre-warms the committed+ /// diff they can serve cheaply from the SHA-keyed cache. Off-screen+ /// worktrees are demand-loaded when selected: their untracked-inclusive+ /// default can require an index copy and full `git add -N` walk.///- /// The remaining [`LOCAL_GIT_MODES`] for items 1..N and their summaries- /// are deferred to [`Self::spawn_deferred_precompute`], which fires- /// after the row pipeline tears down.+ /// Summaries for items 1..N are deferred to+ /// [`Self::spawn_deferred_summaries`], which fires after the row pipeline+ /// tears down. Their subsidiary local-git modes are demand-loaded.pub(super) fn spawn_initial_precompute(&self,spawn_gen: &SpawnGeneration,@@ -732,39 +733,34 @@ impl PreviewOrchestrator {self.spawn_summary(spawn_gen, Arc::clone(first), llm.to_string());}- // Items 1..N: default tab only. Other modes wait for drain.- for item in items.iter().skip(1) {+ // Branch-only items 1..N: default tab only. Worktree-backed rows and+ // all other local modes are demand-loaded.+ for item in items+ .iter()+ .skip(1)+ .filter(|item| item.worktree_data().is_none())+ {self.spawn_preview(spawn_gen, Arc::clone(item), INITIAL_MODE, preview_dims);}}- /// Spawn the deferred pre-compute tier for items 1..N.+ /// Spawn configured summaries for items 1..N after collection completes.////// Fires from the picker handler's `on_collect_complete` hook — i.e./// after `collect::collect`'s drain ends. `COLLECT_POOL` serves/// both the row pipeline and the preview pipeline. Deferring this/// tier keeps these submissions out of that pool's injector while/// row tasks are still landing on workers' local deques. The- /// default tab for these rows already fired at skeleton time via- /// [`Self::spawn_initial_precompute`]; what's left is the rest of- /// [`LOCAL_GIT_MODES`] plus summaries.- ///- /// Spawn order: mode-major across previews, then summaries last —- /// each LLM call can take seconds. Called from outside any rayon- /// worker (the picker-collect bg thread), so submissions land on- /// rayon's FIFO injector and workers pick previews before summaries.- pub(super) fn spawn_deferred_precompute(+ /// Each LLM call can take seconds. Called from outside any rayon worker+ /// (the picker-collect bg thread), so submissions land on rayon's FIFO+ /// injector. Local-git subsidiary modes are served by the demand worker+ /// when selected instead of being computed for every unseen row.+ pub(super) fn spawn_deferred_summaries(&self,spawn_gen: &SpawnGeneration,rest: &[Arc<ListItem>],- preview_dims: (usize, usize),llm_command: Option<&str>,) {- for mode in LOCAL_GIT_MODES.into_iter().filter(|m| *m != INITIAL_MODE) {- for item in rest {- self.spawn_preview(spawn_gen, Arc::clone(item), mode, preview_dims);- }- }if let Some(llm) = llm_command {for item in rest {self.spawn_summary(spawn_gen, Arc::clone(item), llm.to_string());@@ -825,23 +821,34 @@ impl PreviewOrchestrator {}/// Preview-cache inventory for the dry-run dump: one sorted- /// `{branch, mode, bytes}` object per cached preview. Byte-length only- /// (not content) keeps output small and deterministic across terminals.+ /// `{branch, mode, bytes, content}` object per cached preview. Content is+ /// included because dry-run integration tests need to distinguish a real+ /// preview from an equally non-empty error pane; the dump is test-only.pub(super) fn cache_entries_json(&self) -> serde_json::Value {let mut entries: Vec<_> = self.cache.iter().map(|e| {let (branch, mode) = e.key();- (branch.clone(), *mode as u8, e.value().len())+ (+ branch.clone(),+ *mode as u8,+ e.value().len(),+ e.value().clone(),+ )}).collect();entries.sort();entries.into_iter()- .map(|(branch, mode, bytes)| {- serde_json::json!({ "branch": branch, "mode": mode, "bytes": bytes })+ .map(|(branch, mode, bytes, content)| {+ serde_json::json!({+ "branch": branch,+ "mode": mode,+ "bytes": bytes,+ "content": content,+ })}).collect()}@@ -1137,9 +1144,8 @@ mod tests {/// End-to-end demand path: a `preview()` cache miss on a local-git tab is/// computed by the demand worker and served — without any precompute- /// spawn touching the pool. Pins the fix for the "navigated-to tab waits- /// behind the whole precompute queue" latency: the placeholder used to- /// sit until the deferred tier happened to reach the key.+ /// spawn touching the pool. Pins that demand-loaded subsidiary panes do+ /// not depend on speculative bulk precompute.#[test]fn preview_miss_is_served_by_demand_worker() {use super::super::items::{LocalCheckout, LocalContent, PickerRow};@@ -1170,7 +1176,7 @@ mod tests {}),};- // The picker opens on WorkingTree — the process-global default tab,+ // The picker opens on UnifiedDiff — the process-global default tab,// which this test deliberately leaves untouched (other tests read// it). This render misses and posts the demand. No assertion on the// returned placeholder: the worker races the render's own cache read@@ -1190,7 +1196,7 @@ mod tests {// The demand worker fills the key with the real diff. Bounded poll so// a dead worker fails instead of hanging the suite.- let key = ("main".to_string(), PreviewMode::WorkingTree);+ let key = ("main".to_string(), PreviewMode::UnifiedDiff);let deadline = std::time::Instant::now() + Duration::from_secs(60);while !orch.cache.contains_key(&key) {assert!(@@ -1202,7 +1208,43 @@ mod tests {let served = orch.cache.get(&key).unwrap().clone();assert!(served.contains("README"),- "demand-computed working-tree diff served: {served:?}"+ "demand-computed complete diff served: {served:?}"+ );+ }++ #[test]+ fn initial_precompute_skips_offscreen_worktrees_but_warms_branches() {+ let (t, first) = dirty_worktree_item();+ let head = first.head().to_string();+ t.repo.run_command(&["branch", "branch-only"]).unwrap();++ let mut offscreen = ListItem::new_branch(head.clone(), "offscreen".to_string());+ offscreen.kind = ItemKind::Worktree(Box::new(WorktreeData {+ path: t.path().to_path_buf(),+ ..Default::default()+ }));+ let offscreen = Arc::new(offscreen);+ let branch = Arc::new(ListItem::new_branch(head, "branch-only".to_string()));++ let orch = orch_for(&t);+ orch.spawn_initial_precompute(+ &orch.generation(),+ &[first, Arc::clone(&offscreen), Arc::clone(&branch)],+ (80, 24),+ None,+ );+ orch.wait_for_idle();++ assert!(+ !orch+ .cache+ .contains_key(&("offscreen".to_string(), PreviewMode::UnifiedDiff)),+ "off-screen worktree should wait for selected-row demand"+ );+ assert!(+ orch.cache+ .contains_key(&("branch-only".to_string(), PreviewMode::UnifiedDiff)),+ "branch-only default should be prewarmed from the committed diff");}@@ -1531,6 +1573,7 @@ mod tests {assert!(e["branch"].is_string());assert!(e["mode"].is_number());assert!(e["bytes"].is_number());+ assert!(e["content"].is_string());}}}diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex 17ff7f1a3..19e994a32 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -20,17 +20,16 @@//! initialized). Intermediate updates coalesce to [`RENDER_THROTTLE`]; the//! terminal `on_collect_complete` forces one final unthrottled frame.//!-//! Preview pre-compute is staged in two tiers:-//! - `on_skeleton` fires the first item's 4 modes + first-item summary,-//! plus the default-tab mode for items 1..N (so quick j/k navigation-//! lands on warm content). It also fills the static Summary hint for-//! every row when summaries are disabled.-//! - `on_collect_complete` fires the secondary modes (Log / BranchDiff /-//! UpstreamDiff) and summaries for items 1..N once the row pipeline-//! has torn down. Preview tasks share `COLLECT_POOL` with the row-//! pipeline. Staging keeps low-priority preview submissions out of-//! that pool's injector while row tasks are still landing on-//! workers' local deques during drain.+//! Preview work is staged in two tiers:+//! - `on_skeleton` fires the first item's 5 modes + first-item summary,+//! plus the default-tab mode for branch-only items 1..N (their committed+//! diff is cheap from the SHA-keyed cache; off-screen worktree rows are+//! demand-loaded when selected). It also fills the static Summary hint+//! for every row when summaries are disabled.+//! - `on_collect_complete` fires configured summaries for items 1..N once+//! the row pipeline has torn down. Secondary local-git modes on those rows+//! are computed only when selected by the dedicated demand worker, avoiding+//! speculative worktree I/O for panes the user may never open.use std::collections::{HashMap, HashSet};use std::path::Path;@@ -310,7 +309,7 @@ impl PickerProgressHandler for PickerHandler {HashMap::with_capacity(items.len());// Synchronous skeleton-time tab-availability facts (see `TabAvailability`).- // Branches with an upstream tracking ref drive the tab-4 (remote⇅) empty+ // Branches with an upstream tracking ref drive the tab-5 (remote⇅) empty// state, read from the pre-skeleton `for-each-ref` inventory — never the// async `item.upstream`. A `local_branches()` failure yields the empty set// (every branch reads as no-upstream); preview rendering must not error.@@ -532,12 +531,10 @@ impl PickerProgressHandler for PickerHandler {shown_branches,});- // Tier 1: warm the user's landing row (all modes) and every- // other row's default tab. Tier 2 (secondary modes + summaries- // for items 1..N) fires from `on_collect_complete` after the row- // pipeline tears down — spawning that bulk now would queue ahead- // of row tasks in `COLLECT_POOL`'s injector while workers are still- // grinding through the row work.+ // Tier 1: warm the user's landing row (all modes) and the default tab+ // of branch-only rows. Configured summaries for items 1..N fire from+ // `on_collect_complete` after the row pipeline tears down. Secondary+ // local modes stay demand-loaded.self.orchestrator.spawn_initial_precompute(&self.spawn_gen,&list_items,@@ -666,10 +663,9 @@ impl PickerProgressHandler for PickerHandler {if items.len() <= 1 {return;}- self.orchestrator.spawn_deferred_precompute(+ self.orchestrator.spawn_deferred_summaries(&self.spawn_gen,&items[1..],- self.preview_dims,self.llm_command.as_deref(),);}@@ -1594,11 +1590,13 @@ mod tests {}/// Preview pre-compute is tiered. After `on_skeleton`:- /// - First item gets all 4 modes (the user's landing row).- /// - Items 1..N get only `WorkingTree` (the picker's initial tab) so- /// quick j/k navigation hits warm content.- /// - Secondary modes for items 1..N are deferred until- /// `on_collect_complete` fires.+ /// - First item gets all 5 modes (the user's landing row).+ /// - Branch-only items 1..N get only `UnifiedDiff` (the picker's initial+ /// tab) so quick j/k navigation hits warm content. Worktree-backed rows+ /// are demand-loaded instead; that split is pinned in+ /// `preview_orchestrator`, not here.+ /// - Secondary modes for items 1..N stay demand-loaded rather than+ /// consuming worktree I/O speculatively.////// Summary hint is filled for every item synchronously at skeleton/// time so the Summary tab is usable for any selection immediately.@@ -1630,11 +1628,12 @@ mod tests {);}- // First item: all 4 modes spawned at skeleton time.+ // First item: all 5 modes spawned at skeleton time.for mode in [+ PreviewMode::UnifiedDiff,PreviewMode::WorkingTree,- PreviewMode::Log,PreviewMode::BranchDiff,+ PreviewMode::Log,PreviewMode::UpstreamDiff,] {assert!(@@ -1643,26 +1642,27 @@ mod tests {);}- // Items 1..N: WorkingTree (default tab) cached at skeleton time.+ // Branch-only items 1..N: UnifiedDiff cached at skeleton time.for branch in ["beta", "gamma"] {assert!(handler.preview_cache- .contains_key(&(branch.into(), PreviewMode::WorkingTree)),- "{branch}.WorkingTree should be cached after on_skeleton (initial tier)"+ .contains_key(&(branch.into(), PreviewMode::UnifiedDiff)),+ "{branch}.UnifiedDiff should be cached after on_skeleton (initial tier)");}- // Items 1..N: secondary modes NOT yet spawned (deferred tier).+ // Items 1..N: secondary modes are not spawned speculatively.for branch in ["beta", "gamma"] {for mode in [+ PreviewMode::WorkingTree,PreviewMode::Log,PreviewMode::BranchDiff,PreviewMode::UpstreamDiff,] {assert!(!handler.preview_cache.contains_key(&(branch.into(), mode)),- "{branch}.{mode:?} should NOT be cached before on_collect_complete"+ "{branch}.{mode:?} should remain demand-loaded");}}@@ -1670,8 +1670,9 @@ mod tests {handler.on_collect_complete();handler.orchestrator.wait_for_idle();- // After on_collect_complete, every item × every preview mode is cached.- for branch in ["alpha", "beta", "gamma"] {+ // Collection completion must not bulk-compute subsidiary local modes.+ // (Configured summaries use this hook, but this fixture has them off.)+ for branch in ["beta", "gamma"] {for mode in [PreviewMode::WorkingTree,PreviewMode::Log,@@ -1679,8 +1680,8 @@ mod tests {PreviewMode::UpstreamDiff,] {assert!(- handler.preview_cache.contains_key(&(branch.into(), mode)),- "{branch}.{mode:?} should be cached after on_collect_complete"+ !handler.preview_cache.contains_key(&(branch.into(), mode)),+ "{branch}.{mode:?} should remain demand-loaded after collection");}}@@ -1705,8 +1706,8 @@ mod tests {"no work should be spawned when on_skeleton never fired");- // Case 2: single-item skeleton — first-item phase covered the 4- // modes plus the static Summary hint (5 entries total). Nothing+ // Case 2: single-item skeleton — first-item phase covered the 5+ // modes plus the static Summary hint (6 entries total). Nothing// left to defer; on_collect_complete must not add any entries.let (handler, _test, _rx) = make_handler();let items = vec![ListItem::new_branch("aaa".into(), "solo".into())];@@ -1714,6 +1715,7 @@ mod tests {handler.orchestrator.wait_for_idle();let before = handler.preview_cache.iter().count();for mode in [+ PreviewMode::UnifiedDiff,PreviewMode::WorkingTree,PreviewMode::Log,PreviewMode::BranchDiff,@@ -1725,7 +1727,7 @@ mod tests {"first-item phase should have cached {mode:?}");}- assert_eq!(before, 5, "first-item phase populates exactly 5 entries");+ assert_eq!(before, 6, "first-item phase populates exactly 6 entries");handler.on_collect_complete();handler.orchestrator.wait_for_idle();diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex 6575ec04e..4981db415 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -852,15 +852,15 @@ fn gitlab_mr_status(}}-/// The pane for the tabs a `--prs` row leaves empty — working-tree (1),-/// branch-diff (3), upstream (4), summary (5). The head branch isn't checked+/// The pane for the tabs a `--prs` row leaves empty — complete diff (1),+/// working-tree (2), branch-diff (3), upstream (5), summary (6). The head branch isn't checked/// out locally, so there's no working tree or diff to show; point the user at-/// the `pr` tab, which holds the PR/MR metadata. The `log` tab (2) is *not*+/// the `pr` tab, which holds the PR/MR metadata. The `log` tab (4) is *not*/// empty — it loads commits in the background (see [`compute_pr_log`]).pub(super) fn pr_row_empty_placeholder() -> String {let reset = Reset;cformat!(- "{INFO_SYMBOL}{reset} Not checked out locally — press <bold>alt-6</>{reset} for PR details, Enter to fetch & switch\n"+ "{INFO_SYMBOL}{reset} Not checked out locally — press <bold>alt-7</>{reset} for PR details, Enter to fetch & switch\n")}@@ -1974,18 +1974,18 @@ mod tests {}#[test]- fn preview_renders_tabs_and_placeholder_off_the_pr_tab() {- // No tab switch happens here, so the in-memory `read_mode()` is its- // default (WorkingTree) — empty on a --prs row — so `preview()` renders- // the shared tab bar plus the "not checked out" placeholder. Drives the- // real `SkimItem::preview` (the `--prs` streaming path is too async to- // exercise it reliably under a PTY). `context.width` (80) is wide enough- // for the full tab bar, so the `pr` / `comments` tabs show their labels.+ fn preview_defaults_to_pr_tab_for_forge_only_row() {+ // Before an explicit tab choice, a `--prs` row opens on its PR details+ // rather than an empty local-diff placeholder. Drives the real+ // `SkimItem::preview` (the `--prs` streaming path is too async to+ // exercise it reliably under a PTY).+ let _state =+ super::super::preview::PreviewState::new(super::super::preview::PreviewLayout::Right);let pr = pr_item(entry(RefType::Pr, 7, "Title"), 120, Some(&grid()));let ctx = PreviewContext {query: "",cmd_query: "",- width: 80,+ width: 120,height: 24,current_index: 0,current_selection: "",@@ -1998,11 +1998,11 @@ mod tests {// Assert on the ANSI-stripped bar so the check targets the tab labels// themselves, not a coincidental substring of the styled controls line.let bar = plain(&text);- assert!(bar.contains("6: pr"), "pr tab present: {bar:?}");- assert!(bar.contains("7: comments"), "comments tab present: {bar:?}");+ assert!(bar.contains("7: pr"), "pr tab present: {bar:?}");+ assert!(bar.contains("8: comments"), "comments tab present: {bar:?}");assert!(- text.contains("Not checked out locally"),- "placeholder present: {text:?}"+ text.contains("Title") && !text.contains("Not checked out locally"),+ "PR details are the automatic pane: {text:?}");}@@ -2010,7 +2010,7 @@ mod tests {fn log_tab_reads_cache_then_placeholder() {// The deferred `log` tab reads the shared cache keyed by the row's// output token. A miss shows the loading placeholder (pointing at- // alt-2); once the background fetch lands a value under that key, the+ // alt-4); once the background fetch lands a value under that key, the// pane shows it.let cache: PreviewCache = Arc::new(DashMap::new());let pr = pr_item_with_cache(entry(RefType::Pr, 42, "t"), 120, None, Arc::clone(&cache));@@ -2163,7 +2163,7 @@ mod tests {fn comments_tab_reads_cache_then_placeholder() {// Like the log tab, the deferred `comments` tab reads the shared cache// keyed by the row's output token, with a loading placeholder (pointing- // at alt-7) on a miss.+ // at alt-8) on a miss.let cache: PreviewCache = Arc::new(DashMap::new());let pr = pr_item_with_cache(entry(RefType::Mr, 7, "t"), 120, None, Arc::clone(&cache));diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snapindex c0488710c..7804b380b 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [1mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [1mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snapindex 2414ee0e0..d069d9080 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(CONTENT_EMPTY, true, false, false), WIDE,)"----[2m1:[22m [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | [2m3:[22m [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+[2m1:[22m [2mdiff[22m[0m | [2m2:[22m [1mworking[22m[0m | [2m3:[22m [2mcommitted[22m[0m | 4: [2mlog[22m[0m | [2m5:[22m [2mremote⇅[22m[0m | [2m6:[22m [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snapindex f3387fbe9..3077e7038 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(LocalContent::default(), false, false, false),\nWIDE,)"----1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [1mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | [2m5:[22m [2mremote⇅[22m[0m | [2m6:[22m [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_unified_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_unified_diff.snapnew file mode 100644index 000000000..967aaa98f--- /dev/null+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_unified_diff.snap@@ -0,0 +1,5 @@+---+source: src/commands/picker/items.rs+expression: "PickerRow::loading_placeholder(mode)"+---+[2m↳[22m [2mLoading complete diff…[22mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snapindex da038fde6..032b1b035 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [1mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [1mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snapindex 4cee80307..38c8e52ee 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [1mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [1mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snapindex 078c7d54f..efc1387b4 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), WIDE)"----[2m1:[22m [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | [2m3:[22m [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | 6: [1mpr[22m[0m | 7: [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+[2m1:[22m [2mdiff[22m[0m | [2m2:[22m [2mworking[22m[0m | [2m3:[22m [2mcommitted[22m[0m | 4: [2mlog[22m[0m | [2m5:[22m [2mremote⇅[22m[0m | [2m6:[22m [2msummary[22m[0m | 7: [1mpr[22m[0m | 8: [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snapindex ec06e5597..33c6871bc 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [1msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [1msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__unified_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__unified_diff.snapnew file mode 100644index 000000000..6b1b94093--- /dev/null+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__unified_diff.snap@@ -0,0 +1,6 @@+---+source: src/commands/picker/items.rs+expression: "render_preview_tabs(mode, wt, WIDE)"+---+1: [1mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snapindex 29453e7d3..566e9a4d7 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [1mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [2mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [1mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snapindex a2f2004d4..b4d6a46a3 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap@@ -2,5 +2,5 @@source: src/commands/picker/items.rsexpression: "render_preview_tabs(mode, wt, WIDE)"----1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m-[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0m+1: [2mdiff[22m[0m | 2: [1mworking[22m[0m | 3: [2mcommitted[22m[0m | 4: [2mlog[22m[0m | 5: [2mremote⇅[22m[0m | 6: [2msummary[22m[0m | [2m7:[22m [2mpr[22m[0m | [2m8:[22m [2mcomments[22m[0m+[36m[2mEnter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | alt-c: create | alt-x: remove | alt-y: copy | alt-o: open | alt-r: refresh | alt-p: toggle | Esc: cancel[39m[22m[0mdiff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex 7e7d132d2..4389015c8 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -1,12 +1,11 @@//! `wt step commit` — commit working tree changes.-use std::fs;+use std::path::Path;use anyhow::Context;use worktrunk::HookType;use worktrunk::config::UserConfig;-use worktrunk::git::Repository;-use worktrunk::shell_exec::Cmd;+use worktrunk::git::{Repository, TempIndex};use worktrunk::styling::println;use super::super::command_approval::{approve_or_skip, resolve_template_for_preview};@@ -92,7 +91,7 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:} else {None};- let index_override = temp_index.as_deref();+ let index_override = temp_index.as_ref().map(|temp| Path::new(temp.path()));let ctx = env.context(yes);let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;@@ -111,29 +110,14 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:print_dry_run(&prompt, &commit_config, &message)}-/// Copy the current worktree's index to a temp file and run `git <add_args>` against it.+/// Stage into the worktree's shared temporary-index abstraction.///-/// Returns the [`tempfile::TempPath`] so the caller controls its lifetime — when-/// dropped, the temp file is removed without ever touching the user's real index.-fn stage_to_temp_index(repo: &Repository, add_args: &[&str]) -> anyhow::Result<tempfile::TempPath> {- let wt = repo.current_worktree();- let real_index = wt.git_dir()?.join("index");- // Close the freshly-created 0-byte tempfile's handle (Windows leaves- // the name delete-pending if it's still open) and clear the file; if a- // real index exists, copy it back, otherwise let `git add` create a- // fresh index at the reserved path. Mirrors `WorkingTree::temp_index`.- let temp = tempfile::NamedTempFile::new()- .context("Failed to create temporary index")?- .into_temp_path();- fs::remove_file(&temp).context("Failed to clear temporary index")?;- if real_index.exists() {- fs::copy(&real_index, &temp).context("Failed to copy index file")?;- }-- let output = Cmd::new("git")- .args(add_args.iter().copied())- .current_dir(wt.root()?)- .env("GIT_INDEX_FILE", &temp)+/// Returning [`TempIndex`] keeps the copied index alive while the caller builds+/// the prompt, then removes it on drop without touching the user's real index.+fn stage_to_temp_index(repo: &Repository, add_args: &[&str]) -> anyhow::Result<TempIndex> {+ let temp = repo.current_worktree().temp_index()?;+ let output = temp+ .git(add_args.iter().copied()).run().context("Failed to stage changes into temp index")?;if !output.status.success() {@@ -156,7 +140,10 @@ mod tests {let test = TestRepo::with_initial_commit();let repo = Repository::at(test.root_path()).unwrap();- let err = super::stage_to_temp_index(&repo, &["add", "--", ":(bad"]).unwrap_err();+ let err = match super::stage_to_temp_index(&repo, &["add", "--", ":(bad"]) {+ Ok(_) => panic!("invalid pathspec should fail"),+ Err(err) => err,+ };let cmd_err = CommandError::find_in(&err).expect("error should carry a CommandError");assert_eq!(cmd_err.command_string(), "git add -- :(bad");}diff --git a/src/commands/step/diff.rs b/src/commands/step/diff.rsindex 0d6cec13c..580e1d6c6 100644--- a/src/commands/step/diff.rs+++ b/src/commands/step/diff.rs@@ -7,8 +7,9 @@ use worktrunk::git::Repository;////// Shows all changes since branching from the target: committed, staged, unstaged,/// and untracked files in a single diff. Stages untracked files into a temp index-/// (`WorkingTree::temp_index`) so they appear in the diff without mutating the-/// real index — git's stat cache stays warm and tracked files aren't re-hashed.+/// (`WorkingTree::prepare_diff_with_untracked`) so they appear in the diff+/// without mutating the real index — git's stat cache stays warm and tracked+/// files aren't re-hashed.////// `branch` selects which worktree to diff: when `Some`, the repo is rooted at/// that branch's worktree so the diff (and its target resolution) operate there@@ -30,15 +31,9 @@ pub fn step_diff(.merge_base("HEAD", &integration_target)?.context("No common ancestor with target branch")?;- let idx = wt.temp_index()?;- idx.git(["add", "--intent-to-add", "."])- .run()- .context("Failed to register untracked files")?;-// Stream diff to stdout — git handles pager and coloring.- let mut diff_args = vec!["diff".to_string(), merge_base];- diff_args.extend_from_slice(extra_args);- idx.git(diff_args).stream()?;+ wt.prepare_diff_with_untracked([merge_base])?+ .stream(extra_args)?;Ok(())}diff --git a/src/git/mod.rs b/src/git/mod.rsindex 46bac6114..36df8cd9b 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -80,7 +80,7 @@ pub use remove::{pub use repository::sha_cache;pub use repository::{Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,- RefSnapshot, Repository, ResolvedWorktree, Selector, TempIndex, WorkingTree,+ PreparedDiff, RefSnapshot, Repository, ResolvedWorktree, Selector, TempIndex, WorkingTree,duplicated_branches, is_valid_branch_name, normalize_selector, resolve_input_path,select_comparison_base, set_base_path,};diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex c170afb08..7d14316ab 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -1,12 +1,166 @@//! Diff, history, and commit operations for Repository.use std::collections::HashMap;+use std::path::PathBuf;use anyhow::{Context, bail};use dashmap::mapref::entry::Entry;+use crate::git::CommandError;+use crate::shell_exec::Cmd;++use super::working_tree::{TempIndex, WorkingTree, path_to_logging_context};use super::{DiffStats, LineDiff, Repository};+enum DiffSource<'repo> {+ Repository {+ repo: &'repo Repository,+ path: PathBuf,+ },+ TempIndex(TempIndex),+}++/// A fully specified `git diff` whose execution can be captured or streamed.+///+/// The source owns a temporary index when untracked files must participate in+/// the diff. Keeping that index alive in this value makes multi-command reads+/// such as a stat followed by a patch observe the same prepared worktree state.+#[must_use]+pub struct PreparedDiff<'repo> {+ source: DiffSource<'repo>,+ revisions: Vec<String>,+}++impl<'repo> PreparedDiff<'repo> {+ fn new(+ repo: &'repo Repository,+ path: PathBuf,+ revisions: impl IntoIterator<Item = impl Into<String>>,+ ) -> Self {+ Self {+ source: DiffSource::Repository { repo, path },+ revisions: revisions.into_iter().map(Into::into).collect(),+ }+ }++ fn with_temp_index(+ index: TempIndex,+ revisions: impl IntoIterator<Item = impl Into<String>>,+ ) -> Self {+ Self {+ source: DiffSource::TempIndex(index),+ revisions: revisions.into_iter().map(Into::into).collect(),+ }+ }++ fn command(&self, args: &[String]) -> Cmd {+ match &self.source {+ DiffSource::Repository { repo, path } => repo.with_object_store_env(+ Cmd::new("git")+ .args(args.iter().cloned())+ .current_dir(path)+ .context(path_to_logging_context(path)),+ ),+ DiffSource::TempIndex(index) => index.git(args.iter().cloned()),+ }+ }++ fn run(&self, args: &[String]) -> anyhow::Result<String> {+ let output = self+ .command(args)+ .run()+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;+ if !output.status.success() {+ return Err(CommandError::from_failed_output("git", args, &output).into());+ }+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())+ }++ /// Capture one diff invocation with `options` placed before the revisions.+ ///+ /// Revisions are fenced with `--end-of-options`, so even a ref beginning+ /// with `-` is treated as a positional argument.+ pub fn capture(+ &self,+ options: impl IntoIterator<Item = impl Into<String>>,+ ) -> anyhow::Result<String> {+ self.capture_with_git_options(std::iter::empty::<String>(), options)+ }++ /// Capture one diff invocation with git-wide options placed before the+ /// `diff` subcommand and diff options placed after it.+ pub fn capture_with_git_options(+ &self,+ git_options: impl IntoIterator<Item = impl Into<String>>,+ diff_options: impl IntoIterator<Item = impl Into<String>>,+ ) -> anyhow::Result<String> {+ let mut args = vec!["--no-optional-locks".to_string()];+ args.extend(git_options.into_iter().map(Into::into));+ args.push("diff".to_string());+ args.extend(diff_options.into_iter().map(Into::into));+ args.push("--end-of-options".to_string());+ args.extend(self.revisions.iter().cloned());+ self.run(&args)+ }++ /// Capture a stat header followed by the colored patch.+ ///+ /// Returns `None` when the stat is empty, avoiding the second git command.+ pub fn capture_stat_and_patch(&self, width: usize) -> anyhow::Result<Option<String>> {+ let stat = self.capture([+ "--stat".to_string(),+ "--color=always".to_string(),+ format!("--stat-width={width}"),+ ])?;+ if stat.trim().is_empty() {+ return Ok(None);+ }++ let patch = self.capture(["--color=always"])?;+ Ok(Some(format!("{stat}{patch}")))+ }++ /// Stream the diff, preserving `wt step diff`'s argument order so git owns+ /// paging, coloring, and interpretation of caller-supplied arguments.+ pub fn stream(&self, extra_args: &[String]) -> anyhow::Result<()> {+ let mut args = vec!["diff".to_string()];+ args.extend(self.revisions.iter().cloned());+ args.extend_from_slice(extra_args);+ self.command(&args).stream()+ }+}++impl Repository {+ /// Prepare an immutable revision diff in this repository's context.+ pub fn prepare_diff(+ &self,+ revisions: impl IntoIterator<Item = impl Into<String>>,+ ) -> PreparedDiff<'_> {+ PreparedDiff::new(self, self.discovery_path().to_path_buf(), revisions)+ }+}++impl<'repo> WorkingTree<'repo> {+ /// Prepare a diff against this worktree's tracked index and files.+ pub fn prepare_diff(+ &self,+ revisions: impl IntoIterator<Item = impl Into<String>>,+ ) -> PreparedDiff<'repo> {+ PreparedDiff::new(self.repo, self.path.clone(), revisions)+ }++ /// Prepare a diff that also includes untracked files without changing the+ /// real index.+ pub fn prepare_diff_with_untracked(+ &self,+ revisions: impl IntoIterator<Item = impl Into<String>>,+ ) -> anyhow::Result<PreparedDiff<'repo>> {+ let index = self.temp_index()?;+ index.register_untracked()?;+ Ok(PreparedDiff::with_temp_index(index, revisions))+ }+}+/// Subject and body for one commit in a range.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct CommitMessageDetail {diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 3bce7c92d..b231240e7 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -76,6 +76,12 @@ pub struct BranchDiffSpec {/// options: a single three-dot range `["{base}...{head}"]` normally, or/// `["{empty-tree}", "{head}"]` for an orphan.pub revs: Vec<String>,+ /// Single tree-ish to compare with the worktree when rendering a unified+ /// committed + uncommitted diff: the merge-base SHA normally, or the empty+ /// tree for an orphan. `None` only when merge-base resolution failed; unlike+ /// the committed-only three-dot diff, a worktree diff has no correct range+ /// fallback in that case.+ pub working_base: Option<String>,/// Display name of the comparison base, for "no file changes vs X".pub base_name: String,/// Stable SHA identifying the base for disk-cache keying: the base's commit@@ -646,17 +652,27 @@ impl Repository {// merge-base *error* (invalid/unreachable object) is NOT an orphan —// fall through to the normal three-dot range and let the diff surface// the failure rather than dumping the whole tree as "the branch".- let (revs, cache_sha) = if matches!(self.merge_base_by_sha(base_sha, head), Ok(None)) {- (+ let (revs, working_base, cache_sha) = match self.merge_base_by_sha(base_sha, head) {+ Ok(None) => (vec![EMPTY_TREE_SHA.to_string(), head.to_string()],+ Some(EMPTY_TREE_SHA.to_string()),EMPTY_TREE_SHA.to_string(),- )- } else {- (vec![format!("{base_sha}...{head}")], base_sha.to_string())+ ),+ Ok(Some(merge_base)) => (+ vec![format!("{base_sha}...{head}")],+ Some(merge_base),+ base_sha.to_string(),+ ),+ Err(_) => (+ vec![format!("{base_sha}...{head}")],+ None,+ base_sha.to_string(),+ ),};Some(BranchDiffSpec {revs,+ working_base,base_name: base.name.clone(),cache_sha,})diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 9e002e9e0..0c8b3ddd2 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -162,7 +162,7 @@ mod worktrees;// Re-export WorkingTree, Branch, IntegrationTargets, and RefSnapshotpub use branch::Branch;pub use branch::is_valid_branch_name;-pub use diff::CommitMessageDetail;+pub use diff::{CommitMessageDetail, PreparedDiff};pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base};pub use ref_snapshot::RefSnapshot;pub(super) use working_tree::path_to_logging_context;diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 8d4e6bf88..beeda5d10 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};use anyhow::Context;use dashmap::mapref::entry::Entry;+use path_slash::PathExt;use crate::path::canonicalize_with_parents;use crate::shell_exec::Cmd;@@ -13,6 +14,20 @@ use super::{GitError, LineDiff, Repository};use crate::git::CommandError;use crate::git::parse_numstat_line;+const TEMP_INDEX_PREFIX: &str = "worktrunk-temp-index-";++/// Quote a path component for Git's `glob` pathspec magic. The caller adds+/// the one intentional wildcard after the escaped literal.+fn escape_pathspec_glob_literal(path: &str) -> String {+ path.chars().fold(String::new(), |mut escaped, ch| {+ if matches!(ch, '\\' | '*' | '?' | '[' | ']') {+ escaped.push('\\');+ }+ escaped.push(ch);+ escaped+ })+}+/// Parse `git submodule status` output and detect whether any submodule is initialized.////// Status lines start with a one-character state marker:@@ -386,12 +401,19 @@ impl<'a> WorkingTree<'a> {/// each want porcelain (e.g., working-tree diff + conflict detection during/// `wt list`) share a single subprocess. Uses `--no-optional-locks` to avoid/// index-lock contention with the `git write-tree` run by- /// `WorkingTreeConflictsTask` in parallel.+ /// `WorkingTreeConflictsTask` in parallel. Explicitly requests normal+ /// untracked-file reporting so `status.showUntrackedFiles=no` cannot make+ /// an untracked-only worktree look clean to callers.pub fn status_porcelain_cached(&self) -> anyhow::Result<String> {match self.repo.cache.status_porcelain.entry(self.path.clone()) {Entry::Occupied(e) => Ok(e.get().clone()),Entry::Vacant(e) => {- let stdout = self.run_command(&["--no-optional-locks", "status", "--porcelain"])?;+ let stdout = self.run_command(&[+ "--no-optional-locks",+ "status",+ "--porcelain",+ "--untracked-files=normal",+ ])?;Ok(e.insert(stdout).clone())}}@@ -763,18 +785,19 @@ impl<'a> WorkingTree<'a> {}let idx = self.temp_index()?;+ let add_args = [+ "add",+ "--sparse",+ "--pathspec-from-file=-",+ "--pathspec-file-nul",+ ];let add_output = idx- .git(["add", "--pathspec-from-file=-", "--pathspec-file-nul"])+ .git(add_args).stdin_bytes(output.stdout).run().context("Failed to stage untracked files")?;if !add_output.status.success() {- return Err(CommandError::from_failed_output(- "git",- &["add", "--pathspec-from-file=-", "--pathspec-file-nul"],- &add_output,- )- .into());+ return Err(CommandError::from_failed_output("git", &add_args, &add_output).into());}let mut args = vec![@@ -812,19 +835,29 @@ impl<'a> WorkingTree<'a> {let real_index = git_dir.join("index");let log_ctx = path_to_logging_context(self.path());- // A missing `<gitdir>/index` is semantically an empty index (nothing- // staged), so mirror git's own behaviour. Close the- // freshly-created 0-byte tempfile's handle (Windows leaves the name- // delete-pending if it's still open) and remove the file; if a real- // index exists, copy it back, otherwise leave the path empty and- // let the first `git` call against `GIT_INDEX_FILE` create a fresh- // valid index there.- let temp = tempfile::NamedTempFile::new()- .context("Failed to create temporary index")?- .into_temp_path();- std::fs::remove_file(&temp).context("Failed to clear temporary index")?;- if real_index.exists() {- std::fs::copy(&real_index, &temp).context("Failed to copy index file")?;+ // Keep the exclusively-created file open while copying a real index;+ // removing it first would expose its random name to a symlink race in+ // a shared system temp directory. A missing `<gitdir>/index` is+ // semantically an empty index (nothing staged), so only that case+ // closes and removes the 0-byte file before Git creates a valid index.+ let mut temp_file = tempfile::Builder::new()+ .prefix(TEMP_INDEX_PREFIX)+ .tempfile()+ .context("Failed to create temporary index")?;+ let mut real_index_file = match std::fs::File::open(&real_index) {+ Ok(file) => Some(file),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => return Err(error).context("Failed to open index file"),+ };+ if let Some(real_index_file) = &mut real_index_file {+ std::io::copy(real_index_file, temp_file.as_file_mut())+ .context("Failed to copy index file")?;+ }+ let temp = temp_file.into_temp_path();+ if real_index_file.is_none() {+ // `into_temp_path` closes the handle first, which matters on+ // Windows: deleting a still-open file leaves the name pending.+ std::fs::remove_file(&temp).context("Failed to clear temporary index")?;}// Validate UTF-8 once so `TempIndex::path` is infallible.temp.to_str()@@ -939,8 +972,9 @@ impl<'a> WorkingTree<'a> {/// [`WorkingTree::working_tree_diff_stats_with_untracked`] (HEAD± with/// untracked, used by `wt list --full` / `wt statusline`),/// `WorkingTreeConflictsTask` (write-tree of dirty + untracked, for-/// merge-conflict probing), and `wt step diff` (diff vs target merge-base-/// with untracked).+/// merge-conflict probing), `wt step diff` (diff vs target merge-base with+/// untracked), `wt step commit --dry-run` (mirror its `--stage` mode without+/// changing the user's index), and the `wt switch` unified/working preview tabs.pub struct TempIndex {temp: tempfile::TempPath,worktree_root: PathBuf,@@ -957,6 +991,48 @@ impl TempIndex {self.temp.to_str().expect("validated in temp_index()")}+ /// Register untracked files in the temporary index without adding their+ /// contents. A following `git diff <base>` can then include those files as+ /// new while preserving the user's real index and staging state. If the+ /// system temp directory is inside the worktree, the pathspec excludes all+ /// files in that directory with Worktrunk's dedicated prefix so concurrent+ /// temporary indexes cannot enter each other's diffs. Keeping the random+ /// files directly in the OS temp directory avoids a predictable shared+ /// parent on multi-user systems.+ pub(super) fn register_untracked(&self) -> anyhow::Result<()> {+ let mut args = vec![+ "add".to_string(),+ "--intent-to-add".to_string(),+ // An untracked file may sit outside a sparse-checkout definition.+ // Without --sparse git refuses the entire add, hiding both that+ // file and otherwise-valid worktree changes from the preview.+ "--sparse".to_string(),+ "--".to_string(),+ ".".to_string(),+ ];+ let temp_dir = canonicalize_with_parents(+ self.temp+ .parent()+ .context("Temporary index has no parent directory")?,+ );+ let worktree_root = canonicalize_with_parents(&self.worktree_root);+ if let Ok(relative) = temp_dir.strip_prefix(&worktree_root) {+ let relative = escape_pathspec_glob_literal(&relative.to_slash_lossy());+ let separator = if relative.is_empty() { "" } else { "/" };+ args.push(format!(+ ":(top,exclude,glob){relative}{separator}{TEMP_INDEX_PREFIX}*"+ ));+ }+ let output = self+ .git(&args)+ .run()+ .context("Failed to register untracked files")?;+ if !output.status.success() {+ return Err(CommandError::from_failed_output("git", &args, &output).into());+ }+ Ok(())+ }+/// Build a `git` command pointed at this temp index.////// Wires `current_dir` to the worktree root, the worktree's logging@@ -1052,6 +1128,21 @@ mod tests {assert_ne!(before, after, "head_sha must reflect the new commit");}+ #[test]+ fn cached_porcelain_reports_untracked_files_hidden_by_user_config() {+ let test = TestRepo::with_initial_commit();+ test.run_git(&["config", "status.showUntrackedFiles", "no"]);+ std::fs::write(test.root_path().join("hidden-by-config.txt"), "loose\n").unwrap();++ let repo = Repository::at(test.root_path()).unwrap();+ let status = repo.current_worktree().status_porcelain_cached().unwrap();++ assert!(+ status.contains("?? hidden-by-config.txt"),+ "the shared status snapshot must override status.showUntrackedFiles=no: {status:?}"+ );+ }+#[test]fn prewarm_info_second_call_returns_cached_snapshot() {// Once `worktree_roots` is primed, subsequent `prewarm_info` calls@@ -1210,6 +1301,27 @@ mod tests {);}+ #[test]+ fn untracked_diff_stats_crosses_sparse_checkout_boundary() {+ let test = TestRepo::with_initial_commit();+ std::fs::create_dir_all(test.root_path().join("visible")).unwrap();+ std::fs::create_dir_all(test.root_path().join("hidden")).unwrap();+ std::fs::write(test.root_path().join("visible/tracked.txt"), "base\n").unwrap();+ std::fs::write(test.root_path().join("hidden/tracked.txt"), "base\n").unwrap();+ test.run_git(&["add", "visible/tracked.txt", "hidden/tracked.txt"]);+ test.run_git(&["commit", "-m", "add sparse fixture"]);+ test.run_git(&["sparse-checkout", "init", "--cone"]);+ test.run_git(&["sparse-checkout", "set", "visible"]);++ std::fs::create_dir_all(test.root_path().join("hidden")).unwrap();+ std::fs::write(test.root_path().join("hidden/loose.txt"), "loose\n").unwrap();++ let repo = Repository::at(test.root_path()).unwrap();+ let stats = repo.current_worktree().untracked_diff_stats().unwrap();+ assert_eq!(stats.added, 1);+ assert_eq!(stats.deleted, 0);+ }+#[test]fn untracked_diff_stats_unborn_head_is_command_error() {// With an unborn HEAD the untracked files stage fine into the tempdiff --git a/src/summary.rs b/src/summary.rsindex b856171b5..cfa4f0448 100644--- a/src/summary.rs+++ b/src/summary.rs@@ -242,13 +242,11 @@ pub(crate) fn compute_combined_diff(// stat and full-diff invocations differ only by the `--stat` flag.// The prefix overrides keep the diff parseable into per-file sections// by `prepare_diff` (same guard as `build_commit_prompt`).+ let prepared = repo.prepare_diff(spec.revs.iter().cloned());let run_branch_diff = |opts: &[&str], out: &mut String| {- let mut args = DIFF_PREFIX_OVERRIDES.to_vec();- args.push("diff");- args.extend_from_slice(opts);- args.push("--end-of-options");- args.extend(spec.revs.iter().map(String::as_str));- if let Ok(text) = repo.run_command(&args) {+ if let Ok(text) =+ prepared.capture_with_git_options(DIFF_PREFIX_OVERRIDES, opts.iter().copied())+ {out.push_str(&text);}};@@ -258,16 +256,14 @@ pub(crate) fn compute_combined_diff(// Working tree diff: uncommitted changesif let Some(wt_path) = worktree_path {- let path = wt_path.display().to_string();- if let Ok(wt_stat) = repo.run_command(&["-C", &path, "diff", "HEAD", "--stat"])+ let prepared = repo.worktree_at(wt_path).prepare_diff(["HEAD"]);+ if let Ok(wt_stat) = prepared.capture(["--stat"])&& !wt_stat.trim().is_empty(){stat.push_str(&wt_stat);}- let mut wt_diff_args = vec!["-C", &path];- wt_diff_args.extend(DIFF_PREFIX_OVERRIDES);- wt_diff_args.extend(["diff", "HEAD"]);- if let Ok(wt_diff) = repo.run_command(&wt_diff_args)+ if let Ok(wt_diff) =+ prepared.capture_with_git_options(DIFF_PREFIX_OVERRIDES, std::iter::empty::<&str>())&& !wt_diff.trim().is_empty(){diff.push_str(&wt_diff);diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex cb4576a1f..7c06b6621 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -2655,7 +2655,7 @@ fn test_switch_prs_dry_run_github(repo: TestRepo) {/// PR row streams in, `spawn_pr_previews` kicks off `gh pr view <n> --json/// commits` on `COLLECT_POOL`, keyed by the row's `pr:{N}` token. The dry-run/// path joins that work and dumps the preview cache, so a `{branch:"pr:42",-/// mode:2}` (Log) entry with non-empty bytes proves the whole mechanism end to+/// mode:4}` (Log) entry with non-empty bytes proves the whole mechanism end to/// end: `spawn_compute` → `compute_pr_log` → `parse_github_commits` → cache.////// `headRefOid` here is a SHA that isn't in the test repo's object store, so@@ -2695,10 +2695,10 @@ fn test_switch_prs_dry_run_github_log_tab(repo: TestRepo) {let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");let entries = parsed["entries"].as_array().expect("entries array");- // Mode 2 is Log (see `PreviewMode`); the row keys its cache by `pr:42`.+ // Mode 4 is Log (see `PreviewMode`); the row keys its cache by `pr:42`.let log_entry = entries.iter()- .find(|e| e["branch"] == "pr:42" && e["mode"] == 2)+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 4).unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));assert!(log_entry["bytes"].as_u64().unwrap_or(0) > 0,@@ -2757,7 +2757,7 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {let entries = parsed["entries"].as_array().expect("entries array");let log_entry = entries.iter()- .find(|e| e["branch"] == "pr:42" && e["mode"] == 2)+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 4).unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));assert!(log_entry["bytes"].as_u64().unwrap_or(0) > 0,@@ -2766,12 +2766,12 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {// The comments tab has no local path, so its forge fetch failed (pr view →// exit 1); the closure caches a terminal "couldn't load" pane rather than- // leaving the slot empty. Mode 7 is Comments. A non-empty entry here can only+ // leaving the slot empty. Mode 8 is Comments. A non-empty entry here can only// be that failure pane — a successful comments fetch is impossible with// `pr view` rigged to exit 1.let comments_entry = entries.iter()- .find(|e| e["branch"] == "pr:42" && e["mode"] == 7)+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 8).unwrap_or_else(|| {panic!("failed comments fetch must cache a couldn't-load pane:\n{stdout}")});@@ -2786,7 +2786,7 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {/// strand the tab on its loading spinner for the session — there's no in-session/// retry). Here the PR carries no `headRefOid`, so the `log` tab can't take the/// local fast path and must hit the forge API, and `gh pr view` is rigged to-/// exit 1 — so both the `log` (mode 2) and `comments` (mode 7) cache entries are+/// exit 1 — so both the `log` (mode 4) and `comments` (mode 8) cache entries are/// present and non-empty, each the couldn't-load pane.#[rstest]fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {@@ -2822,8 +2822,8 @@ fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");let entries = parsed["entries"].as_array().expect("entries array");// Both deferred tabs cached a terminal couldn't-load pane (non-empty), never- // an empty slot. Modes: 2 = Log, 7 = Comments.- for (mode, tab) in [(2, "log"), (7, "comments")] {+ // an empty slot. Modes: 4 = Log, 8 = Comments.+ for (mode, tab) in [(4, "log"), (8, "comments")] {let entry = entries.iter().find(|e| e["branch"] == "pr:42" && e["mode"] == mode)@@ -2835,10 +2835,10 @@ fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {}}-/// The `comments` tab (7) loads the PR discussion in the background, the same+/// The `comments` tab (8) loads the PR discussion in the background, the same/// way the `log` tab loads commits: `spawn_pr_previews` fires `gh pr view <n>/// --json comments` keyed by the row's `pr:{N}` token. A `{branch:"pr:42",-/// mode:7}` entry in the dry-run cache dump proves `compute_pr_comments` →+/// mode:8}` entry in the dry-run cache dump proves `compute_pr_comments` →/// `render_github_comments` → cache ran end to end. (`gh pr view --json/// commits` and `--json comments` both match the mock's `pr view` key, so the/// canned response carries both arrays; serde ignores the one each renderer@@ -2875,10 +2875,10 @@ fn test_switch_prs_dry_run_github_comments_tab(repo: TestRepo) {let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");let entries = parsed["entries"].as_array().expect("entries array");- // Mode 7 is Comments; the row keys its cache by `pr:42`.+ // Mode 8 is Comments; the row keys its cache by `pr:42`.let comments_entry = entries.iter()- .find(|e| e["branch"] == "pr:42" && e["mode"] == 7)+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 8).unwrap_or_else(|| panic!("no pr:42 Comments cache entry in dump:\n{stdout}"));assert!(comments_entry["bytes"].as_u64().unwrap_or(0) > 0,@@ -2921,7 +2921,7 @@ fn test_switch_prs_dry_run_gitlab(repo: TestRepo) {/// GitLab counterpart of the GitHub `_log_tab` / `_comments_tab` dry-run tests:/// an MR row's deferred `log` and `comments` tabs load via background `glab api/// --paginate projects/:fullpath/merge_requests/<n>/commits` / `…/notes?sort=asc`-/// calls keyed by the row's `mr:{N}` token. Both `mode:2` (Log) and `mode:7`+/// calls keyed by the row's `mr:{N}` token. Both `mode:4` (Log) and `mode:8`/// (Comments) cache entries with non-empty bytes prove `compute_pr_log` //// `compute_pr_comments` → `parse_gitlab_commits` / `render_gitlab_notes` →/// cache for the GitLab forge — the half the unit tests (canned JSON straight@@ -2964,7 +2964,7 @@ fn test_switch_prs_dry_run_gitlab_deferred_tabs(repo: TestRepo) {let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");let entries = parsed["entries"].as_array().expect("entries array");- for (mode, label) in [(2, "Log"), (7, "Comments")] {+ for (mode, label) in [(4, "Log"), (8, "Comments")] {let entry = entries.iter().find(|e| e["branch"] == "mr:7" && e["mode"] == mode)diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 7b61fad5c..ec911d480 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -396,7 +396,7 @@ fn wait_for_exit(////// Example: `[("\x1b[B", None), ("\x1b3", Some("diff --git"))]`/// - After Down (move cursor to the next worktree): just wait for the screen to settle.-/// - After Alt-3 (switch to the main…± diff panel): wait until "diff --git" appears.+/// - After Alt-3 (switch to the committed diff panel): wait until "diff --git" appears.fn exec_in_pty_with_input_expectations(command: &str,args: &[&str],@@ -736,7 +736,7 @@ fn is_cursor_arrow(input: &str) -> bool {/// that decorate asynchronously (CI status / PR markers): when the background/// resolution lands it refreshes skim's item list, which resets the cursor to the/// top, stranding the pointer on the primary worktree. That is a Windows-CI flake-/// observed with the cursor stuck on `main`, where the HEAD± tab showed the+/// observed with the cursor stuck on `main`, where the complete-diff tab showed the/// primary's empty diff and the awaited `diff --git` never appeared. Re-issuing/// the idempotent arrow drives the cursor back down after any reset; the wait/// returns only once the pointer holds on the target through [`STABLE_DURATION`],@@ -789,28 +789,6 @@ fn switch_picker_settings(repo: &TestRepo) -> insta::Settings {// \A anchors to absolute start of string, matching only the first line.settings.add_filter(r"\A> [^\n]*", "> [QUERY]");- // Skim's previewer overlays its vertical scroll indicator (`{vscroll_offset}/- // {content.len()}`) at the right edge of the preview pane's first line, in- // reverse video — see `skim::previewer::Previewer::draw`. We don't see the- // reverse-video attribute (vt100's `rows()` strips it), so it lands on screen- // as bare `N/M` overlapping the tab header text. content.len() varies with- // terminal width and preview content height, so it must be normalized.- //- // The previewer right-aligns the indicator at `screen_width - len - 1`, so- // it overwrites a variable-width chunk at the right edge of the tab bar. With- // all six numbered tabs the bar fills the 60-col preview pane, so the chunk- // covers tab 6 (`6: pr`), its ` | ` divider, and a few trailing chars of tab- // 5 — how many depends on the indicator's digit count (`5: summary1/46` vs- // `5: summar1/286`). Anchor on the always-visible left portion (through- // `5: summ`, well inside the pane) and rewrite the corrupted tail to the- // canonical full bar. The exact per-tab styling (bold/plain/dim) is asserted- // by the `items.rs` unit snapshots; here we only need a stable marker that- // the bar rendered with tab 6 present.- settings.add_filter(- r"(?m)^(1: HEAD± \| 2: log \| 3: main…± \| 4: remote⇅ \| 5: summ).*$",- "${1}ary | 6: pr [N/M]",- );-// Commit hashes (7-8 hex chars)settings.add_filter(r"\b[0-9a-f]{7,8}\b", "[HASH]");@@ -975,7 +953,8 @@ fn test_switch_picker_preview_navigation_and_log_panel(mut repo: TestRepo) {repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");- // One clean commit is enough to distinguish the log pane from HEAD±.+ // One clean commit is enough to distinguish the complete diff and log panes+ // from the clean working-tree pane.std::fs::write(feature_path.join("file.txt"), "content\n").unwrap();repo.run_git_in(&feature_path, &["add", "file.txt"]);repo.run_git_in(@@ -999,33 +978,34 @@ fn test_switch_picker_preview_navigation_and_log_panel(mut repo: TestRepo) {&env_vars,);- // One real session covers both cyclic directions and direct Alt-N- // selection. The paired Shift-Tab then Tab transition distinguishes- // comments (7) from PR (6): both empty panes say "has no PR", but only- // comments advances to HEAD± (1).+ // One real session covers both cyclic directions, skipping empty tabs, and+ // direct Alt-N selection. This row has content only in complete diff,+ // committed diff, and log.send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[B", Some("feature"));+ wait_for_stable_with_content(&rx, &mut parser, Some("diff --git"));- send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[Z", Some("has no PR"));+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[Z", Some("* "));- send_input_awaiting_content(- &writer,- &rx,- &mut parser,- "\t",- Some("has no uncommitted changes"),- );+ send_input_awaiting_content(&writer, &rx, &mut parser, "\t", Some("diff --git"));- send_input_awaiting_content(&writer, &rx, &mut parser, "\t", Some("* "));+ send_input_awaiting_content(&writer, &rx, &mut parser, "\t", Some("diff --git"));+ assert!(+ !preview_pane_text(parser.screen()).contains("no working-tree changes"),+ "Tab skips the empty working-tree pane"+ );+ // Direct accelerators still allow inspecting an empty tab.send_input_awaiting_content(&writer,&rx,&mut parser,- "\x1b1",- Some("has no uncommitted changes"),+ "\x1b2",+ Some("has no working-tree changes"),);- send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b2", Some("* "));+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b1", Some("diff --git"));++ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b4", Some("* "));let list = list_pane_text(parser.screen());let preview = preview_pane_text(parser.screen());@@ -1304,6 +1284,69 @@ fn test_switch_picker_alt_x_flashes_unremovable_reason(mut repo: TestRepo) {assert_valid_abort_exit_code(exit_code);}+/// skim debounces preview rendering after navigation, so a Down immediately+/// followed by Tab must let the newly selected row resolve the cycle, rather+/// than use whichever row rendered last. A listed PR starts on PR and advances+/// directly to its next available tab, comments.+#[rstest]+fn test_switch_picker_rapid_pr_navigation_cycles_from_pr(repo: TestRepo) {+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);++ let mock_bin = repo.root_path().join("mock-bin");+ std::fs::create_dir_all(&mock_bin).unwrap();+ let head = repo.git_output(&["rev-parse", "HEAD"]);+ let pr_json = format!(+ r#"[{{"number":42,"title":"Rapid preview cycle","headRefName":"rapid-pr","headRefOid":"{}","author":{{"login":"octocat"}},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42","body":"body"}}]"#,+ head.trim()+ );+ std::fs::write(mock_bin.join("pr_list.json"), pr_json).unwrap();+ let comments_json = r#"{"comments":[{"author":{"login":"octocat"},"body":"RAPIDCYCLEMARK","createdAt":"2025-01-01T00:00:00Z"}]}"#;+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list --state", MockResponse::file("pr_list.json"))+ .command("pr list --head", MockResponse::output("[]"))+ .command("pr view 42", MockResponse::output(comments_json))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);+ let env_vars = forge_mock_env_vars(&repo, &mock_bin);++ let PickerSession {+ child,+ _master,+ writer,+ rx,+ mut parser,+ } = boot_picker_pty(+ wt_bin().to_str().unwrap(),+ &["switch", "--prs"],+ repo.root_path(),+ &env_vars,+ );++ // Wait only for the row inventory, then queue navigation and cycling in+ // one flush so the PR preview cannot render between the two key events.+ wait_for_stable_with_content(&rx, &mut parser, Some("rapid"));+ {+ let mut w = writer.lock().unwrap();+ w.write_all(b"\x1b[B\t").unwrap();+ w.flush().unwrap();+ }+ wait_for_stable_with_content(&rx, &mut parser, Some("RAPIDCYCLEMARK"));++ let preview = preview_pane_text(parser.screen());+ assert!(+ preview.contains("RAPIDCYCLEMARK"),+ "Tab after rapid local→PR navigation must open comments:\n{preview}"+ );+ let exit_code = abort_and_exit_code(child, writer, rx);+ assert_valid_abort_exit_code(exit_code);+}+/// A preview pane fills in on its own once its background compute lands — no/// keystroke needed. The deterministic vehicle is a `--prs` row's `comments`/// tab: the comment fetch (`gh pr view <n> --json comments`) is held behind a@@ -1382,7 +1425,7 @@ fn test_switch_picker_preview_auto_refreshes_when_compute_lands(repo: TestRepo)// shows the short head branch `flaky`; the worktree row shows `main`. A// re-issued Down re-drives the pointer after a streamed-row refresh.send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[B", Some("flaky"));- send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b7", Some("Loading comments"));+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b8", Some("Loading comments"));let loading = preview_pane_text(parser.screen());assert!(loading.contains("Loading comments"),@@ -1891,7 +1934,7 @@ fn test_switch_picker_alt_x_last_row_refreshes_preview(mut repo: TestRepo) {wait_for_stable_with_content(&rx,&mut parser,- Some(&format!("{remove_target} has no uncommitted changes")),+ Some(&format!("{remove_target} has no file changes vs")),);// alt-x drops the last row; the cursor lands on the new last row and its preview@@ -1901,16 +1944,16 @@ fn test_switch_picker_alt_x_last_row_refreshes_preview(mut repo: TestRepo) {wait_for_stable_with_content(&rx,&mut parser,- Some(&format!("{new_last} has no uncommitted changes")),+ Some(&format!("{new_last} has no file changes vs")),);let preview = preview_pane_text(parser.screen());assert!(- preview.contains(&format!("{new_last} has no uncommitted changes")),+ preview.contains(&format!("{new_last} has no file changes vs")),"the preview refreshed to the new last row `{new_last}`.\nPreview:\n{preview}");assert!(- !preview.contains(&format!("{remove_target} has no uncommitted changes")),+ !preview.contains(&format!("{remove_target} has no file changes vs")),"the preview must not keep showing the removed row `{remove_target}`.\nPreview:\n{preview}");@@ -1918,7 +1961,7 @@ fn test_switch_picker_alt_x_last_row_refreshes_preview(mut repo: TestRepo) {}/// alt-r refreshes the preview pane, not just the row list. The in-memory preview-/// cache is keyed by `(branch, mode)` with no SHA, so a warm working-tree diff+/// cache is keyed by `(branch, mode)` with no SHA, so a warm complete diff/// would otherwise survive an edit and re-serve stale content; the refresh clears/// it so the pane recomputes against the current tree. Targets the pinned current/// worktree (the top row), so the cursor sits on it before and after the reload@@ -1927,8 +1970,8 @@ fn test_switch_picker_alt_x_last_row_refreshes_preview(mut repo: TestRepo) {fn test_switch_picker_alt_r_refreshes_preview(repo: TestRepo) {repo.run_git(&["remote", "remove", "origin"]);- // A committed, tracked file in the current worktree so `git diff HEAD` has- // something to show once it's edited (untracked files don't appear in it).+ // A committed, tracked file in the current worktree so the complete diff has+ // something to show once it's edited.let tracked = repo.root_path().join("tracked.txt");std::fs::write(&tracked, "original\n").unwrap();repo.run_git(&["add", "tracked.txt"]);@@ -1953,12 +1996,12 @@ fn test_switch_picker_alt_r_refreshes_preview(repo: TestRepo) {w.flush().unwrap();};- // The picker opens on the working-tree tab with the cursor on the pinned+ // The picker opens on the complete-diff tab with the cursor on the pinned// current worktree (`main`), whose tree is clean.- wait_for_stable_with_content(&rx, &mut parser, Some("has no uncommitted changes"));+ wait_for_stable_with_content(&rx, &mut parser, Some("has no file changes vs"));// Edit the tracked file *while the picker is open*. Without the refresh clearing- // the warm cache, alt-r would re-serve the cached "no uncommitted changes" pane.+ // the warm cache, alt-r would re-serve the cached "no changes" pane.std::fs::write(&tracked, "original\nedited\n").unwrap();send(b"\x1br"); // alt-r: refresh@@ -1970,7 +2013,7 @@ fn test_switch_picker_alt_r_refreshes_preview(repo: TestRepo) {"alt-r must recompute the working-tree preview to show the new edit.\nPreview:\n{preview}");assert!(- !preview.contains("has no uncommitted changes"),+ !preview.contains("has no file changes vs"),"the stale clean preview must not survive the refresh.\nPreview:\n{preview}");diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rsindex eff6e1803..b6bab51e4 100644--- a/tests/integration_tests/switch_picker_dry_run.rs+++ b/tests/integration_tests/switch_picker_dry_run.rs@@ -99,7 +99,7 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json("expected at least one cache entry, got: {stdout}");- // Every entry has {branch: string, mode: u8, bytes: usize}. Asserting+ // Every entry has {branch: string, mode: u8, bytes: usize, content: string}. Asserting// schema (not specific branches/modes) keeps the test robust to fixture// changes while still covering the dump format.for e in entries {@@ -121,12 +121,16 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json(.is_some_and(|bytes| usize::try_from(bytes).is_ok()),"entry bytes is not a usize: {e}");+ assert!(+ e["content"].is_string(),+ "entry content is not a string: {e}"+ );}assert!(entries.iter()- .any(|e| e["mode"] == 5 && e["bytes"].as_u64().is_some_and(|bytes| bytes > 0)),+ .any(|e| e["mode"] == 6 && e["bytes"].as_u64().is_some_and(|bytes| bytes > 0)),"summaries are disabled, so the picker must seed a nonempty static config hint: {stdout}");assert!(@@ -135,6 +139,164 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json();}+/// The speculative default-preview producer runs before list collection. It+/// must carry a real HEAD, or it can poison the `(branch, UnifiedDiff)` cache+/// key with an error pane before the collected row tries to fill it. One Rayon+/// worker makes that ordering deterministic. The hidden-untracked setting also+/// pins that the shared cleanliness signal cannot suppress the file.+#[rstest]+fn test_picker_dry_run_speculative_complete_diff_uses_real_head(+ #[from(main_only_repo)] repo: TestRepo,+) {+ repo.run_git(&["config", "status.showUntrackedFiles", "no"]);+ std::fs::write(repo.path().join("untracked-preview.txt"), "preview\n").unwrap();+ let branch = repo.current_branch();++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("RAYON_NUM_THREADS", "1")+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "dry-run should exit 0; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let complete = parsed["entries"]+ .as_array()+ .expect("top-level `entries` array")+ .iter()+ .find(|entry| entry["branch"] == branch && entry["mode"] == 1)+ .expect("current branch has a complete-diff cache entry");+ let content = complete["content"].as_str().expect("content is a string");++ assert!(+ content.contains("untracked-preview.txt"),+ "complete preview should contain the untracked file, got: {content:?}"+ );+ assert!(+ !content.contains("Could not load the complete diff"),+ "speculative preview must not cache an error pane: {content:?}"+ );+}++/// A user may point TMPDIR inside the repository (common in hermetic build+/// environments). Temporary indexes share an excluded temp namespace so+/// concurrent panes cannot see them as untracked files. Genuine untracked+/// content still appears.+#[rstest]+fn test_picker_dry_run_tempdir_inside_worktree_has_no_index_artifacts(+ #[from(main_only_repo)] repo: TestRepo,+) {+ // Brackets also prove the exclusion quotes Git pathspec glob metacharacters+ // in the user-selected temporary directory.+ let local_tmp = repo.path().join("local-[tmp]");+ std::fs::create_dir_all(&local_tmp).unwrap();+ std::fs::write(local_tmp.join(".gitkeep"), "").unwrap();+ repo.run_git(&["add", "local-[tmp]/.gitkeep"]);+ repo.run_git(&["commit", "-m", "track local temp directory"]);+ std::fs::write(repo.path().join("loose.txt"), "loose\n").unwrap();+ let branch = repo.current_branch();++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("TMPDIR", &local_tmp)+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "dry-run should exit 0; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"]+ .as_array()+ .expect("top-level `entries` array");+ for mode in [1, 2] {+ let pane = entries+ .iter()+ .find(|entry| entry["branch"] == branch && entry["mode"] == mode)+ .unwrap_or_else(|| panic!("branch {branch} has mode-{mode} cache entry"));+ let content = pane["content"].as_str().expect("content is a string");+ assert!(+ content.contains("loose.txt"),+ "mode {mode} retains genuine untracked content: {content:?}"+ );+ assert!(+ !content.contains("local-[tmp]/"),+ "mode {mode} must not include temporary-index artifacts: {content:?}"+ );+ }+}++/// Intent-to-add must cross a sparse-checkout boundary. Otherwise one+/// untracked file outside the sparse definition makes Git reject the whole add+/// and both complete/working panes degrade to an unavailable warning.+#[rstest]+fn test_picker_dry_run_includes_untracked_outside_sparse_checkout(+ #[from(main_only_repo)] repo: TestRepo,+) {+ let visible = repo.path().join("visible");+ let hidden = repo.path().join("hidden");+ std::fs::create_dir_all(&visible).unwrap();+ std::fs::create_dir_all(&hidden).unwrap();+ std::fs::write(visible.join("tracked.txt"), "base\n").unwrap();+ std::fs::write(hidden.join("tracked.txt"), "base\n").unwrap();+ repo.run_git(&["add", "visible/tracked.txt", "hidden/tracked.txt"]);+ repo.run_git(&["commit", "-m", "add sparse fixture"]);+ repo.run_git(&["sparse-checkout", "init", "--cone"]);+ repo.run_git(&["sparse-checkout", "set", "visible"]);++ std::fs::write(visible.join("tracked.txt"), "changed\n").unwrap();+ std::fs::create_dir_all(&hidden).unwrap();+ std::fs::write(hidden.join("loose.txt"), "loose\n").unwrap();+ let branch = repo.current_branch();++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "dry-run should exit 0; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"]+ .as_array()+ .expect("top-level `entries` array");+ for mode in [1, 2] {+ let pane = entries+ .iter()+ .find(|entry| entry["branch"] == branch && entry["mode"] == mode)+ .unwrap_or_else(|| panic!("branch {branch} has mode-{mode} cache entry"));+ let content = pane["content"].as_str().expect("content is a string");+ assert!(+ content.contains("visible/tracked.txt") && content.contains("hidden/loose.txt"),+ "mode {mode} includes tracked and out-of-sparse untracked changes: {content:?}"+ );+ assert!(+ !content.contains("Could not load"),+ "mode {mode} must not degrade on sparse checkout: {content:?}"+ );+ }+}+/// `switch --prs` must select the GitLab subprocess route from the remote URL,/// not merely parse GitLab-shaped JSON after some caller has already selected/// the provider. A fresh null CI cache entry keeps the worktree-row CI task@@ -278,7 +440,7 @@ fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {);// The worktree row with a PR spawns a `comments` background fetch keyed by- // its branch name (PreviewMode::Comments == 7) — the same fetch a `--prs`+ // its branch name (PreviewMode::Comments == 8) — the same fetch a `--prs`// row makes, so the comments tab is no longer `--prs`-only. In this no-network// test the entry holds a terminal pane (a "couldn't load" on a GitHub remote,// or a "forge unsupported" note otherwise), but its presence proves the fetch@@ -287,7 +449,7 @@ fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {.as_array().expect("top-level `entries` array").iter()- .filter(|e| e["mode"] == 7)+ .filter(|e| e["mode"] == 8).map(|e| e["branch"].as_str().expect("branch is a string")).collect();assert!(@@ -337,7 +499,7 @@ fn test_picker_dry_run_drains_stashed_warnings(mut repo: TestRepo) {}/// Same as above but with `list.summary=true` and a strict fake LLM command,-/// proving the configured generator runs before its result reaches mode 5.+/// proving the configured generator runs before its result reaches mode 6.#[rstest]fn test_picker_dry_run_with_summary(mut repo: TestRepo) {repo.add_worktree("feature-a");@@ -366,14 +528,14 @@ fn test_picker_dry_run_with_summary(mut repo: TestRepo) {.as_array().expect("top-level `entries` array");- // Summary mode is `5` (see `PreviewMode` in `src/commands/picker/preview.rs`).+ // Summary mode is `6` (see `PreviewMode` in `src/commands/picker/preview.rs`).// At least one entry should be a summary when summaries are enabled —- // that proves the summary spawn branch ran to completion. Mode 4+ // that proves the summary spawn branch ran to completion. Mode 5// (UpstreamDiff) is always present as part of the normal preview// modes array, so asserting on it would not prove anything about// the summary path.assert!(- entries.iter().any(|e| e["mode"] == 5),+ entries.iter().any(|e| e["mode"] == 6),"expected at least one Summary entry, got: {stdout}");assert!(diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_cache.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_cache.snapindex 0fa67439e..3996ab8f8 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_cache.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_cache.snap@@ -72,7 +72,7 @@ View or drop worktrunk's regenerable caches in one place. Everything here is reb- [1mCI status[0m — GitHub/GitLab CI per branch (30–60s TTL), shown in [2mwt list[0m, plus the largest PR/MR number seen (sizes the CI column)- [1mSummaries[0m — LLM-generated branch summaries ([2mwt list --full[0m, [2mwt switch[0m preview)-- [1mGit commands[0m — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and [2mwt switch[0m preview renders+- [1mGit commands[0m — cached merge-tree, ancestry, diff-stat, and [2mwt switch[0m preview results- [1mHints[0m — one-time hints already shown in this repo- [1mPrevious branch[0m — the [2mwt switch -[0m target, re-recorded on the next switchdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snapindex 4478adff2..4731e267f 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap@@ -72,7 +72,7 @@ Shows all stored state including:- [1mVars[0m: Custom variables per branch- [1mCI status[0m: Cached GitHub/GitLab CI status per branch (30-60s TTL), plus the largest PR/MR number seen (sizes the [2mwt list[0m CI column)- [1mSummaries[0m: Cached LLM-generated branch summaries (shown in [2mwt list --full[0m and [2mwt switch[0m preview)-- [1mGit commands cache[0m: SHA-keyed disk caches — merge-tree, ancestry, diff-stats, and [2mwt switch[0m preview renders+- [1mGit commands cache[0m: Cached merge-tree, ancestry, diff-stat, and [2mwt switch[0m preview results- [1mHints[0m: One-time hints that have been shown- [1mLog files[0m: Operation and debug logs- [1mTrash[0m: Staged worktree directories awaiting background deletiondiff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 8cd68dcfd..b85c101d4 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -9,6 +9,13 @@ info:CLICOLOR_FORCE: "1"COLUMNS: "500"GIT_ALLOW_PROTOCOL: file+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"LANG: CLC_ALL: CLLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"@@ -28,6 +35,7 @@ info:WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"WORKTRUNK_TEST_ZSH_INSTALLED: "0"---@@ -197,8 +205,8 @@ The CI column shows each row's PR/MR CI and review status, the same as [2mwt li[2mAlt-o[0m Open the selected row's PR/MR URL in the browser[2mAlt-r[0m Refresh the list (pick up worktrees created elsewhere)[2mEsc[0m Cancel- [2mAlt-1[0m–[2mAlt-7[0m Jump to a preview tab- [2mTab[0m/[2mShift-Tab[0m Cycle preview tabs forward/backward+ [2mAlt-1[0m–[2mAlt-8[0m Jump to a preview tab+ [2mTab[0m/[2mShift-Tab[0m Cycle available preview tabs forward/backward[2mAlt-p[0m Toggle preview panel[2mCtrl-u[0m/[2mCtrl-d[0m Scroll preview up/down@@ -212,13 +220,16 @@ Typing a gutter sigil filters by row kind: [36m+[0m narrows to linked worktree[1mPreview tabs:[0m-1. [1mHEAD±[0m — Diff of uncommitted changes-2. [1mlog[0m — Recent commits; commits already on the default branch have dimmed hashes-3. [1mmain…±[0m — Diff of changes since the merge-base with the default branch-4. [1mremote⇅[0m — Ahead/behind diff vs upstream tracking branch-5. [1msummary[0m — LLM-generated branch summary; requires [2m[list] summary = true[0m and [2mcommit.generation[0m-6. [1mpr[0m — The selected row's PR/MR, for any row whose branch has one-7. [1mcomments[0m — The PR/MR's comment thread, fetched from the forge for any row whose branch has one+1. [1mdiff[0m — One net diff from the comparison base through the current worktree: committed, staged, unstaged, and untracked changes+2. [1mworking[0m — Staged, unstaged, and untracked changes against [2mHEAD[0m+3. [1mcommitted[0m — Committed changes since the comparison base+4. [1mlog[0m — Recent commits; commits already on the default branch have dimmed hashes+5. [1mremote⇅[0m — Ahead/behind diff vs upstream tracking branch+6. [1msummary[0m — LLM-generated branch summary; requires [2m[list] summary = true[0m and [2mcommit.generation[0m+7. [1mpr[0m — The selected row's PR/MR, for any row whose branch has one+8. [1mcomments[0m — The PR/MR's comment thread, fetched from the forge for any row whose branch has one++The comparison base is the merge-base with the default branch, or with its upstream when the local default branch lags. The picker opens on [1mdiff[0m for local rows and [1mpr[0m for a PR/MR listed by [2m--prs[0m but not available locally. [2mTab[0m and [2mShift-Tab[0m skip tabs without content; [2mAlt-1[0m through [2mAlt-8[0m open any tab directly. After you choose a tab, that choice stays active while you navigate.On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every [2mAlt-N[0m accelerator stays visible.diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snapindex d3cfb2703..3db9793eb 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap@@ -2,7 +2,7 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± 2 3 4 5 6 7-Enter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | a+1: diff 2 3 4 5 6 7 8+Enter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | a-○ main has no uncommitted changes+○ main has no file changes vs maindiff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snapindex d29db1c39..6b7351f75 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap@@ -2,8 +2,8 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1 2: log 3 4 5 6 7-Enter: switch | ctrl-u/d: scroll | Tab/alt-1…7: preview | a+1 2 3 4: log 5 6 7 8+Enter: switch | ctrl-u/d: scroll | Tab/alt-1…8: preview | a* [HASH] +1 -1 [TIME] (feature) Commit for preview navig* [HASH] +2 [TIME] (HEAD -> main) Initial commit