Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): repaint the picker preview after the alt-r sticky reposition (#3225)
Maximilian Roos84efcb3b504f
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 2613ed309..840836c3a 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -596,6 +596,13 @@ fn sticky_reposition_target(removed_pos: usize, remaining_data_rows: usize) -> O/// 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.+///+/// On landing, it returns [`Event::RunPreview`] so the preview pane repaints for+/// the row the cursor settled on. skim only repaints the preview on a+/// selection-*change* event (`on_selection_changed`), and moving the cursor+/// through the `ItemList` API here is not one — without this, the pane keeps+/// showing the row skim last previewed (the current worktree, which the reload+/// briefly reset the cursor to) until the next keystroke.fn reposition_cursor_action(target: usize,attempts: Arc<AtomicUsize>,@@ -603,12 +610,13 @@ fn reposition_cursor_action() -> 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.+ // Rows are in: land the cursor on the removed row's slot, then+ // repaint the preview for it (the cursor move alone doesn't).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());+ return Ok(vec![Event::RunPreview]);}// 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 thediff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex d0c752a52..ab9e1c9a4 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -391,26 +391,79 @@ fn wait_for_stable(rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Parser) {/// AND has stabilized. This is essential for async preview panels where the initial/// render may show placeholder content before the actual data loads.///-/// Handles a subtle race condition: skim may continuously redraw (cursor repositioning,-/// border repaints) even after all meaningful content is rendered. These minor redraws-/// reset the stability timer, preventing the "no changes for 500ms" condition from-/// being met. To handle this, once expected content is found, we track how long it-/// has been continuously present and accept stability after STABLE_DURATION even if-/// the screen keeps changing cosmetically.-////// Tip: avoid including the panel border character (`│`) in `expected_content` —/// its rendering varies by platform and terminal, causing flaky assertions.fn wait_for_stable_with_content(rx: &mpsc::Receiver<Vec<u8>>,parser: &mut vt100::Parser,expected_content: Option<&str>,+) {+ let describe = expected_content.map(|c| format!("expected content {c:?}"));+ wait_for_stable_until(+ rx,+ parser,+ |screen| expected_content.is_none_or(|c| screen.contains(c)),+ describe.as_deref(),+ );+}++/// Wait until the list-pane cursor pointer lands on the row for `name`, then+/// settles.+///+/// skim draws its `> ` pointer on the selected row on every render of the item+/// list, so the pointer is a race-free signal of cursor position. The preview+/// pane is not: skim only repaints it on a selection-*change* event+/// (`on_selection_changed` → `Event::RunPreview`), so a cursor move driven by a+/// `Custom` action — the alt-r sticky reposition — leaves the preview showing+/// the previous row until something else repaints it. Gating cursor-position+/// assertions on the preview text therefore races the picker's async render;+/// gating on the pointer does not.+///+/// The query line also starts with `> `, but these helpers navigate by cursor+/// and never type, so the query stays empty — only the selected row both starts+/// with `>` and carries a worktree `name`, which uniquely picks it out.+fn wait_for_cursor_on_row(rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Parser, name: &str) {+ let describe = format!("the cursor (> pointer) on row {name:?}");+ wait_for_stable_until(+ rx,+ parser,+ |screen| {+ screen+ .lines()+ .any(|line| line.starts_with('>') && line.contains(name))+ },+ Some(&describe),+ );+}++/// Drive the PTY reader until the screen satisfies `ready` and then settles, or+/// the stabilization timeout elapses.+///+/// `ready` is evaluated against the full screen contents. When `describe` is+/// `Some`, a timeout that never saw `ready` panics with diagnostics (naming the+/// awaited condition); when it is `None` the caller has no readiness condition+/// (stability only) and `ready` is ignored.+///+/// Handles a subtle race: skim may keep redrawing cosmetically (cursor+/// repositioning, border repaints) even after the meaningful content is on+/// screen, which keeps resetting the "no changes for STABLE_DURATION" timer. So+/// once `ready` holds, we track how long it has held continuously and accept+/// stability after STABLE_DURATION even if the screen keeps churning. With no+/// readiness condition there is nothing to find, so the screen must settle the+/// hard way (the cosmetic-redraw fallback never engages).+fn wait_for_stable_until(+ rx: &mpsc::Receiver<Vec<u8>>,+ parser: &mut vt100::Parser,+ ready: impl Fn(&str) -> bool,+ describe: Option<&str>,) {let start = Instant::now();let mut last_change = Instant::now();let mut last_content = parser.screen().contents();- // Tracks when expected content first appeared continuously on screen.- // Used as a fallback stability signal when skim keeps redrawing cosmetically.- let mut content_found_at: Option<Instant> = None;+ // Tracks when `ready` first held continuously on screen. Used as a fallback+ // stability signal when skim keeps redrawing cosmetically.+ let mut ready_since: Option<Instant> = None;+ let has_condition = describe.is_some();while start.elapsed() < STABILIZE_TIMEOUT {// Drain available output@@ -424,19 +477,17 @@ fn wait_for_stable_with_content(last_change = Instant::now();}- // Check if expected content is present (if required)- let content_ready = match expected_content {- Some(expected) => {- let found = current_content.contains(expected);- if found {- content_found_at.get_or_insert(Instant::now());- } else {- // Content disappeared (e.g., skim full redraw) — reset- content_found_at = None;- }- found+ let content_ready = if has_condition {+ let found = ready(¤t_content);+ if found {+ ready_since.get_or_insert(Instant::now());+ } else {+ // Condition lost (e.g., skim full redraw) — reset+ ready_since = None;}- None => true,+ found+ } else {+ true};// Primary: screen hasn't changed for STABLE_DURATION and content is ready@@ -444,11 +495,10 @@ fn wait_for_stable_with_content(return;}- // Fallback for content-expected case: if expected content has been continuously- // present for STABLE_DURATION, consider the screen stable even if skim keeps- // doing cosmetic redraws (cursor repositioning, border repaints). These minor- // changes don't affect snapshot correctness.- if let Some(found_time) = content_found_at+ // Fallback (only with a readiness condition): if it has held continuously+ // for STABLE_DURATION, consider the screen stable even while skim keeps+ // doing cosmetic redraws (cursor repositioning, border repaints).+ if let Some(found_time) = ready_since&& found_time.elapsed() >= STABLE_DURATION{return;@@ -457,19 +507,19 @@ fn wait_for_stable_with_content(std::thread::sleep(POLL_INTERVAL);}- // Timeout: if expected content was specified but not found, fail with diagnostics- // instead of proceeding to a guaranteed snapshot mismatch.- if let Some(expected) = expected_content- && !last_content.contains(expected)+ // Timeout: if a condition was specified but never held, fail with diagnostics+ // instead of proceeding to a guaranteed assertion mismatch.+ if let Some(desc) = describe+ && !ready(&last_content){panic!(- "Timed out after {:?} waiting for expected content {:?} to appear on screen.\n\+ "Timed out after {:?} waiting for {desc} to appear on screen.\n\Screen content:\n{}",- STABILIZE_TIMEOUT, expected, last_content+ STABILIZE_TIMEOUT, last_content);}- // Stability-only timeout (no content expectation, or content present but unstable) —+ // Stability-only timeout (no condition, or condition present but unstable) —// warn but proceed (test may still pass with current screen state)eprintln!("Warning: Screen did not fully stabilize within {:?}",@@ -1839,24 +1889,20 @@ fn drive_alt_r_then_switch(}};- // Down onto row 1, confirmed via its preview pane (cursor navigation never- // invokes the matcher, so this is deterministic regardless of load).+ // Down onto row 1, confirmed via the list-pane cursor pointer (cursor+ // navigation never invokes the matcher, and the pointer refreshes on every+ // render, 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")),- );+ wait_for_cursor_on_row(&rx, &mut parser, row1);// 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.+ // The pointer landing on row 2 *is* the sticky assertion: a cursor reset to+ // the top would leave the pointer on the current worktree and time this out.+ // We gate on the pointer, not row 2's preview pane, because the reposition is+ // a `Custom` action and skim doesn't repaint the preview after one — see+ // `wait_for_cursor_on_row`.send(&writer, b"\x1br");- wait_for_stable_with_content(- &rx,- &mut parser,- Some(&format!("{row2} has no uncommitted changes")),- );+ wait_for_cursor_on_row(&rx, &mut parser, row2);// Enter switches to the cursor row (row 2).send(&writer, b"\r");