Skip to content

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

fix(switch): rebuild repo per picker spawn so refresh drops removed worktrees

Maximilian Rooseebbea9676c0
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 57ae25a4f..77ea779da 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -827,7 +827,7 @@ impl CommandCollector for PickerCollector {
// are kept alive by those threads, so let them drop here. On a spawn
// failure we fall through and re-stream the current items unchanged.
if cmd.trim() == "refresh" {
- match self.factory.spawn() {
+ match self.factory.spawn(true) {
Ok(SpawnedPipeline { rx, .. }) => {
let (tx_interrupt, _rx_interrupt) = bounded(1);
return (rx, tx_interrupt);
@@ -972,7 +972,14 @@ impl PipelineFactory {
/// once the spawned threads finish the channel closes and skim's reader sees
/// EOF — the "background work done → picker idle" contract, which a refresh
/// relies on to end its `reload`.
- fn spawn(&self) -> anyhow::Result<SpawnedPipeline> {
+ /// `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).
+ fn spawn(&self, rebuild_repo: bool) -> anyhow::Result<SpawnedPipeline> {
let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
// Fresh per spawn: the header shows a "loading…" marker keyed to this
@@ -980,6 +987,25 @@ impl PipelineFactory {
let prs_loading: Option<Arc<AtomicBool>> =
(self.show_prs && !self.is_preview_bench).then(|| Arc::new(AtomicBool::new(true)));
+ // Worktree/branch inventory source for this spawn. The factory's `repo`
+ // was primed with `git worktree list` / `local_branches` at picker
+ // startup, and those `RepoCache` cells are `OnceCell`s that are never
+ // invalidated. A refresh re-probing that shared cache would re-serve the
+ // startup list, so after an in-picker removal the removed worktrees would
+ // still appear and collect's per-worktree git ops would fail against the
+ // gone branches ("fatal: Needed a single revision"). So a refresh
+ // (`rebuild_repo`) builds a fresh `Repository::at` — the post-mutation
+ // discipline the `RepoCache` docs and `prepare_removal` already require.
+ // The initial spawn skips the rebuild: the primed cache is still valid,
+ // and rebuilding would re-pay both git calls on the first-paint path.
+ // 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 {
+ Repository::at(self.repo.discovery_path())?
+ } else {
+ self.repo.clone()
+ };
+
let handler: Arc<progressive_handler::PickerHandler> =
Arc::new(progressive_handler::PickerHandler {
tx: tx.clone(),
@@ -992,6 +1018,7 @@ impl PipelineFactory {
comments_fetched: OnceLock::new(),
local_content_slots: OnceLock::new(),
preview_cache: Arc::clone(&self.preview_cache),
+ repo: spawn_repo.clone(),
orchestrator: Arc::clone(&self.orchestrator),
preview_dims: self.preview_dims,
llm_command: self.llm_command.clone(),
@@ -1003,7 +1030,7 @@ impl PipelineFactory {
});
let bg_handler: Arc<dyn collect::PickerProgressHandler> = handler.clone();
- let bg_repo = self.repo.clone();
+ let bg_repo = spawn_repo.clone();
let bg_skip_tasks = self.skip_tasks.clone();
let show_branches = self.show_branches;
let show_remotes = self.show_remotes;
@@ -1035,7 +1062,7 @@ impl PipelineFactory {
// PR rows stream in (~1s) when the call returns.
let prs_handle = if let Some(prs_loading) = prs_loading {
let prs_tx = tx.clone();
- let prs_repo = self.repo.clone();
+ let prs_repo = spawn_repo.clone();
let prs_warnings = Arc::clone(&self.stashed_warnings);
let prs_orchestrator = Arc::clone(&self.orchestrator);
let prs_render_tx = Arc::clone(&self.render_tx);
@@ -1503,14 +1530,15 @@ pub fn handle_picker(
// Spawn the collect pipeline (and the `--prs` thread when active). The
// handler holds the only non-thread `tx` clone; when the bg threads exit,
- // `tx` drops, skim's reader sees EOF, and the picker goes idle. Every alt-r
- // refresh re-runs this same `factory.spawn()` — see `PipelineFactory`.
+ // `tx` drops, skim's reader sees EOF, and the picker goes idle. The initial
+ // spawn reuses the startup-primed inventory (`false`); every alt-r refresh
+ // re-runs `factory.spawn(true)` to re-enumerate — see `PipelineFactory`.
let SpawnedPipeline {
rx,
handler,
collect_handle,
prs_handle,
- } = factory.spawn()?;
+ } = factory.spawn(false)?;
worktrunk::trace::instant("Picker collect spawned");
// The dry run keeps the handler: skim never runs there, so the EOF contract
@@ -2537,6 +2565,82 @@ pub mod tests {
);
}
+ /// A refresh (`alt-r`) re-runs `factory.spawn()`. The factory carries the
+ /// `Repository` whose worktree-list cache was primed at picker startup and
+ /// is never invalidated, so after a worktree disappears `spawn` must rebuild
+ /// a fresh `Repository` rather than re-probe that stale cache — otherwise the
+ /// refresh streams a row for the gone worktree and collect's per-worktree git
+ /// ops fail against its deleted branch ("fatal: Needed a single revision").
+ #[test]
+ fn test_spawn_reenumerates_worktrees_after_removal() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ // The repo the factory carries; its cache is primed below, as the
+ // picker prelude primes it at startup.
+ let factory_repo = worktrunk::git::Repository::at(test.path()).unwrap();
+
+ let wt_dir = tempfile::tempdir().unwrap();
+ let doomed_path = wt_dir.path().join("doomed");
+ factory_repo
+ .run_command(&[
+ "worktree",
+ "add",
+ "-b",
+ "doomed",
+ doomed_path.to_str().unwrap(),
+ ])
+ .unwrap();
+ let primed_has_doomed = factory_repo
+ .list_worktrees()
+ .unwrap()
+ .iter()
+ .any(|wt| wt.branch.as_deref() == Some("doomed"));
+ assert!(primed_has_doomed, "cache primed while doomed still present");
+
+ // Remove the worktree through a separate fresh `Repository`, exactly as
+ // the picker's background removal does. `factory_repo`'s cache is now
+ // stale: it still lists `doomed`.
+ let removal_repo = worktrunk::git::Repository::at(test.path()).unwrap();
+ removal_repo
+ .run_command(&[
+ "worktree",
+ "remove",
+ "--force",
+ doomed_path.to_str().unwrap(),
+ ])
+ .unwrap();
+ removal_repo
+ .run_command(&["branch", "-D", "doomed"])
+ .unwrap();
+
+ let factory = test_factory(factory_repo);
+ // `true` models the refresh path (`alt-r`), which rebuilds a fresh repo;
+ // the initial spawn (`false`) deliberately reuses the startup inventory.
+ let super::SpawnedPipeline {
+ rx,
+ handler,
+ collect_handle,
+ ..
+ } = factory.spawn(true).unwrap();
+ // Drop the returned handler's sender, then wait for the collect thread
+ // to finish (dropping its handler clone); the lone senders gone, `rx`
+ // hits EOF. The unbounded channel buffered every streamed row.
+ drop(handler);
+ collect_handle.join().unwrap();
+ let outputs: Vec<String> = std::iter::from_fn(|| rx.recv().ok())
+ .flatten()
+ .map(|item| item.output().into_owned())
+ .collect();
+
+ assert!(
+ !outputs.is_empty(),
+ "the surviving worktree should still stream a row"
+ );
+ assert!(
+ !outputs.iter().any(|out| out.contains("doomed")),
+ "refresh must not stream the removed worktree: {outputs:?}"
+ );
+ }
+
/// alt-x with nothing selectable under the cursor expands to `remove ''`;
/// `invoke` must treat the empty token as a no-op and leave the list intact.
#[test]
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 00e63a67d..a14c9b2af 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -40,6 +40,7 @@ use std::time::{Duration, Instant};
use color_print::cformat;
use skim::prelude::*;
+use worktrunk::git::Repository;
use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};
use super::super::list::ci_status::PrStatus;
@@ -108,6 +109,16 @@ pub(super) struct PickerHandler {
/// their diff is known empty.
pub(super) local_content_slots: OnceLock<Box<[LocalContentSlot]>>,
pub(super) preview_cache: PreviewCache,
+ /// Fresh `Repository` for this spawn, used for the mutation-sensitive
+ /// `on_skeleton` reads (`list_worktrees`, `local_branches`). The
+ /// `orchestrator` carries its own startup-cloned repo shared across every
+ /// spawn — reading worktrees/branches through that re-probes a
+ /// `RepoCache.worktrees`/`local_branches` `OnceCell` primed at startup and
+ /// never invalidated, so after an in-picker removal it would yield the stale
+ /// pre-removal set. `spawn` rebuilds this repo per pass (same `spawn_repo`
+ /// the collect/prs threads use); read inventories through it, not through
+ /// `orchestrator.repo()`.
+ pub(super) repo: Repository,
pub(super) orchestrator: Arc<PreviewOrchestrator>,
pub(super) preview_dims: (usize, usize),
pub(super) llm_command: Option<String>,
@@ -229,8 +240,7 @@ impl PickerProgressHandler for PickerHandler {
// async `item.upstream`. A `local_branches()` failure yields the empty set
// (every branch reads as no-upstream); preview rendering must not error.
let upstream_branches: HashSet<String> = self
- .orchestrator
- .repo()
+ .repo
.local_branches()
.map(|branches| {
branches
@@ -254,8 +264,7 @@ impl PickerProgressHandler for PickerHandler {
// shared sibling parent. Computed once; a worktree outside that parent
// keeps its full path via the `strip_prefix` fallback.
let path_base = self
- .orchestrator
- .repo()
+ .repo
.list_worktrees()
.ok()
.and_then(|worktrees| worktrees.first())
@@ -494,26 +503,27 @@ mod tests {
use crate::commands::list::model::ListItem;
use worktrunk::testing::TestRepo;
- fn make_handler() -> (PickerHandler, TestRepo, SkimItemReceiver) {
- let test = TestRepo::with_initial_commit();
- let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
- let shared_items = Arc::new(Mutex::new(Vec::new()));
- let orchestrator = Arc::new(PreviewOrchestrator::new(
- test.repo.clone(),
- Arc::new(OnceLock::new()),
- ));
+ /// Build a handler with explicit `repo` (the per-spawn inventory source)
+ /// and `orchestrator` (preview compute). Diverging the two lets a test
+ /// prove which one `on_skeleton`'s inventory reads consult.
+ fn handler_with(
+ repo: Repository,
+ orchestrator: Arc<PreviewOrchestrator>,
+ tx: SkimItemSender,
+ ) -> PickerHandler {
let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
- let handler = PickerHandler {
+ PickerHandler {
tx,
render_tx: Arc::new(OnceLock::new()),
last_render_poke: Mutex::new(Instant::now()),
- shared_items,
+ shared_items: Arc::new(Mutex::new(Vec::new())),
shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
rendered_slots: OnceLock::new(),
pr_status_slots: OnceLock::new(),
comments_fetched: OnceLock::new(),
local_content_slots: OnceLock::new(),
preview_cache,
+ repo,
orchestrator,
preview_dims: (80, 24),
llm_command: None,
@@ -522,7 +532,17 @@ mod tests {
deferred_items: OnceLock::new(),
grid_slot: Arc::new(super::super::prs::GridSlot::new()),
prs_loading: None,
- };
+ }
+ }
+
+ fn make_handler() -> (PickerHandler, TestRepo, SkimItemReceiver) {
+ let test = TestRepo::with_initial_commit();
+ let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
+ let orchestrator = Arc::new(PreviewOrchestrator::new(
+ test.repo.clone(),
+ Arc::new(OnceLock::new()),
+ ));
+ let handler = handler_with(test.repo.clone(), orchestrator, tx);
(handler, test, rx)
}
@@ -536,6 +556,56 @@ mod tests {
crate::commands::list::layout::ColumnGrid::default()
}
+ /// `on_skeleton` reads the worktree/branch inventory through the handler's
+ /// own per-spawn `repo`, NOT the orchestrator's startup-cloned repo. `spawn`
+ /// rebuilds `repo` fresh each refresh; reading inventory through the
+ /// orchestrator's never-invalidated `RepoCache` would serve the stale
+ /// pre-removal snapshot after an in-picker removal. Here the two repos live
+ /// under different temp parents, so the matcher path-base
+ /// (`list_worktrees().first()`) differs — a row under the handler-repo's tree
+ /// strips to a relative tail only if `on_skeleton` consulted `self.repo`.
+ #[test]
+ fn on_skeleton_reads_inventory_from_handler_repo_not_orchestrator() {
+ use crate::commands::list::model::{ItemKind, WorktreeData};
+
+ let self_repo = TestRepo::with_initial_commit();
+ let orchestrator_repo = TestRepo::with_initial_commit();
+ let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
+ let orchestrator = Arc::new(PreviewOrchestrator::new(
+ orchestrator_repo.repo.clone(),
+ Arc::new(OnceLock::new()),
+ ));
+ let handler = handler_with(self_repo.repo.clone(), orchestrator, tx);
+
+ // A worktree row under the handler-repo's tree. The shared parent strips
+ // only if path_base comes from self_repo (parent of `<temp>/repo`), not
+ // from orchestrator_repo (a different temp parent).
+ let mut item = ListItem::new_branch("abc".into(), "feature".into());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path: self_repo.path().join("feature"),
+ ..Default::default()
+ }));
+ handler.on_skeleton(vec![item], vec!["skel".into()], header("hdr"), grid());
+
+ let received = rx.recv().expect("skeleton batch");
+ // received[0] is the header; received[1] is the worktree row.
+ let matcher_text = received[1].text().into_owned();
+ // The stripped tail renders with the OS separator (`to_string_lossy`),
+ // so build the expected tail the same way rather than hardcoding `/`
+ // (the row path is `repo\feature` on Windows).
+ let expected_tail = Path::new("repo").join("feature");
+ assert!(
+ matcher_text.contains(expected_tail.to_string_lossy().as_ref()),
+ "row path should appear in the matcher text: {matcher_text:?}"
+ );
+ // The buggy orchestrator-repo path_base can't strip a self_repo path, so
+ // it would leave the absolute `<temp>/repo` prefix in the matcher text.
+ assert!(
+ !matcher_text.contains(self_repo.path().to_string_lossy().as_ref()),
+ "path_base from self.repo must strip the absolute prefix: {matcher_text:?}"
+ );
+ }
+
/// Skeleton → update → reveal: verifies that each event writes through
/// to the shared `rendered` string the `WorktreeSkimItem` holds. Skim
/// reads these strings each time it repaints (which `request_render`