Skip to content

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

feat(picker): surface alt-x decline reasons in the header (#3336)

Maximilian Roos7f6f34d0cb4b
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index cea16f60d..51a1ab803 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -6,7 +6,7 @@
use std::borrow::Cow;
use std::collections::HashSet;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use ansi_to_tui::IntoText;
@@ -252,11 +252,63 @@ pub(super) struct HeaderLoading {
pub marker_ansi: String,
}
+/// A transient header line shown in place of the column labels for a beat, then
+/// cleared — the in-picker echo of an `alt-x` that declined to remove a row (the
+/// current worktree, or an unmerged branch-only row). The same reason still
+/// drains to stderr on exit (the stash stays the fallback); this just lands it
+/// immediately, in the header where the user is looking, so the *why* isn't
+/// missed when the row visibly stays put.
+///
+/// Shared picker-lifetime between the header item (which renders it) and
+/// [`AltXRemover`](super::AltXRemover) (which sets it and schedules the clear).
+/// `generation` bumps on every `set`, and a clear only fires when its captured
+/// generation still matches — so a newer flash can't be wiped early by an older
+/// flash's timer.
+#[derive(Default)]
+pub(super) struct HeaderFlash {
+ message: Mutex<Option<String>>,
+ generation: AtomicU64,
+}
+
+impl HeaderFlash {
+ /// Show `message` (pre-rendered ANSI) and return this set's generation, to
+ /// be handed to the clear timer.
+ pub fn set(&self, message: String) -> u64 {
+ let generation = self.generation.fetch_add(1, Ordering::Relaxed) + 1;
+ *self.message.lock().unwrap() = Some(message);
+ generation
+ }
+
+ /// Clear the flash, but only if no newer `set` happened since `generation`.
+ ///
+ /// The generation is read *under* the message lock so the check and the clear
+ /// are atomic against a concurrent `set` (which bumps the generation before it
+ /// takes this same lock): an interleaved `set` either bumps the generation
+ /// before this load (so the check fails and the new flash survives) or installs
+ /// its message strictly after this clear releases the lock (so it wins). A read
+ /// outside the lock could pass the check, then have a newer `set` slip in before
+ /// the clear, wiping a brand-new flash.
+ pub fn clear_if_current(&self, generation: u64) {
+ let mut message = self.message.lock().unwrap();
+ if self.generation.load(Ordering::Relaxed) == generation {
+ *message = None;
+ }
+ }
+
+ /// The flash line currently showing, if any.
+ pub fn current(&self) -> Option<String> {
+ self.message.lock().unwrap().clone()
+ }
+}
+
/// Header item for column names (non-selectable)
pub(super) struct HeaderSkimItem {
pub display_text: String,
pub display_text_with_ansi: String,
pub loading: Option<HeaderLoading>,
+ /// Transient "couldn't remove this row" message; shown in place of the
+ /// labels for a beat after a declined `alt-x` (see [`HeaderFlash`]).
+ pub flash: Arc<HeaderFlash>,
}
impl SkimItem for HeaderSkimItem {
@@ -265,6 +317,12 @@ impl SkimItem for HeaderSkimItem {
}
fn display(&self, _context: DisplayContext) -> Line<'_> {
+ // A declined-removal flash takes the slot first: it's the most recent
+ // user action and self-clears after a beat. `ansi_to_line` returns an
+ // owned `Line<'static>`, so rendering from the cloned local is fine.
+ if let Some(flash) = self.flash.current() {
+ return ansi_to_line(&flash);
+ }
// While the --prs fetch is in flight, show the loading line in place of
// the column labels — appending would clip off the right edge of a
// full-width header. The labels return when the rows land.
@@ -2081,8 +2139,9 @@ mod tests {
display_text_with_ansi: "Branch CI".to_string(),
loading: Some(HeaderLoading {
pending: Arc::clone(&pending),
- marker_ansi: " loading open PRs…".to_string(),
+ marker_ansi: "↳ Loading open PRs…".to_string(),
}),
+ flash: Arc::new(HeaderFlash::default()),
};
let text = |h: &HeaderSkimItem| {
h.display(DisplayContext::default())
@@ -2093,14 +2152,14 @@ mod tests {
};
assert!(
- text(&header).contains("loading open PRs"),
+ text(&header).contains("Loading open PRs"),
"marker shows while pending"
);
pending.store(false, Ordering::Relaxed);
let cleared = text(&header);
assert!(
- !cleared.contains("loading"),
+ !cleared.contains("Loading"),
"marker gone once cleared: {cleared:?}"
);
assert!(
@@ -2109,6 +2168,71 @@ mod tests {
);
}
+ #[test]
+ fn header_flash_takes_the_slot_then_clears() {
+ // A declined-`alt-x` flash shows in place of the column labels (and over
+ // an in-flight loading marker), then yields back once cleared.
+ let pending = Arc::new(AtomicBool::new(true));
+ let flash = Arc::new(HeaderFlash::default());
+ let header = HeaderSkimItem {
+ display_text: "Branch CI".to_string(),
+ display_text_with_ansi: "Branch CI".to_string(),
+ loading: Some(HeaderLoading {
+ pending: Arc::clone(&pending),
+ marker_ansi: "↳ Loading open PRs…".to_string(),
+ }),
+ flash: Arc::clone(&flash),
+ };
+ let text = |h: &HeaderSkimItem| {
+ h.display(DisplayContext::default())
+ .spans
+ .iter()
+ .map(|s| s.content.as_ref().to_string())
+ .collect::<String>()
+ };
+
+ // No flash yet → the loading marker holds the slot.
+ assert!(text(&header).contains("Loading open PRs"));
+
+ // The flash takes priority even over an in-flight loading marker.
+ let generation = flash.set("Can't remove the current worktree".to_string());
+ let shown = text(&header);
+ assert!(
+ shown.contains("Can't remove the current worktree"),
+ "flash takes the slot over the loading marker: {shown:?}"
+ );
+ assert!(
+ !shown.contains("Loading"),
+ "flash hides the marker: {shown:?}"
+ );
+
+ // A newer flash bumps the generation, so the first flash's clear is a
+ // no-op — the second message stays put.
+ flash.set("Kept feature — branch is unmerged".to_string());
+ flash.clear_if_current(generation);
+ let still = text(&header);
+ assert!(
+ still.contains("Kept feature — branch is unmerged"),
+ "stale clear can't wipe a newer flash: {still:?}"
+ );
+
+ // Clearing at the current generation yields the slot back — here to the
+ // still-pending loading marker.
+ let latest = flash.set("Kept feature — branch is unmerged".to_string());
+ flash.clear_if_current(latest);
+ assert!(
+ text(&header).contains("Loading open PRs"),
+ "the loading marker returns once the flash clears while still pending"
+ );
+
+ // With nothing else claiming the slot, the column labels return.
+ pending.store(false, Ordering::Relaxed);
+ assert!(
+ text(&header).contains("Branch"),
+ "the column labels return once flash and loading are both clear"
+ );
+ }
+
#[test]
fn test_loading_placeholder_all_modes() {
// Verifies wording and refresh-key hint per mode.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 7a886f7f6..103012c7e 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -123,7 +123,7 @@ use worktrunk::config::Approvals;
use worktrunk::git::{ErrorExt, Repository, current_or_recover};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- eprintln, hint_message, info_message, strip_osc8_hyperlinks, warning_message,
+ eprintln, error_message, hint_message, info_message, strip_osc8_hyperlinks, warning_message,
};
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
@@ -305,8 +305,19 @@ struct AltXRemover {
/// renders the `/ branch` row on this grid so it lines up with the worktree
/// rows. Shared with the handler (which fills it).
layout_slot: Arc<Mutex<Option<crate::commands::list::layout::LayoutConfig>>>,
+ /// The header's transient-message slot, shared with the header item. A
+ /// declined `alt-x` (current worktree, or an unmerged branch-only row) keeps
+ /// its row in place, so [`flash_header`](Self::flash_header) drops a short
+ /// "couldn't remove" line into the header for a beat — the *why* lands
+ /// immediately, not only when the stash drains on exit. See
+ /// [`items::HeaderFlash`].
+ header_flash: Arc<items::HeaderFlash>,
}
+/// How long a declined-`alt-x` header flash stays up before it self-clears and
+/// the column labels return — long enough to read, short enough not to linger.
+const HEADER_FLASH_DURATION: std::time::Duration = std::time::Duration::from_millis(2500);
+
impl AltXRemover {
/// Build removal state from a fresh `Repository` so picker reloads after a
/// background removal do not reuse the startup worktree inventory cache.
@@ -508,6 +519,36 @@ impl AltXRemover {
});
}
+ /// Flash a one-line message in the header for a beat, then restore the column
+ /// labels. The slot is shared with the header item (see [`items::HeaderFlash`]),
+ /// so this sets it, repaints, and spawns a short-lived timer that clears it and
+ /// repaints again. The timer's `clear_if_current` is generation-guarded, so a
+ /// second flash arriving mid-beat replaces this one and isn't wiped early by
+ /// this timer.
+ ///
+ /// A no-op until skim's `render_tx` is published — but `alt-x` can only fire
+ /// once the TUI is showing rows, so it's always live by the time a keep path
+ /// calls this.
+ fn flash_header(&self, message: String) {
+ let Some(tx) = self.render_tx.get() else {
+ return;
+ };
+ let generation = self.header_flash.set(message);
+ let _ = tx.try_send(Event::Render);
+
+ let header_flash = Arc::clone(&self.header_flash);
+ let render_tx = Arc::clone(&self.render_tx);
+ let _ = std::thread::Builder::new()
+ .name("picker-header-flash".into())
+ .spawn(move || {
+ std::thread::sleep(HEADER_FLASH_DURATION);
+ header_flash.clear_if_current(generation);
+ if let Some(tx) = render_tx.get() {
+ let _ = tx.try_send(Event::Render);
+ }
+ });
+ }
+
/// Keep the selected row in place and explain why its target wasn't removed.
///
/// Called from [`apply`](Self::apply) when [`removal_will_remove_target`]
@@ -515,12 +556,13 @@ impl AltXRemover {
/// is unmerged, which `SafeDelete` declines to delete (data safety). Deciding
/// this up front from `prepare_removal`'s already-computed integration check
/// means the row never drops (no flicker) and no background `do_removal` runs
- /// for a no-op. The row stays in its slot under the (un-reset) cursor; this just
- /// stashes the canonical "retained; unmerged" info + hint pair `wt remove`
- /// itself prints (see `print_retained_unmerged_branch`), deduped and drained to
- /// stderr when the picker exits. (This is a by-design retain, not a failure —
- /// distinct from [`restore_failed_removal`]'s `kept … could not remove it`
- /// warning.)
+ /// for a no-op. The row stays in its slot under the (un-reset) cursor, so this
+ /// flashes a terse "branch is unmerged" line in the header (the *why*, where the
+ /// user is looking) and stashes the canonical "retained; unmerged" info + hint
+ /// pair `wt remove` itself prints (see `print_retained_unmerged_branch`), deduped
+ /// and drained to stderr when the picker exits. (This is a by-design retain, not
+ /// a failure — distinct from [`restore_failed_removal`]'s `kept … could not
+ /// remove it` warning.)
fn keep_unremovable_row(&self, branch_name: &str) {
// The canonical "retained; unmerged" info + hint `wt remove` prints,
// shared so the picker copy can't drift (see
@@ -528,6 +570,11 @@ impl AltXRemover {
// `RemoveResult`) makes it unrepresentable for this keep path to be handed
// a `RemovedWorktree`, which always removes — see the dispatch in
// [`apply`](Self::apply) and [`removal_will_remove_target`].
+ // A by-design retain, not a failure — info (○), matching the canonical
+ // `info_message` this path stashes (see `stash_retained_unmerged_branch`).
+ self.flash_header(
+ info_message(cformat!("Kept <bold>{branch_name}</> — branch is unmerged")).to_string(),
+ );
stash_retained_unmerged_branch(&self.stashed_warnings, branch_name);
}
@@ -538,10 +585,14 @@ impl AltXRemover {
/// is true — alt-x on the worktree the picker was launched from. Removing it
/// would have to switch the shell elsewhere first (see
/// `removal_targets_current_worktree` for why that's disruptive mid-picker), so
- /// the row stays put and a hint to switch away first is stashed, drained to
- /// stderr when the picker exits. The row never drops and no `do_removal` runs,
- /// so this is the only removal path that never reaches a background thread.
+ /// the row stays put: this flashes a terse "current worktree" line in the header
+ /// and stashes the fuller hint to switch away first, drained to stderr when the
+ /// picker exits. The row never drops and no `do_removal` runs, so this is the
+ /// only removal path that never reaches a background thread.
fn keep_current_worktree_row(&self) {
+ // A by-design decline, not a failure — info (○), matching the canonical
+ // `info_message` this path stashes (see `stash_current_worktree_hint`).
+ self.flash_header(info_message("Can't remove the current worktree").to_string());
stash_current_worktree_hint(&self.stashed_warnings);
}
@@ -718,6 +769,16 @@ impl AltXRemover {
stashed.push(diagnostic);
}
}
+ // Flash the terse headline in the header too, so the *why* lands
+ // at alt-x time and not only when the stash drains on exit. Unlike
+ // the keep paths (by-design retains → info ○), this arm is a genuine
+ // rejection — error (✗), matching the `render_diagnostic` error this
+ // path stashes. `to_string()` is the typed error's short single-line
+ // label (ANSI-stripped); take its first line so a multi-line chain
+ // can't smear the header.
+ let headline = e.to_string();
+ let headline = headline.lines().next().unwrap_or(&headline);
+ self.flash_header(error_message(headline).to_string());
RemovalEffect::Kept
}
}
@@ -1266,6 +1327,11 @@ struct PipelineFactory {
/// `/ branch` row on the same grid at `alt-x` time. Filled by the handler's
/// `provide_layout`, read by [`PickerCollector`]. See [`items::LayoutSlot`].
layout_slot: items::LayoutSlot,
+ /// Shared picker-lifetime with the header item and [`AltXRemover`]: a declined
+ /// `alt-x` flashes a transient "couldn't remove this row" line in the header
+ /// (see [`items::HeaderFlash`]). One slot for the picker's life, re-shared into
+ /// each spawn's header item, so a reload reads the same (cleared) flash.
+ header_flash: Arc<items::HeaderFlash>,
preview_dims: (usize, usize),
skim_list_width: usize,
command_timeout: Option<std::time::Duration>,
@@ -1382,6 +1448,7 @@ impl PipelineFactory {
grid_slot: Arc::clone(&grid_slot),
layout_slot: Arc::clone(&self.layout_slot),
prs_loading: prs_loading.clone(),
+ header_flash: Arc::clone(&self.header_flash),
});
let bg_handler: Arc<dyn collect::PickerProgressHandler> = handler.clone();
@@ -1746,6 +1813,7 @@ summary = true
// Full-layout handoff: the handler fills it in `provide_layout`, the
// collector reads it to render the `alt-x` `/ branch` row on this grid.
layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::new(items::HeaderFlash::default()),
preview_dims,
skim_list_width,
command_timeout,
@@ -1777,6 +1845,7 @@ summary = true
stashed_warnings: Arc::clone(&stashed_warnings),
shortcut_table: Arc::clone(&shortcut_table),
layout_slot: Arc::clone(&factory.layout_slot),
+ header_flash: Arc::clone(&factory.header_flash),
};
// Half-page preview scroll: half of skim's usable height.
@@ -2936,6 +3005,7 @@ pub mod tests {
orchestrator,
stashed_warnings: Arc::new(Mutex::new(Vec::new())),
layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::new(super::items::HeaderFlash::default()),
preview_dims: (80, 24),
skim_list_width: 80,
command_timeout: None,
@@ -2965,6 +3035,7 @@ pub mod tests {
stashed_warnings: Arc::clone(&factory.stashed_warnings),
shortcut_table: Arc::clone(&factory.shortcut_table),
layout_slot: Arc::clone(&factory.layout_slot),
+ header_flash: Arc::clone(&factory.header_flash),
}
}
@@ -3399,6 +3470,7 @@ pub mod tests {
stashed_warnings: Arc::clone(&stashed),
shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::new(super::items::HeaderFlash::default()),
};
remover.apply(token.clone());
@@ -3956,6 +4028,71 @@ pub mod tests {
);
}
+ /// The header flash a declined alt-x sets self-clears after the beat: the timer
+ /// thread `flash_header` spawns runs `clear_if_current` + repaints once
+ /// `HEADER_FLASH_DURATION` elapses. Also pins the keep-path symbol — a by-design
+ /// decline flashes as info (○), not a warning. Polls for the clear (driving the
+ /// detached timer to completion) rather than racing a fixed sleep.
+ #[test]
+ fn test_header_flash_set_then_self_clears() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();
+
+ let item = branched_picker_item("current", &test.path().join("current"));
+ let items = Arc::new(Mutex::new(vec![Arc::clone(&item)]));
+ // A live sender so `flash_header` sets the flash and its timer can repaint.
+ let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<skim::prelude::Event>>> =
+ Arc::new(OnceLock::new());
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ render_tx.set(tx).unwrap();
+ let header_flash = Arc::new(super::items::HeaderFlash::default());
+ let remover = AltXRemover {
+ items,
+ repo,
+ approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::clone(&render_tx),
+ stashed_warnings: Arc::new(Mutex::new(Vec::new())),
+ shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
+ layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::clone(&header_flash),
+ };
+
+ remover.keep_current_worktree_row();
+
+ // The flash is up, styled as info (○ — a by-design decline, not a warning),
+ // and `flash_header` queued a repaint.
+ let flash = header_flash.current();
+ assert!(
+ flash
+ .as_deref()
+ .is_some_and(|f| f.contains('○') && f.contains("current worktree")),
+ "the decline flashes as info in the header: {flash:?}"
+ );
+ assert!(rx.try_recv().is_ok(), "flash_header queues a repaint");
+
+ // The timer clears it after the beat. Poll (don't fixed-sleep) so the test
+ // tracks the detached thread's completion causally; the deadline is a safety
+ // net well above `HEADER_FLASH_DURATION`.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while header_flash.current().is_some() {
+ assert!(Instant::now() < deadline, "flash never auto-cleared");
+ std::thread::sleep(Duration::from_millis(25));
+ }
+
+ // The auto-clear queues its own repaint (sent right after the clear); poll
+ // briefly so the assertion doesn't race the timer thread's final send.
+ let repaint_deadline = Instant::now() + Duration::from_secs(2);
+ let mut saw_repaint = false;
+ while Instant::now() < repaint_deadline {
+ if rx.try_recv().is_ok() {
+ saw_repaint = true;
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(saw_repaint, "the auto-clear queues a repaint");
+ }
+
/// alt-x on an unremovable target surfaces the same diagnostic `wt remove`
/// prints rather than swallowing it: `prepare_removal` errors (here the main
/// worktree can't be removed), so the dispatch's `Err` arm stashes the rendered
@@ -3969,7 +4106,22 @@ pub mod tests {
let item = branched_picker_item("main", test.path());
let token = item.output().to_string();
let items = Arc::new(Mutex::new(vec![Arc::clone(&item)]));
- let remover = test_remover(Arc::clone(&items), repo.clone());
+ // A live sender so the Err arm's `flash_header` sets the header flash.
+ let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<skim::prelude::Event>>> =
+ Arc::new(OnceLock::new());
+ let (tx, _rx) = tokio::sync::mpsc::channel(8);
+ render_tx.set(tx).unwrap();
+ let header_flash = Arc::new(super::items::HeaderFlash::default());
+ let remover = AltXRemover {
+ items: Arc::clone(&items),
+ repo: repo.clone(),
+ approvals: Arc::new(Approvals::default()),
+ render_tx: Arc::clone(&render_tx),
+ stashed_warnings: Arc::new(Mutex::new(Vec::new())),
+ shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
+ layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::clone(&header_flash),
+ };
remover.apply(token.clone());
@@ -3992,6 +4144,14 @@ pub mod tests {
.any(|w| w.contains("main worktree cannot be removed")),
"the unremovable diagnostic is stashed for the user: {warnings:?}"
);
+ // The terse headline also flashes in the header at alt-x time.
+ let flash = header_flash.current();
+ assert!(
+ flash
+ .as_deref()
+ .is_some_and(|f| f.contains("main worktree")),
+ "the unremovable reason flashes in the header: {flash:?}"
+ );
}
/// alt-x on an unmerged branch-only row never drops it (no flicker): an
@@ -4017,14 +4177,22 @@ pub mod tests {
let token = item.output().to_string();
let items = Arc::new(Mutex::new(vec![Arc::clone(&item)]));
let stashed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ // A live sender so `flash_header` sets the header flash rather than
+ // taking its no-`render_tx` early return.
+ let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<skim::prelude::Event>>> =
+ Arc::new(OnceLock::new());
+ let (tx, _rx) = tokio::sync::mpsc::channel(8);
+ render_tx.set(tx).unwrap();
+ let header_flash = Arc::new(super::items::HeaderFlash::default());
let remover = AltXRemover {
items: Arc::clone(&items),
repo: repo.clone(),
approvals: Arc::new(Approvals::default()),
- render_tx: Arc::new(OnceLock::new()),
+ render_tx: Arc::clone(&render_tx),
stashed_warnings: Arc::clone(&stashed),
shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
layout_slot: Arc::new(Mutex::new(None)),
+ header_flash: Arc::clone(&header_flash),
};
remover.apply(token.clone());
@@ -4053,6 +4221,15 @@ pub mod tests {
warnings.iter().any(|w| w.contains("wt remove -D unmerged")),
"a kept unmerged branch stashes the actionable `-D` hint: {warnings:?}"
);
+ // The *why* also flashes in the header immediately (the in-picker echo of
+ // the stash), not only on exit.
+ let flash = header_flash.current();
+ assert!(
+ flash
+ .as_deref()
+ .is_some_and(|f| f.contains("Kept") && f.contains("unmerged")),
+ "the keep path flashes the reason in the header: {flash:?}"
+ );
// A second alt-x on the same kept row dedups — the stash doesn't grow.
remover.apply(token);
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 5acfa72cf..642ffde08 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -41,7 +41,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 worktrunk::styling::{HINT_SYMBOL, StyledLine, strip_osc8_hyperlinks};
use super::super::list::ci_status::PrStatus;
@@ -52,9 +52,9 @@ use super::super::list::ci_status::PrStatus;
const RENDER_THROTTLE: Duration = Duration::from_millis(16);
use super::items::{
- HeaderLoading, HeaderSkimItem, LayoutSlot, LocalCheckout, LocalContent, LocalContentSlot,
- MorphHandle, PickerRow, PrStatusSlot, PreviewCache, RowShortcutData, RowUrl, ShortcutTable,
- pr_presence, pr_status_pane_eq, worktree_output_token,
+ HeaderFlash, HeaderLoading, HeaderSkimItem, LayoutSlot, LocalCheckout, LocalContent,
+ LocalContentSlot, MorphHandle, PickerRow, PrStatusSlot, PreviewCache, RowShortcutData, RowUrl,
+ ShortcutTable, pr_presence, pr_status_pane_eq, worktree_output_token,
};
use super::preview::PreviewMode;
use super::preview_notify::PrStatusDelta;
@@ -149,6 +149,10 @@ pub(super) struct PickerHandler {
/// flight, so the header shows a "loading…" marker. The `--prs` thread
/// clears it when the fetch resolves. `None` on non-`--prs` pickers.
pub(super) prs_loading: Option<Arc<AtomicBool>>,
+ /// Shared picker-lifetime with the header and [`AltXRemover`](super::AltXRemover):
+ /// a declined `alt-x` sets a transient "couldn't remove this row" message
+ /// here, shown in place of the column labels for a beat (see [`HeaderFlash`]).
+ pub(super) header_flash: Arc<HeaderFlash>,
}
impl PickerHandler {
@@ -322,20 +326,22 @@ impl PickerProgressHandler for PickerHandler {
.and_then(|wt| wt.path.parent().map(Path::to_path_buf));
// Header row — non-selectable via `header_lines(1)` on the options.
- // In `--prs` mode it shows a dim "loading open PRs…" line (in place of
+ // In `--prs` mode it shows a dim "↳ Loading open PRs…" line (in place of
// the column labels) until the forge call's rows land — wording mirrors
- // the empty-list "No open PRs found".
+ // the empty-list "No open PRs found", styled as a hint (the dim `↳` sits
+ // in the pointer gutter, the text aligned with the row content at col 2).
let loading = self.prs_loading.as_ref().map(|pending| {
let noun = super::prs::forge_noun(self.orchestrator.repo());
HeaderLoading {
pending: Arc::clone(pending),
- marker_ansi: cformat!(" <dim>loading open {noun}…</>"),
+ marker_ansi: cformat!("{HINT_SYMBOL} <dim>Loading open {noun}…</>"),
}
});
skim_items.push(Arc::new(HeaderSkimItem {
display_text: header.plain_text(),
display_text_with_ansi: header.render(),
loading,
+ flash: Arc::clone(&self.header_flash),
}) as Arc<dyn SkimItem>);
for (item, rendered_line) in items.into_iter().zip(rendered) {
@@ -654,6 +660,7 @@ mod tests {
grid_slot: Arc::new(super::super::prs::GridSlot::new()),
layout_slot: Arc::new(Mutex::new(None)),
prs_loading: None,
+ header_flash: Arc::new(HeaderFlash::default()),
}
}
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index e0db7cc79..9c1272759 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1525,7 +1525,7 @@ fn test_switch_picker_prs_github_list(mut repo: TestRepo) {
);
// The header's loading marker is gone once the rows have streamed in.
assert!(
- !screen.contains("loading open PRs"),
+ !screen.contains("Loading open PRs"),
"loading marker cleared once rows arrived:\n{screen}"
);
}
@@ -1653,6 +1653,59 @@ fn test_switch_picker_prs_rows_survive_alt_x_removal(mut repo: TestRepo) {
);
}
+/// alt-x on a row that can't be removed flashes the reason in the header at
+/// alt-x time, not only when the stash drains on exit. The current worktree is
+/// the picker's pinned top row, so launching from the main worktree and pressing
+/// alt-x (no cursor move) targets it — and the main worktree can't be removed, so
+/// the header swaps the column labels for `✗ The main worktree cannot be removed`
+/// for a beat. The flash *clearing* after the beat is covered by the `HeaderFlash`
+/// unit tests; this asserts it paints. A presence-wait catches it before the beat
+/// elapses (`HEADER_FLASH_DURATION`), so the test never depends on the timer.
+#[rstest]
+fn test_switch_picker_alt_x_flashes_unremovable_reason(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ // A second worktree so the skeleton paints a distinctive row to gate on; the
+ // cursor still starts on the pinned current (main) worktree above it.
+ repo.add_worktree("wt-extra");
+
+ let env_vars = repo.test_env_vars();
+ let PickerSession {
+ child,
+ _master,
+ writer,
+ rx,
+ mut parser,
+ } = boot_picker_pty(
+ wt_bin().to_str().unwrap(),
+ &["switch"],
+ repo.root_path(),
+ &env_vars,
+ );
+
+ // The worktree rows have painted (one skeleton batch); the cursor is on the
+ // pinned current worktree — the main worktree, which can't be removed.
+ wait_for_stable_with_content(&rx, &mut parser, Some("wt-extra"));
+
+ // alt-x is declined, and the reason flashes in the header. The presence-wait
+ // returns as soon as the flash paints — before it self-clears.
+ send_input_awaiting_content(
+ &writer,
+ &rx,
+ &mut parser,
+ "\x1bx",
+ Some("main worktree cannot be removed"),
+ );
+
+ 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("main worktree cannot be removed"),
+ "the unremovable reason flashes in the header at alt-x time:\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
@@ -1731,7 +1784,7 @@ fn test_switch_picker_preview_auto_refreshes_when_compute_lands(mut repo: TestRe
);
}
-/// `wt switch --prs` shows a dim "loading open PRs…" marker on the header row
+/// `wt switch --prs` shows a dim "↳ Loading open PRs…" marker on the header row
/// while the forge call is in flight. A delayed mock holds the PR list long
/// enough to observe the marker on the real screen before the rows land. The
/// picker captures and aborts at stabilize time — well before the delay
@@ -1760,13 +1813,13 @@ fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {
&env_vars,
// The loading line paints at skeleton, before the (slow) forge call
// returns its rows.
- &[("", Some("loading open PRs"))],
+ &[("", Some("Loading open PRs"))],
);
assert_valid_abort_exit_code(result.exit_code);
let (list, _preview) = result.panels();
assert!(
- list.contains("loading open PRs"),
+ list.contains("Loading open PRs"),
"loading line on the header while --prs fetches:\n{list}"
);
// The PR row hasn't streamed in yet — still inside the delayed forge call.