Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(picker): refresh previews on alt-r, not just the row list (#3293)

Maximilian Roosc1994055c54d
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index ae6016c47..549f842bb 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -113,7 +113,9 @@ fn anchor_faint_under_selection(
pub(super) type PreviewCacheKey = (String, PreviewMode);
/// Cache for pre-computed previews, keyed by [`PreviewCacheKey`].
-/// Shared across all PickerRows for background pre-computation.
+/// Shared across all PickerRows for background pre-computation. This is the
+/// in-memory tier and the only one `preview()` reads; the disk tiers and the
+/// invalidation rules are mapped in [`super::preview_orchestrator`].
pub(super) type PreviewCache = Arc<DashMap<PreviewCacheKey, String>>;
/// Per-row live `pr_status` for the `pr` tab, shared with the collect handler.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index dabfe0dbe..b6552640c 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -1242,8 +1242,10 @@ fn approved_removal_plan(
///
/// Each [`spawn`](Self::spawn) builds a *fresh* progressive handler (its
/// `OnceLock` slots can't be reset) and item channel, but shares the
-/// session-long state — the orchestrator / preview cache (so previews stay
-/// warm), `shared_items` and `shortcut_table` (which `on_skeleton` seeds and the
+/// session-long state — the orchestrator / preview cache (warm across row
+/// navigation and the fall-through re-stream; a refresh clears it so previews
+/// recompute — see [`spawn`](Self::spawn)), `shared_items` and `shortcut_table`
+/// (which `on_skeleton` seeds and the
/// `--prs` thread extends), and skim's `render_tx`. Held by [`PickerCollector`]
/// so a refresh can re-enter the pipeline.
struct PipelineFactory {
@@ -1294,11 +1296,14 @@ impl PipelineFactory {
/// relies on to end its `reload`.
/// `rebuild_repo` controls the worktree/branch inventory source. A refresh
/// (`alt-r`) passes `true` to rebuild a fresh `Repository`, re-enumerating
- /// after an in-picker removal. The initial spawn passes `false` to reuse the
- /// startup repo, whose cache the prelude already primed — nothing has mutated
- /// yet, so reusing it is correct and avoids re-paying `git worktree list` /
- /// `local_branches` on the first-paint hot path (doubling them there slows
- /// the picker, worst on Windows).
+ /// after an in-picker removal, and to clear the in-memory preview cache so
+ /// previews recompute (see the `spawn_repo` binding, and the
+ /// `preview_orchestrator` spec for what a refresh does and doesn't refresh).
+ /// The initial spawn passes `false` to reuse the startup repo, whose cache
+ /// the prelude already primed — nothing has mutated yet, so reusing it is
+ /// correct and avoids re-paying `git worktree list` / `local_branches` on the
+ /// first-paint hot path (doubling them there slows the picker, worst on
+ /// Windows).
///
/// The rebuild is also what lets `alt-r` drop a worktree an in-picker `alt-x`
/// removed: re-enumerating from a fresh handle skips the gone worktree, where
@@ -1325,6 +1330,22 @@ impl PipelineFactory {
// The collect thread (`bg_repo`), the `--prs` thread (`prs_repo`), and
// the skeleton handler's inventory reads all share this one snapshot.
let spawn_repo = if rebuild_repo {
+ // A refresh recomputes previews too, not just the row inventory.
+ // The in-memory preview cache is keyed by `(branch, mode)` with no
+ // SHA — the working-tree diff has no stable hash to key on — so a
+ // warm entry outlives the branch's commits or working tree moving
+ // and would re-serve a stale diff / log / summary. Dropping it lets
+ // each rebuilt row recompute against its current `item.head()` from
+ // the rebuilt inventory; the on-disk caches (SHA-keyed for log /
+ // branch-diff / upstream, diff-hash-keyed for the summary) make an
+ // unchanged branch a cheap re-read, so only genuinely changed content
+ // pays a recompute. The `pr` / `comments` tabs already self-invalidate
+ // on the CI path; clearing them here too just means a refresh also
+ // re-fetches their forge data. Precompute still runs against the
+ // orchestrator's startup repo, so a moved default-branch base isn't
+ // picked up and a narrow stale-fill race remains — see the
+ // `preview_orchestrator` module spec ("Refresh") for both.
+ self.preview_cache.clear();
Repository::at(self.repo.discovery_path())?
} else {
self.repo.clone()
@@ -3075,6 +3096,50 @@ pub mod tests {
);
}
+ /// A refresh (`alt-r`, `spawn(true)`) drops the warm in-memory preview cache
+ /// so each rebuilt row recomputes against the fresh repo; the initial spawn
+ /// (`spawn(false)`) keeps it warm. The probe entry is keyed under a branch
+ /// with no row, so the background precompute never re-fills it — the entry's
+ /// fate is the clear alone, not a race with recompute.
+ #[test]
+ fn test_refresh_clears_preview_cache_initial_spawn_keeps_it() {
+ use super::preview::PreviewMode;
+
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();
+ let factory = test_factory(repo);
+ let ghost = ("ghost-branch".to_string(), PreviewMode::WorkingTree);
+
+ // Initial spawn (`false`) preserves warm previews.
+ factory
+ .preview_cache
+ .insert(ghost.clone(), "warm".to_string());
+ let super::SpawnedPipeline {
+ handler,
+ collect_handle,
+ ..
+ } = factory.spawn(false).unwrap();
+ drop(handler);
+ collect_handle.join().unwrap();
+ assert!(
+ factory.preview_cache.contains_key(&ghost),
+ "initial spawn must keep the preview cache warm"
+ );
+
+ // Refresh (`true`) drops them.
+ let super::SpawnedPipeline {
+ handler,
+ collect_handle,
+ ..
+ } = factory.spawn(true).unwrap();
+ drop(handler);
+ collect_handle.join().unwrap();
+ assert!(
+ !factory.preview_cache.contains_key(&ghost),
+ "refresh must clear the in-memory preview cache"
+ );
+ }
+
/// alt-x with nothing selectable under the cursor hands `apply` an empty token;
/// `apply` must treat it as a no-op and leave the list intact.
#[test]
diff --git a/src/commands/picker/preview_cache.rs b/src/commands/picker/preview_cache.rs
index 548594363..53c092065 100644
--- a/src/commands/picker/preview_cache.rs
+++ b/src/commands/picker/preview_cache.rs
@@ -1,5 +1,8 @@
//! Persistent cache for picker preview content, keyed by SHA + dimensions.
//!
+//! This is the on-disk tier for three of the modes; the in-memory tier above it
+//! and the system-wide invalidation rules live in [`super::preview_orchestrator`].
+//!
//! Three of the picker's preview modes are deterministic functions of git
//! object SHAs at a given terminal width: Log on `(branch_head_sha)`,
//! BranchDiff on `(default_head_sha, branch_head_sha)`, and UpstreamDiff on
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index a075f50ae..35963595c 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -1,4 +1,99 @@
-//! Background preview pre-compute orchestration.
+//! Picker preview caching — the whole system.
+//!
+//! This module orchestrates the picker's preview content and sits on top of two
+//! cache tiers whose pieces live across several modules; this docstring is the
+//! map that ties them together. The disk tiers are in [`super::preview_cache`]
+//! and [`crate::summary`], the repaint loop in [`super::preview_notify`], the
+//! synchronous read path in [`super::items`], and the cross-spawn lifetime in
+//! the picker's `PipelineFactory` (`src/commands/picker/mod.rs`).
+//!
+//! # Two tiers
+//!
+//! **In-memory** — [`PreviewCache`], an `Arc<DashMap<(row-key, mode), String>>`.
+//! The only *cache tier* `SkimItem::preview` reads (a lock-free `get`; it never
+//! touches disk) — a miss renders a loading placeholder. (`preview()` also reads
+//! the row's live `pr_status` / `local_content` slots for tab availability and
+//! the Pr/Comments panes, but those aren't cache reads.) Session-scoped, and
+//! **shared across every
+//! `alt-r` spawn** (the one `Arc` is reused). The key is `(row-key, mode)`,
+//! where row-key is the branch for a worktree row or the `pr:N` / `mr:N` token
+//! for a `--prs` row — with **no SHA or content hash**. Two consequences: every
+//! mode shares one key shape (a `--prs` row's forge fetches and a worktree
+//! row's git diffs coexist), and a `git fetch` or new commit that moves a
+//! branch does *not* invalidate the entry — the key is unchanged, so a warm
+//! entry can outlive the content it was computed from. That staleness is
+//! reconciled two ways, both below: per-event invalidation for the PR tabs, and
+//! a wholesale clear on refresh.
+//!
+//! **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).
+//!
+//! # What backs an in-memory miss, per mode
+//!
+//! | Mode | Disk tier | Recompute on miss |
+//! |------|-----------|-------------------|
+//! | 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 |
+//! | Pr | none | render from the already-fetched CI/PR data |
+//! | Comments | none | one background forge fetch per PR |
+//!
+//! # Invalidation
+//!
+//! - **Pr / Comments** self-invalidate on the CI path: `on_update` drops the
+//! `(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.
+//! - **Refresh (`alt-r`)** clears the entire in-memory cache (in
+//! `PipelineFactory::spawn`, gated on `rebuild_repo`). What then refreshes is
+//! bounded by what the recompute sees: the rebuilt inventory gives each row a
+//! current `item.head()`, so the live working-tree diff, the log, and a branch
+//! whose own commits moved all recompute correctly. But precompute runs against
+//! the orchestrator's *startup* repo — it's built once and shared (`Arc`),
+//! never rebuilt — so values read from its `RepoCache`, notably the
+//! default-branch base SHA for BranchDiff, stay at session start; a default
+//! branch that moved externally isn't picked up until the picker reopens. The
+//! disk tiers keep an unchanged branch cheap; only genuinely changed content
+//! pays.
+//!
+//! Two known limitations follow from that once-built orchestrator: (1) the
+//! stale base SHA above; (2) a narrow race — a prior spawn's still-draining
+//! precompute task computes against its captured (now stale) `item.head()` and,
+//! because the clear emptied the cache, *fills* it instead of short-circuiting,
+//! after which the new spawn's task short-circuits on that stale entry, which
+//! then persists until the next refresh. The window opens only when a refresh
+//! fires while a prior spawn's precompute is still draining (large repo / slow
+//! summaries) and the row's content moved in that window — the common "I edited
+//! the branch I'm viewing" case doesn't hit it, since that branch's precompute
+//! finished when the picker opened. The structural fix for both is to give the
+//! orchestrator the current spawn's repo plus a spawn generation (mirroring
+//! `prs_epoch`) so a superseded fill drops.
+//!
+//! # Filling and surfacing
+//!
+//! Every background producer routes through the one [`PreviewOrchestrator::fill`]
+//! 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
+//! `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
+//! diff-hash disk cache.
+//!
+//! # Orchestration
//!
//! Routes preview tasks to the dedicated [`COLLECT_POOL`] (shared with the
//! row pipeline) and tracks the in-memory cache. A single pool lets workers
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 2a9b9fe9a..5800e86a4 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -2789,6 +2789,67 @@ fn test_switch_picker_alt_x_last_row_refreshes_preview(mut repo: TestRepo) {
let _ = abort_and_exit_code(child, writer, rx);
}
+/// 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
+/// 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
+/// regardless of skim's reload cursor behavior — no navigation needed.
+#[rstest]
+fn test_switch_picker_alt_r_refreshes_preview(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ 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).
+ let tracked = repo.root_path().join("tracked.txt");
+ std::fs::write(&tracked, "original\n").unwrap();
+ repo.run_git(&["add", "tracked.txt"]);
+ repo.run_git(&["commit", "-m", "add tracked file"]);
+
+ let env_vars = repo.test_env_vars();
+ let PickerSession {
+ child,
+ _master,
+ writer,
+ rx,
+ mut parser,
+ } = boot_picker_pty(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--no-cd", "--format=json"],
+ repo.root_path(),
+ &env_vars,
+ );
+ let send = |bytes: &[u8]| {
+ let mut w = writer.lock().unwrap();
+ w.write_all(bytes).unwrap();
+ w.flush().unwrap();
+ };
+
+ // The picker opens on the working-tree 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"));
+
+ // 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.
+ std::fs::write(&tracked, "original\nedited\n").unwrap();
+
+ send(b"\x1br"); // alt-r: refresh
+ wait_for_stable_with_content(&rx, &mut parser, Some("diff --git"));
+
+ let preview = preview_pane_text(parser.screen());
+ assert!(
+ preview.contains("diff --git"),
+ "alt-r must recompute the working-tree preview to show the new edit.\nPreview:\n{preview}"
+ );
+ assert!(
+ !preview.contains("has no uncommitted changes"),
+ "the stale clean preview must not survive the refresh.\nPreview:\n{preview}"
+ );
+
+ let _ = abort_and_exit_code(child, writer, rx);
+}
+
/// Removing the sole row matching an active query leaves the filtered list empty,
/// so the settled-gated preview refresh gives up once the matcher settles empty
/// rather than spinning the event loop. A second alt-x with nothing selected is a