Skip to content

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

feat(switch): keep the alt-r picker cursor on the removed row's slot (#3199)

Maximilian Roos599c4bab91d7
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index ea5f60076..29d99037a 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -112,6 +112,7 @@ use anyhow::Context;
// bounded/unbounded/Sender are re-exported by skim::prelude
use skim::prelude::*;
use skim::reader::CommandCollector;
+use skim::tui::event::ActionCallback;
use worktrunk::HookType;
use worktrunk::config::Approvals;
use worktrunk::git::{Repository, current_or_recover};
@@ -212,8 +213,11 @@ fn picker_item_identifier(item: &dyn SkimItem) -> String {
/// thread because skim calls `invoke()` on the main event loop thread.
/// Blocking it freezes the TUI.
///
-/// Cursor position resets to the first item after reload (skim limitation,
-/// tracked in #1695).
+/// skim resets the cursor to the top on every reload (`handle_reload` clears
+/// `item_list` before the new rows stream in — skim #1695). To keep the cursor
+/// sticky, `invoke` injects a [`reposition_cursor_action`] Custom action that
+/// moves the cursor back to the slot the removed row occupied once the reloaded
+/// rows land.
struct PickerCollector {
items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,
repo: Repository,
@@ -223,6 +227,12 @@ struct PickerCollector {
/// unapproved project commands are skipped, never run. See
/// [`approved_removal_plan`].
approvals: Arc<Approvals>,
+ /// skim's event sender, published once the TUI is initialized (same
+ /// `OnceLock` the progressive handler pushes `Event::Render` through). alt-r
+ /// removals inject a [`reposition_cursor_action`] through it to restore the
+ /// cursor after the reload. `None` until the TUI is up — but a reload can
+ /// only fire after skim is showing rows, so it's always set by then.
+ render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>>,
}
impl PickerCollector {
@@ -350,6 +360,109 @@ fn parse_reload_remove_token(cmd: &str) -> String {
unquoted.replace("'\\''", "'")
}
+/// Number of leading non-selectable header rows the picker streams (the single
+/// `HeaderSkimItem`). The skim options pass this to `.header_lines(...)`: skim
+/// reserves these from the item pool into its own Header widget, so `item_list`
+/// — what the cursor moves over — holds data rows only, indexed from 0.
+const PICKER_HEADER_ROWS: usize = 1;
+
+/// Consecutive "matcher settled but list still empty" observations
+/// [`reposition_cursor_action`] waits out before concluding the reloaded list is
+/// genuinely empty (no row to land on). `item_list.count()` lags the matcher by
+/// one render — the matcher writes its result, then a later `Event::Render`
+/// applies it — so a bare `settled && count() == 0` could give up while matches
+/// are still one render away. Each re-arm queues a Render (skim appends one after
+/// every action), so three consecutive settled observations guarantee the
+/// matcher's result has been applied before giving up.
+const REPOSITION_SETTLED_RENDERS: usize = 3;
+
+/// Hard backstop on [`reposition_cursor_action`] re-arms, far above the handful a
+/// normal reload needs. The `settled` check is the real stop condition; this only
+/// guards against an unforeseen state where the matcher never settles.
+const REPOSITION_MAX_ATTEMPTS: usize = 1000;
+
+/// The `item_list` row the cursor should land on after an alt-r removal, given
+/// the removed row's position in `shared_items` (header included) and how many
+/// data rows remain.
+///
+/// The removed row sat at `removed_pos`; the row that slides up into its slot is
+/// the next one, which lands at the same `item_list` index once the header is
+/// subtracted. Returns `None` when there's nothing to land on (the list is now
+/// header-only) or the position was the header itself. The caller clamps to the
+/// list's last row via `scroll_by`, so a removed-last-row target just overshoots
+/// and snaps back to the new last row.
+fn sticky_reposition_target(removed_pos: usize, remaining_data_rows: usize) -> Option<usize> {
+ if remaining_data_rows == 0 {
+ return None;
+ }
+ removed_pos.checked_sub(PICKER_HEADER_ROWS)
+}
+
+/// A skim `Custom` action that moves the cursor to `target` once the reloaded
+/// item list is populated.
+///
+/// skim has no "set cursor to index N" action and resets the cursor to the top
+/// on reload, so this drives the move through `ItemList`'s public cursor API
+/// with `&mut App` in hand: `jump_to_first` + `scroll_by(target)` lands on
+/// `target`, clamped to the last row.
+///
+/// The reload repopulates `item_list` asynchronously — the reader refills
+/// `item_pool`, then the matcher filters it into `item_list` — so the first
+/// invocation usually runs before the rows exist. It re-arms (returns another
+/// copy of itself; skim queues a Render after each) until the rows land. Stopping
+/// is gated on the matcher, not a blind count: once it has settled on an empty
+/// result (a removal that emptied the list, or an active query now matching
+/// nothing) for [`REPOSITION_SETTLED_RENDERS`] checks, there's nothing to land
+/// on. Sleeping instead of re-arming would hold `&mut App` across the await and
+/// starve the render that loads the rows.
+///
+/// `target` is an `item_list` index (data rows only — see [`PICKER_HEADER_ROWS`])
+/// from [`sticky_reposition_target`]. Under an active fuzzy query the displayed
+/// order diverges from `shared_items` order, so the landing row is approximate
+/// (a valid nearby row) rather than the exact next row.
+fn reposition_cursor_action(
+ target: usize,
+ attempts: Arc<AtomicUsize>,
+ settled_streak: Arc<AtomicUsize>,
+) -> Action {
+ Action::Custom(ActionCallback::new_sync(
+ move |app| -> Result<Vec<Event>, Box<dyn std::error::Error + Send + Sync>> {
+ // Rows are in: land the cursor on the removed row's slot.
+ if app.item_list.count() > 0 {
+ app.item_list.jump_to_first();
+ app.item_list
+ .scroll_by(i32::try_from(target).unwrap_or(i32::MAX));
+ return Ok(Vec::new());
+ }
+ // No rows yet. The matcher has "settled" once it has stopped with the
+ // reloaded items taken and a non-empty pool (the empty pool is the
+ // pre-refill transient). A settled-but-empty `item_list` means the
+ // reload produced no matchable rows — wait out the count() render lag,
+ // then give up. `attempts` is a hard backstop for an unforeseen
+ // never-settles state.
+ let matcher_settled = app.matcher_control.stopped()
+ && !app.item_pool.is_empty()
+ && app.item_pool.num_not_taken() == 0;
+ let streak = if matcher_settled {
+ settled_streak.fetch_add(1, Ordering::Relaxed) + 1
+ } else {
+ settled_streak.store(0, Ordering::Relaxed);
+ 0
+ };
+ if streak >= REPOSITION_SETTLED_RENDERS
+ || attempts.fetch_add(1, Ordering::Relaxed) >= REPOSITION_MAX_ATTEMPTS
+ {
+ return Ok(Vec::new());
+ }
+ Ok(vec![Event::Action(reposition_cursor_action(
+ target,
+ Arc::clone(&attempts),
+ Arc::clone(&settled_streak),
+ ))])
+ },
+ ))
+}
+
impl CommandCollector for PickerCollector {
fn invoke(
&mut self,
@@ -376,10 +489,21 @@ impl CommandCollector for PickerCollector {
// fail at runtime (TypeId mismatch between reader thread and main
// thread compilation units). All item lookups use output()
// matching instead.
- {
+ //
+ // Capture the removed row's position before dropping it so
+ // the cursor can be restored to that slot (the row that
+ // slides up) after the reload — see `reposition_cursor_action`.
+ let reposition_target = {
let mut items = self.items.lock().unwrap();
+ let removed_pos = items
+ .iter()
+ .position(|item| item.output().as_ref() == selected_output);
items.retain(|item| item.output().as_ref() != selected_output);
- }
+ let remaining_data_rows =
+ items.len().saturating_sub(PICKER_HEADER_ROWS);
+ removed_pos
+ .and_then(|pos| sticky_reposition_target(pos, remaining_data_rows))
+ };
// If removing the current worktree, cd to home so skim and git
// commands continue to work after the directory disappears.
@@ -410,6 +534,21 @@ impl CommandCollector for PickerCollector {
);
}
});
+
+ // Restore the cursor near the removed row. skim resets it
+ // to the top on every reload; inject a Custom action that
+ // moves it back to the removed row's slot once the reloaded
+ // rows land (`render_tx` is skim's event sender, set once
+ // the TUI is up — always present by the time a reload fires).
+ if let Some(target) = reposition_target
+ && let Some(event_tx) = self.render_tx.get()
+ {
+ let _ = event_tx.try_send(Event::Action(reposition_cursor_action(
+ target,
+ Arc::new(AtomicUsize::new(0)),
+ Arc::new(AtomicUsize::new(0)),
+ )));
+ }
}
Err(e) => {
log::info!("picker: cannot remove '{selected_output}': {e:#}");
@@ -646,10 +785,19 @@ pub fn handle_picker(
// to filter the hook plan; see `approved_removal_plan`.
let approvals = Arc::new(Approvals::load().context("Failed to load approvals")?);
+ // skim 4.x repaints on demand, so the collect handler needs a handle to
+ // skim's event loop to surface in-place row updates. The picker fills this
+ // once `Skim::init_tui` has run (inside `run_skim`); until then the handler
+ // simply skips its render pokes. The alt-r collector shares it too, to inject
+ // the cursor-reposition action after a removal. See `progressive_handler`
+ // module docstring.
+ let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>> = Arc::new(OnceLock::new());
+
let collector = PickerCollector {
items: Arc::clone(&shared_items),
repo: repo.clone(),
approvals,
+ render_tx: Arc::clone(&render_tx),
};
// Get state path for key bindings (shell-escaped for safety)
@@ -671,7 +819,9 @@ pub fn handle_picker(
// shows just the `>` pointer (the row's own `display()` ANSI spans carry
// no background). skim 0.20's tuikit backend highlighted the row for free.
.highlight_line(true)
- .header_lines(1usize) // Make first line (header) non-selectable
+ // First line (header) non-selectable. `PICKER_HEADER_ROWS` mirrors this
+ // count so the alt-r cursor-reposition math stays in sync — keep them one.
+ .header_lines(PICKER_HEADER_ROWS)
.multi(false)
.no_info(true) // Hide info line (matched/total counter)
.preview("") // Enable preview (empty string means use SkimItem::preview())
@@ -778,7 +928,9 @@ pub fn handle_picker(
// and streams updated items back — all without leaving the picker.
// Passing the token through the reload cmd (not an execute-silent +
// file write) sidesteps skim 4.x's fire-and-forget execute-silent,
- // which raced the reader and removed nothing.
+ // which raced the reader and removed nothing. The collector also
+ // re-positions the cursor onto the removed row's slot afterward —
+ // reload otherwise snaps it back to the top (see PickerCollector).
"alt-r:reload(remove {})".to_string(),
// Preview toggle (alt-p shows/hides preview)
// Note: skim doesn't support change-preview-window like fzf, only toggle
@@ -803,12 +955,6 @@ pub fn handle_picker(
// the `--prs` thread reads it to align PR rows with the worktree rows.
let grid_slot = Arc::new(prs::GridSlot::new());
- // skim 4.x repaints on demand, so the collect handler needs a handle to
- // skim's event loop to surface in-place row updates. The picker fills this
- // once `Skim::init_tui` has run (inside `run_skim`); until then the handler
- // simply skips its render pokes. See `progressive_handler` module docstring.
- let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>> = Arc::new(OnceLock::new());
-
// `--prs` loading flag, shared between the header (shows a "loading…"
// marker while true) and the `--prs` thread (clears it when the forge call
// resolves). `Some` exactly when that thread spawns below, so the marker
@@ -1192,7 +1338,7 @@ pub mod tests {
use std::fs;
use std::path::Path;
use std::sync::atomic::AtomicUsize;
- use std::sync::{Arc, Mutex};
+ use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use worktrunk::config::Approvals;
use worktrunk::git::BranchDeletionMode;
@@ -1301,6 +1447,26 @@ pub mod tests {
assert_eq!(parse_reload_remove_token("remove plain"), "plain");
}
+ /// `sticky_reposition_target` maps a removed row's `shared_items` position
+ /// (header at index 0) to the `item_list` index the cursor should land on —
+ /// the data-row index of the slot the removed row vacated. It declines when
+ /// the list is now header-only (nothing to land on); `scroll_by` clamps the
+ /// removed-last-row overshoot, so the helper itself never caps the target.
+ #[test]
+ fn test_sticky_reposition_target() {
+ // First data row (shared_items index 1) → item_list index 0.
+ assert_eq!(super::sticky_reposition_target(1, 3), Some(0));
+ // Third data row (index 3) → item_list index 2, with rows remaining.
+ assert_eq!(super::sticky_reposition_target(3, 2), Some(2));
+ // Removed the only data row → header-only list, nothing to land on.
+ assert_eq!(super::sticky_reposition_target(1, 0), None);
+ // The header position itself never repositions.
+ assert_eq!(super::sticky_reposition_target(0, 2), None);
+ // Removed-last-row target may exceed the remaining rows; the helper
+ // returns it verbatim and leaves clamping to `scroll_by`.
+ assert_eq!(super::sticky_reposition_target(4, 3), Some(3));
+ }
+
/// `from_signal` rejects tokens that carry no usable target: a blank or
/// whitespace-only signal, and a bare `worktree-path:` prefix with no path
/// after it. A non-empty branch token and a prefixed path both parse.
@@ -1485,6 +1651,7 @@ pub mod tests {
items: Arc::new(Mutex::new(Vec::new())),
repo,
approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::new(OnceLock::new()),
};
let target = PickerRemovalTarget::from_signal("branch-only-feature").unwrap();
@@ -1507,6 +1674,7 @@ pub mod tests {
items: Arc::new(Mutex::new(Vec::new())),
repo,
approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::new(OnceLock::new()),
};
// `RemoveResult` isn't `Debug`; drop the Ok payload so `unwrap_err`
@@ -1676,6 +1844,7 @@ pub mod tests {
items: Arc::clone(&items),
repo: repo.clone(),
approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::new(OnceLock::new()),
};
// skim's `reload(remove {})` hands invoke `remove <single-quoted token>`.
@@ -1713,6 +1882,7 @@ pub mod tests {
items: Arc::clone(&items),
repo,
approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::new(OnceLock::new()),
};
let (_rx, _interrupt) = collector.invoke("remove ''", Arc::new(AtomicUsize::new(0)));
assert_eq!(
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 283b95af5..3c4450ebb 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1664,3 +1664,178 @@ fn test_switch_picker_pre_switch_hook_requires_approval(mut repo: TestRepo) {
);
assert!(!marker.exists(), "a declined pre-switch hook must not run");
}
+
+/// Drive the picker to remove the first non-current worktree with alt-r, then
+/// switch — capturing the screen between steps so the assertion doesn't depend on
+/// the picker's commit-recency row order. Returns `(landing_branch, final_screen,
+/// exit_code)`, where `landing_branch` is the worktree that slid into the removed
+/// row's slot (the row the sticky cursor must land on).
+fn drive_alt_r_then_switch(
+ args: &[&str],
+ working_dir: &Path,
+ env_vars: &[(String, String)],
+ candidates: [&str; 2],
+) -> (String, String, i32) {
+ let pair = crate::common::open_pty_with_size(TERM_ROWS, TERM_COLS);
+
+ let mut cmd = CommandBuilder::new(wt_bin().to_str().unwrap());
+ for arg in args {
+ cmd.arg(arg);
+ }
+ cmd.cwd(working_dir);
+ crate::common::configure_pty_command(&mut cmd);
+ cmd.env("CLICOLOR_FORCE", "1");
+ cmd.env("TERM", "xterm-256color");
+ for (key, value) in env_vars {
+ cmd.env(key, value);
+ }
+
+ let mut child = pair.slave.spawn_command(cmd).unwrap();
+ drop(pair.slave);
+
+ let reader = pair.master.try_clone_reader().unwrap();
+ let writer: crate::common::pty::SharedPtyWriter =
+ Arc::new(Mutex::new(pair.master.take_writer().unwrap()));
+ let rx = crate::common::pty::spawn_pty_reader_answering_queries(reader, Arc::clone(&writer));
+
+ let mut parser = vt100::Parser::new(TERM_ROWS, TERM_COLS, 0);
+ let drain = |rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Parser| {
+ while let Ok(chunk) = rx.try_recv() {
+ parser.process(&chunk);
+ }
+ };
+ let send = |writer: &crate::common::pty::SharedPtyWriter, bytes: &[u8]| {
+ let mut w = writer.lock().unwrap();
+ w.write_all(bytes).unwrap();
+ w.flush().unwrap();
+ };
+
+ // Wait for skim to be ready.
+ let start = Instant::now();
+ loop {
+ drain(&rx, &mut parser);
+ if is_skim_ready(&parser.screen().contents()) || start.elapsed() > READY_TIMEOUT {
+ break;
+ }
+ std::thread::sleep(POLL_INTERVAL);
+ }
+
+ // Both worktree rows land in one skeleton batch, so waiting for the first
+ // candidate implies the second is present too.
+ wait_for_stable_with_content(&rx, &mut parser, Some(candidates[0]));
+
+ // Learn the row order: the candidate on the earlier list line is row 1 — the
+ // one Down lands on and alt-r removes; the other is the sticky landing row.
+ let (row1, row2) = {
+ let screen = parser.screen();
+ let list = screen
+ .rows(0, LIST_WIDTH)
+ .map(|row| row.trim_end().to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ let line_of = |name: &str| list.lines().position(|l| l.contains(name));
+ let a = line_of(candidates[0]).expect("candidate 0 in list");
+ let b = line_of(candidates[1]).expect("candidate 1 in list");
+ if a < b {
+ (candidates[0], candidates[1])
+ } else {
+ (candidates[1], candidates[0])
+ }
+ };
+
+ // Down onto row 1, confirmed via its preview pane (cursor navigation never
+ // invokes the matcher, so this is deterministic regardless of load).
+ send(&writer, b"\x1b[B");
+ wait_for_stable_with_content(
+ &rx,
+ &mut parser,
+ Some(&format!("{row1} has no uncommitted changes")),
+ );
+
+ // alt-r removes row 1; the cursor must stick to its slot — now holding row 2.
+ // Gating on row 2's preview *is* the sticky assertion: a cursor reset to the
+ // top would show the current worktree's preview and time this out.
+ send(&writer, b"\x1br");
+ wait_for_stable_with_content(
+ &rx,
+ &mut parser,
+ Some(&format!("{row2} has no uncommitted changes")),
+ );
+
+ // Enter switches to the cursor row (row 2).
+ send(&writer, b"\r");
+ drop(writer);
+
+ let start = Instant::now();
+ while start.elapsed() < Duration::from_secs(5) {
+ if child.try_wait().unwrap().is_some() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let _ = child.kill();
+ drain(&rx, &mut parser);
+ let exit_code = child.wait().unwrap().exit_code() as i32;
+
+ (row2.to_string(), parser.screen().contents(), exit_code)
+}
+
+/// alt-r keeps the cursor on the removed row's slot. After removing the first
+/// non-current worktree, the cursor stays on the row that slides up (the next
+/// worktree), so Enter switches there — not back to the current worktree at the
+/// top, which is where skim's reload would otherwise reset the cursor.
+#[rstest]
+fn test_switch_picker_alt_r_keeps_cursor_sticky(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.add_worktree("wt-keep");
+ repo.add_worktree("wt-drop");
+
+ let env_vars = repo.test_env_vars();
+ let (landing, screen, exit_code) = drive_alt_r_then_switch(
+ &["switch", "--no-cd", "--format=json"],
+ repo.root_path(),
+ &env_vars,
+ ["wt-keep", "wt-drop"],
+ );
+
+ assert_eq!(
+ exit_code, 0,
+ "switch after alt-r should exit 0.\nScreen:\n{screen}"
+ );
+ // The structured result reaches stdout only after the switch pipeline ran;
+ // it targets the sticky row, not the current worktree.
+ assert!(
+ screen.contains("\"action\""),
+ "switch emitted its --format=json result.\nScreen:\n{screen}"
+ );
+ assert!(
+ screen.contains(&landing),
+ "switch targeted the sticky row `{landing}`.\nScreen:\n{screen}"
+ );
+}
+
+/// Removing the sole row matching an active query leaves the filtered list empty,
+/// so the cursor-reposition gives up once the matcher settles empty rather than
+/// spinning the event loop. The picker stays responsive — its screen stabilizes,
+/// then aborts cleanly.
+#[rstest]
+fn test_switch_picker_alt_r_no_match_stays_responsive(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.add_worktree("solo-wt");
+
+ let env_vars = repo.test_env_vars();
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ ("solo-wt", Some("solo-wt")), // filter to the sole matching worktree
+ ("\x1br", None), // alt-r removes it; query now matches nothing
+ ],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+}