Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(picker): keep --prs rows visible after an alt-x removal (#3275)
Maximilian Roos41db03754bf4
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 4ffb849f9..a4660d1e0 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1243,13 +1243,19 @@ 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` overwrites),-/// and skim's `render_tx`. Held by [`PickerCollector`] so a refresh can-/// re-enter the pipeline.+/// warm), `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 {repo: Repository,render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>>,shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,+ /// Monotonic spawn counter. Each [`spawn`](Self::spawn) bumps it and hands+ /// the value to that spawn's `--prs` thread, which appends its PR/MR rows to+ /// `shared_items` only while the counter still matches — so a stale forge call+ /// from a pre-refresh spawn can't pollute the list a later spawn rebuilt. See+ /// [`prs::PrsShared`].+ prs_epoch: Arc<AtomicUsize>,shortcut_table: ShortcutTable,preview_cache: PreviewCache,orchestrator: Arc<PreviewOrchestrator>,@@ -1395,9 +1401,18 @@ impl PipelineFactory {let prs_warnings = Arc::clone(&self.stashed_warnings);let prs_orchestrator = Arc::clone(&self.orchestrator);let prs_render_tx = Arc::clone(&self.render_tx);+ // Bump the spawn counter and capture this spawn's value: the `--prs`+ // thread appends its rows to `shared_items` only while the counter+ // still matches, so an earlier spawn's still-in-flight forge call+ // can't add rows to this (or a later) spawn's list. See+ // `PipelineFactory::prs_epoch` and `prs::PrsShared`.+ let current_epoch = self.prs_epoch.fetch_add(1, Ordering::SeqCst) + 1;let prs_shared = prs::PrsShared {grid_slot: Arc::clone(&grid_slot),shortcut_table: Arc::clone(&self.shortcut_table),+ shared_items: Arc::clone(&self.shared_items),+ epoch: Arc::clone(&self.prs_epoch),+ current_epoch,};let prs_layout = prs::PrsLayout {list_width: self.skim_list_width,@@ -1648,10 +1663,11 @@ pub fn handle_picker((None, Some(hint.to_string()))};- // Shared items list: populated by the handler's `on_skeleton` and read- // by `PickerCollector` on alt-x reload. Starts empty — the collector's- // `invoke` only fires after skim has displayed items, by which time- // the handler has already published them.+ // The picker's full row list — header, worktree/branch rows, and (in `--prs`+ // mode) PR/MR rows. `on_skeleton` fills it with the header + worktree/branch+ // rows and the `--prs` thread appends its PR/MR rows; an `alt-x` removal+ // mutates it (`AltXRemover`) and rebuilds skim's pool from it (`resync_pool`).+ // Starts empty — those writers run only after skim is displaying rows.let shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>> = Arc::new(Mutex::new(Vec::new()));// `alt-y` / `alt-o` lookup table (token → branch + URL). The collect handler@@ -1675,6 +1691,7 @@ pub fn handle_picker(repo: repo.clone(),render_tx: Arc::clone(&render_tx),shared_items: Arc::clone(&shared_items),+ prs_epoch: Arc::new(AtomicUsize::new(0)),shortcut_table: Arc::clone(&shortcut_table),preview_cache: Arc::clone(&preview_cache),orchestrator: Arc::clone(&orchestrator),@@ -2869,6 +2886,7 @@ pub mod tests {repo,render_tx,shared_items: Arc::new(Mutex::new(Vec::new())),+ prs_epoch: Arc::new(std::sync::atomic::AtomicUsize::new(0)),shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),preview_cache,orchestrator,diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex d1231c296..35b93f904 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -37,7 +37,7 @@use std::collections::HashSet;use std::path::Path;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Condvar, Mutex, OnceLock};use std::time::Duration;@@ -242,12 +242,31 @@ pub(super) struct PrsLayout {}/// The structures the `--prs` thread coordinates with the collect side: the-/// column-geometry handoff that aligns PR rows with the worktree grid, and the-/// `alt-y` / `alt-o` shortcut table it extends with PR/MR rows. Bundled so the-/// streaming entry points stay within the argument budget.+/// column-geometry handoff that aligns PR rows with the worktree grid, the+/// `alt-y` / `alt-o` shortcut table it extends with PR/MR rows, and the picker's+/// shared row list it appends those rows into. Bundled so the streaming entry+/// points stay within the argument budget.pub(super) struct PrsShared {pub grid_slot: Arc<GridSlot>,pub shortcut_table: ShortcutTable,+ /// The picker's row list (`shared_items` — what `resync_pool` rebuilds skim's+ /// pool from on an `alt-x` removal). `on_skeleton` fills it with the+ /// worktree/branch rows; the `--prs` thread appends its PR/MR rows here too,+ /// so a removal's pool rebuild keeps the streamed rows (they reach skim+ /// through its own channel, which `resync_pool` never reads). Appended after+ /// the skeleton has populated it — the `grid_slot.wait` below is gated on+ /// that — so PR rows always land after the worktree rows, never in the+ /// reserved header slot.+ pub shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,+ /// Session-shared spawn counter (`PipelineFactory::prs_epoch`); each spawn+ /// bumps it. Read together with `current_epoch` to decide whether this+ /// thread's append is still wanted — see the append in [`fetch_and_stream`].+ pub epoch: Arc<AtomicUsize>,+ /// This spawn's `epoch` value, captured when the thread was spawned. The+ /// append into `shared_items` runs only while `epoch` still equals it, so a+ /// stale forge call from a pre-refresh spawn (whose skim channel is already+ /// dropped) can't pollute the list a newer spawn rebuilt.+ pub current_epoch: usize,}/// Stream the open PRs/MRs into the picker, then clear the header's "loading…"@@ -380,6 +399,23 @@ fn fetch_and_stream()) as Arc<dyn SkimItem>}).collect();++ // Record the PR rows in the picker's shared list so an `alt-x` removal's+ // pool rebuild (`resync_pool`) keeps them — they reach skim through its own+ // channel below, which the rebuild never reads. The skeleton has already+ // populated `shared_items` (the `grid_slot.wait` above gates on it), so this+ // appends after the worktree rows. Done under the lock and gated on the spawn+ // epoch: a stale forge call from a pre-refresh spawn (its skim channel already+ // dropped) must not add rows to the list a newer spawn rebuilt — reading the+ // epoch inside the lock pairs the check with the next spawn's `on_skeleton`+ // overwrite, which holds the same lock. Ordered before `tx.send` so the rows+ // reach `shared_items` no later than they reach skim's pool.+ {+ let mut list = shared.shared_items.lock().unwrap();+ if shared.epoch.load(Ordering::SeqCst) == shared.current_epoch {+ list.extend(items.iter().map(Arc::clone));+ }+ }let _ = tx.send(items);}@@ -1772,6 +1808,9 @@ mod tests {let shared = PrsShared {grid_slot: Arc::new(GridSlot::new()),shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),+ shared_items: Arc::new(Mutex::new(Vec::new())),+ epoch: Arc::new(AtomicUsize::new(1)),+ current_epoch: 1,};let (rtx, mut rrx) = tokio::sync::mpsc::channel(8);let render_tx = OnceLock::new();diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex bb96cf940..c65fc4a99 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1473,6 +1473,92 @@ fn test_switch_picker_prs_gitlab_list(mut repo: TestRepo) {);}+/// Removing a worktree row with alt-x in `--prs` mode must keep the streamed+/// PR/MR rows on screen — only the removed worktree row leaves the list, no+/// alt-r refresh needed.+///+/// alt-x's drop path rebuilds skim's item pool from the picker's shared row list+/// (`resync_pool`). The `--prs` thread streams its PR rows straight to skim's+/// item channel, so unless they're also recorded in that shared list the rebuild+/// drops them. This drives the drop path (a clean, integrated worktree, removed+/// row leaves the list) and asserts the `#42` PR row survives it.+#[rstest]+fn test_switch_picker_prs_rows_survive_alt_x_removal(mut repo: TestRepo) {+ repo.remove_fixture_worktrees();+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);+ // A clean worktree at main's commit: its branch is integrated, so alt-x+ // takes the drop path (row leaves the list → `resync_pool`), not the morph+ // path (which keeps the row in place and never resyncs the pool).+ repo.add_worktree("wt-drop");++ // PR #42's head branch isn't a shown worktree/branch, so it survives the+ // `--prs` dedup and streams in as its own `#42` row. The mock answers only+ // the `--prs` list call (`gh pr list --state`); the per-worktree CI fetch+ // (`gh pr list --head <branch>`) gets an empty list, so `#42` appears solely+ // as the streamed `--prs` row — never folded into a worktree row's CI cell.+ let pr_json = r#"[{"number":42,"title":"Retry the flaky network test","headRefName":"fix/flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42","body":"Wraps the request in a retry so the suite stops flaking."}]"#;+ let mock_bin = repo.root_path().join("mock-bin");+ std::fs::create_dir_all(&mock_bin).unwrap();+ std::fs::write(mock_bin.join("list.json"), pr_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list --state", MockResponse::file("list.json"))+ .command("pr list --head", MockResponse::output("[]"))+ .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,+ );++ // Preview off (alt-p) so the full-width list renders the CI column (`#42`),+ // which the preview-shown pane otherwise clips past skim's split. The wait+ // also blocks until the `--prs` row has streamed in.+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1bp", Some("#42"));+ // The worktree row is on screen too (one skeleton batch).+ wait_for_stable_with_content(&rx, &mut parser, Some("wt-drop"));++ // Cursor onto the removable worktree row (the row below the pinned current+ // worktree), then alt-x removes it.+ send_input_awaiting_content(&writer, &rx, &mut parser, "\x1b[B", Some("wt-drop"));+ {+ let mut w = writer.lock().unwrap();+ w.write_all(b"\x1bx").unwrap();+ w.flush().unwrap();+ }+ // The worktree row drops; gating on its disappearance proves the resync ran.+ wait_for_stable_until(+ &rx,+ &mut parser,+ |screen| !screen.contains("wt-drop"),+ Some("the wt-drop row to leave the list"),+ None,+ );++ let screen = parser.screen().contents();+ let exit_code = abort_and_exit_code(child, writer, rx);+ assert_valid_abort_exit_code(exit_code);+ assert!(+ screen.contains("#42"),+ "PR row must survive the alt-x worktree removal (no alt-r needed).\nScreen:\n{screen}"+ );+}+/// 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 mocked behind a