Skip to content

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

fix(switch): auto-refresh picker preview when a background compute lands (#3247)

Maximilian Roose3ca4c2b5156
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 5eec6f247..85ed8e374 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -25,6 +25,7 @@ use super::pager::{diff_pager, pipe_through_pager};
use super::pr_pane;
use super::preview::{PreviewMode, PreviewStateData};
use super::preview_cache;
+use super::preview_notify::PreviewNotifier;
/// Parse a pre-rendered ANSI string into a single ratatui `Line` for skim's
/// item list. skim's `DisplayContext::to_line` only applies match-highlight
@@ -270,6 +271,11 @@ pub(super) struct WorktreeSkimItem {
/// handler mirrors them here as the pipeline lands — letting those tabs dim
/// once their diff is known empty (see [`LocalContent`]).
pub local_content: LocalContentSlot,
+ /// Surfaces a background preview fill without a keystroke. `preview()`
+ /// records the row's awaited `(branch, mode)` here on every render; the
+ /// orchestrator pokes a repaint when that key's compute lands (see
+ /// [`PreviewNotifier`]).
+ pub notifier: Arc<PreviewNotifier>,
}
impl SkimItem for WorktreeSkimItem {
@@ -294,6 +300,10 @@ impl SkimItem for WorktreeSkimItem {
// `render_preview`, which takes the mode explicitly so it's testable
// without touching that global state.
let mode = PreviewStateData::read_mode();
+ // Record what this (selected) row is showing *before* reading the cache,
+ // so a background fill that lands right after a miss still finds the key
+ // set and pokes a repaint (see `PreviewNotifier`).
+ self.notifier.note_awaiting(&self.branch_name, mode);
ItemPreview::AnsiText(self.render_preview(mode, context.width, context.height))
}
}
@@ -784,9 +794,9 @@ impl WorktreeSkimItem {
let reset = Reset;
let branch = self.item.branch_name();
match pr {
- PrPreview::Loading => cformat!(
- "○ Fetching PR status for <bold>{branch}</>{reset}… press <bold>alt-6</>{reset} to refresh\n"
- ),
+ PrPreview::Loading => {
+ cformat!("○ Fetching PR status for <bold>{branch}</>{reset}…\n")
+ }
PrPreview::NoPr => {
cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no PR\n")
}
@@ -809,11 +819,10 @@ impl WorktreeSkimItem {
let branch = self.item.branch_name();
match self.pr_preview() {
// The CI fetch hasn't reported yet — we don't know whether there's a
- // PR to fetch comments for. Mirror the `pr` tab's loading state,
- // pointing at this tab's accelerator.
- PrPreview::Loading => cformat!(
- "○ Fetching PR status for <bold>{branch}</>{reset}… press <bold>alt-7</>{reset} to refresh\n"
- ),
+ // PR to fetch comments for. Mirror the `pr` tab's loading state.
+ PrPreview::Loading => {
+ cformat!("○ Fetching PR status for <bold>{branch}</>{reset}…\n")
+ }
PrPreview::NoPr => {
cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no PR\n")
}
@@ -830,7 +839,8 @@ impl WorktreeSkimItem {
/// Pure cache read: skim invokes `preview()` synchronously while drawing
/// the preview pane, so any blocking here gates the render. Background
/// tasks populate the cache out-of-band; a miss returns a placeholder, and
- /// skim re-queries on the next selection/query change.
+ /// the orchestrator pokes a repaint for the awaited key once the fill lands
+ /// (see [`PreviewNotifier`]).
fn preview_for_mode(&self, mode: PreviewMode, width: usize, _height: usize) -> String {
let cache_key = (self.branch_name.clone(), mode);
let content = self
@@ -841,19 +851,17 @@ impl WorktreeSkimItem {
match mode {
// Summary post-processing is cheap (string formatting, no subprocess).
- // Applied at display time because generate_and_cache_summary() inserts
+ // Applied at display time because `generate_summary_for_item` produces
// raw LLM output.
PreviewMode::Summary => super::summary::render_summary(&content, width),
_ => content,
}
}
- /// Placeholder shown while a background task is still computing the
- /// preview for this mode. Skim has no API to re-query the preview from
- /// outside user interaction, so the hint tells the user to press the mode
- /// key again to refresh once the background fill lands. `alt-N`
- /// re-runs the same `echo N + refresh-preview` chain, re-reading the
- /// now-populated cache.
+ /// Placeholder shown while a background task is still computing the preview
+ /// for this mode. The pane fills in on its own once the compute lands — the
+ /// orchestrator pokes a repaint for the awaited key (see [`PreviewNotifier`])
+ /// — so the placeholder just states what's loading.
pub(super) fn loading_placeholder(mode: PreviewMode) -> String {
let (verb, label) = match mode {
PreviewMode::WorkingTree => ("Loading", "working-tree diff"),
@@ -871,8 +879,7 @@ impl WorktreeSkimItem {
unreachable!("comments tab renders via render_comments_pane")
}
};
- let key = mode as u8;
- format!("○ {verb} {label}. Press alt-{key} again to refresh.\n")
+ format!("○ {verb} {label}…\n")
}
/// Compute preview and apply pager for diff modes. Returns the
@@ -1672,6 +1679,7 @@ mod tests {
summaries_enabled: false,
pr_status: Arc::new(Mutex::new(None)),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
}
};
@@ -1687,6 +1695,7 @@ mod tests {
summaries_enabled: false,
pr_status: Arc::new(Mutex::new(None)),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
}
};
@@ -1773,6 +1782,7 @@ mod tests {
summaries_enabled: false,
pr_status: Arc::new(Mutex::new(pr_status)),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
}
};
@@ -1880,13 +1890,14 @@ mod tests {
summaries_enabled: false,
pr_status: Arc::new(Mutex::new(slot)),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
};
- // CI hasn't reported (None) → fetching hint pointing at this tab's key.
+ // CI hasn't reported (None) → the shared "Fetching PR status…" hint (it
+ // auto-resolves once the live status lands; see `PreviewNotifier`).
let loading = row(None, Arc::new(DashMap::new()));
let pane = loading.render_comments_pane();
assert!(pane.contains("Fetching PR status"), "loading: {pane:?}");
- assert!(pane.contains("alt-7"), "loading points at alt-7: {pane:?}");
// No PR (Some(None)) → "has no PR", matching the `pr` tab.
let no_pr = row(Some(None), Arc::new(DashMap::new()));
@@ -1984,6 +1995,7 @@ mod tests {
comment_count: None,
})))),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
};
// In Pr mode, `render_preview` assembles the tab bar plus the worktree PR
@@ -2066,6 +2078,7 @@ mod tests {
summaries_enabled: false,
pr_status: Arc::clone(&slot),
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: PreviewNotifier::detached(),
};
// First render populates the shared cache.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 28750fee0..57ae25a4f 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -97,6 +97,7 @@ mod pager;
mod pr_pane;
mod preview;
pub(crate) mod preview_cache;
+mod preview_notify;
mod preview_orchestrator;
mod progressive_handler;
mod prs;
@@ -1160,7 +1161,20 @@ pub fn handle_picker(
// preview tasks share one inventory scan instead of each forking
// `git rev-parse`. Read-only for the picker session — see the
// accessor's docstring for the staleness contract.
- let orchestrator = Arc::new(PreviewOrchestrator::new(repo.clone()));
+ //
+ // skim 4.x repaints on demand, so the orchestrator needs a handle to skim's
+ // event loop to surface a preview compute that lands after the keystroke that
+ // requested it. The picker fills this `OnceLock` once `Skim::init_tui` has run
+ // (inside `run_skim`); until then a fill simply doesn't poke (harmless — skim
+ // hasn't rendered a preview to strand yet). The progressive handler and alt-x
+ // collector share the same sender for their own `Event::Render` /
+ // reposition pokes. See `preview_notify` and the `progressive_handler` module
+ // docstring.
+ let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>> = Arc::new(OnceLock::new());
+ let orchestrator = Arc::new(PreviewOrchestrator::new(
+ repo.clone(),
+ Arc::clone(&render_tx),
+ ));
let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
// Speculative warm-up: the picker sorts the current worktree first, and
@@ -1293,14 +1307,6 @@ 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-x 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());
-
// Shared between the bg-thread collect handler and a failed alt-x removal
// (both push warnings while skim owns the terminal) and the main thread
// (which drains them after `Skim::run_with` returns and stderr is safe
@@ -2365,6 +2371,7 @@ pub mod tests {
summaries_enabled: false,
pr_status,
local_content: Arc::new(Mutex::new(LocalContent::default())),
+ notifier: super::preview_notify::PreviewNotifier::detached(),
}) as Arc<dyn SkimItem>
}
@@ -2403,13 +2410,15 @@ pub mod tests {
/// tests don't exercise, so the minimal field set is enough to satisfy the
/// type without standing up a full picker.
fn test_factory(repo: worktrunk::git::Repository) -> std::rc::Rc<super::PipelineFactory> {
+ let render_tx = Arc::new(OnceLock::new());
let orchestrator = Arc::new(super::preview_orchestrator::PreviewOrchestrator::new(
repo.clone(),
+ Arc::clone(&render_tx),
));
let preview_cache = Arc::clone(&orchestrator.cache);
std::rc::Rc::new(super::PipelineFactory {
repo,
- render_tx: Arc::new(OnceLock::new()),
+ render_tx,
shared_items: Arc::new(Mutex::new(Vec::new())),
shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),
preview_cache,
diff --git a/src/commands/picker/preview_notify.rs b/src/commands/picker/preview_notify.rs
new file mode 100644
index 000000000..62d0c5b5e
--- /dev/null
+++ b/src/commands/picker/preview_notify.rs
@@ -0,0 +1,164 @@
+//! Surfacing a background preview fill without a keystroke.
+//!
+//! skim 4.x renders a row's preview only when it *runs* a preview
+//! (`Event::RunPreview`), which it produces on a selection change or a
+//! preview-tab switch. The picker's preview panes are served from a shared
+//! [`PreviewCache`](super::items::PreviewCache) that background workers fill
+//! out-of-band (a `git diff HEAD`, a `git log`, a forge `gh pr view`). A fill
+//! that lands *after* the `RunPreview` the keystroke produced has no event to
+//! surface it: the finished content sits in the cache while the pane keeps
+//! showing its "Loading…" placeholder until the next keystroke.
+//!
+//! `PreviewNotifier` closes that loop. The selected row records what its preview
+//! is currently showing — `(row-key, mode)` — on every render via
+//! [`note_awaiting`](PreviewNotifier::note_awaiting). When a background fill lands
+//! on that exact key, [`notify_filled`](PreviewNotifier::notify_filled) injects an
+//! `Event::RunPreview` through skim's own event sender, so skim re-reads the
+//! now-warm cache and paints the content. A fill for any other key — an
+//! off-screen row, or a tab the user isn't looking at — matches nothing and
+//! injects nothing, so background pre-compute never re-runs the visible preview.
+//!
+//! Some panes aren't fed by an orchestrator cache fill: the `pr` / `comments`
+//! panes read the row's live `pr_status`, and the diff tabs' dim state reads its
+//! `local_content` — both mirrored by the collect handler's `on_update` as the
+//! list pipeline lands. [`notify_row_changed`](PreviewNotifier::notify_row_changed)
+//! covers those: it re-runs the selected row's preview (whatever tab is showing)
+//! when that row's live data changes, so e.g. the `pr` tab flips from "Fetching
+//! PR status…" to the resolved PR on its own.
+//!
+//! ## Why recording happens before the cache read
+//!
+//! `*SkimItem::preview` calls `note_awaiting` *before* it reads the cache. That
+//! ordering is what makes the hand-off race-free: if the read misses (the
+//! placeholder is returned), the fill that satisfies it necessarily completes
+//! *after* that read, so it observes the awaited key already set and notifies.
+//! The fill can't slip into the gap between "miss" and "record" because the
+//! record precedes the read.
+
+use std::sync::{Arc, Mutex, OnceLock};
+
+use skim::prelude::Event;
+use tokio::sync::mpsc::Sender;
+
+use super::items::PreviewCacheKey;
+use super::preview::PreviewMode;
+
+/// Bridges a background [`PreviewCache`](super::items::PreviewCache) fill to
+/// skim's event loop. See the module docstring for the full contract.
+///
+/// One instance is shared (via `Arc`) for the picker session: the
+/// [`PreviewOrchestrator`](super::preview_orchestrator::PreviewOrchestrator) owns
+/// it and notifies on every fill; the skim items hold a clone and record their
+/// awaited preview on every render.
+pub(super) struct PreviewNotifier {
+ /// skim's event sender, published once `Skim::init_tui` has run (the same
+ /// `OnceLock` the progressive handler pushes `Event::Render` through).
+ /// `None` until then — an early fill (the speculative warm-up before skim is
+ /// up) simply doesn't notify, which is harmless because skim hasn't rendered
+ /// a preview that could strand yet.
+ render_tx: Arc<OnceLock<Sender<Event>>>,
+ /// The `(row-key, mode)` the selected row's preview is currently showing or
+ /// awaiting. Written by `*SkimItem::preview` on every render; read on each
+ /// background fill. The row-key is the branch name for worktree rows and the
+ /// `pr:{N}` / `mr:{N}` token for `--prs` rows — exactly the
+ /// [`PreviewCacheKey`] string, so a fill's key compares directly.
+ awaiting: Mutex<Option<PreviewCacheKey>>,
+}
+
+impl PreviewNotifier {
+ pub(super) fn new(render_tx: Arc<OnceLock<Sender<Event>>>) -> Self {
+ Self {
+ render_tx,
+ awaiting: Mutex::new(None),
+ }
+ }
+
+ /// Record the `(row-key, mode)` the selected row is rendering, so a matching
+ /// background fill knows to surface itself. Called from `*SkimItem::preview`
+ /// before it reads the cache (see the module docstring on ordering).
+ pub(super) fn note_awaiting(&self, row_key: &str, mode: PreviewMode) {
+ *self.awaiting.lock().unwrap() = Some((row_key.to_string(), mode));
+ }
+
+ /// Inject an `Event::RunPreview` if `key` is the preview the selected row is
+ /// awaiting, so the just-filled content paints without a keystroke. A no-op
+ /// when the key isn't the visible one (an off-screen or other-tab fill) or
+ /// skim's sender isn't published yet. For the orchestrator's per-mode cache
+ /// fills (diff / log / comments / summary).
+ pub(super) fn notify_filled(&self, key: &PreviewCacheKey) {
+ if self.awaiting.lock().unwrap().as_ref() == Some(key) {
+ self.poke();
+ }
+ }
+
+ /// Inject an `Event::RunPreview` if the selected row is `row_key` on *any*
+ /// tab, so a change to that row's live data re-renders its preview without a
+ /// keystroke. Unlike [`Self::notify_filled`] this matches the row regardless
+ /// of mode, because the data it covers feeds several panes at once: the
+ /// collect handler's `on_update` mirrors the live `pr_status` (the `pr` /
+ /// `comments` panes) and `local_content` (the diff tabs' dim state), none of
+ /// which is an orchestrator cache fill.
+ pub(super) fn notify_row_changed(&self, row_key: &str) {
+ if self
+ .awaiting
+ .lock()
+ .unwrap()
+ .as_ref()
+ .is_some_and(|(k, _)| k == row_key)
+ {
+ self.poke();
+ }
+ }
+
+ /// Push a `RunPreview` onto skim's event loop so it re-reads the selected
+ /// row's preview. A no-op before skim's sender is published (the speculative
+ /// warm-up before the TUI is up).
+ fn poke(&self) {
+ if let Some(tx) = self.render_tx.get() {
+ let _ = tx.try_send(Event::RunPreview);
+ }
+ }
+
+ /// A notifier with no event sender — used by tests that build skim items or
+ /// an orchestrator without a live TUI. `notify_filled` is then a no-op.
+ #[cfg(test)]
+ pub(super) fn detached() -> Arc<Self> {
+ Arc::new(Self::new(Arc::new(OnceLock::new())))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// `notify_row_changed` re-runs the selected row's preview on *any* tab when
+ /// that row's live data lands (the `on_update` path), and stays silent for
+ /// other rows — so a CI-status / diff-content update surfaces on the visible
+ /// row without thrashing off-screen ones. (`notify_filled`'s exact-key
+ /// scoping is covered by the orchestrator's `fill_notifies_only_awaited_key`.)
+ #[test]
+ fn notify_row_changed_pokes_only_the_selected_row() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<Event>(8);
+ let render_tx = Arc::new(OnceLock::new());
+ render_tx.set(tx).unwrap();
+ let notifier = PreviewNotifier::new(render_tx);
+
+ // The selected row is on the `pr` tab (still "Fetching PR status…").
+ notifier.note_awaiting("feature", PreviewMode::Pr);
+
+ // That row's CI status lands → re-run, even though the awaited tab (Pr)
+ // isn't an orchestrator-filled mode.
+ notifier.notify_row_changed("feature");
+ assert!(
+ matches!(rx.try_recv(), Ok(Event::RunPreview)),
+ "the selected row's update re-runs its preview"
+ );
+
+ // A different row's update injects nothing.
+ notifier.notify_row_changed("other");
+ assert!(
+ rx.try_recv().is_err(),
+ "an off-screen row's update doesn't thrash the visible preview"
+ );
+ }
+}
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index 9c6a38bf7..6d3a987a7 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -16,15 +16,18 @@
//! all spawned tasks to complete before reading the cache. The picker
//! entry point (`handle_picker`) uses this for its real spawns.
-use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, OnceLock};
use std::time::Duration;
use dashmap::DashMap;
+use skim::prelude::Event;
+use tokio::sync::mpsc::Sender;
use worktrunk::git::Repository;
use super::items::{PreviewCache, PreviewCacheKey, WorktreeSkimItem};
use super::preview::PreviewMode;
+use super::preview_notify::PreviewNotifier;
use super::summary;
use crate::commands::list::collect::COLLECT_POOL;
use crate::commands::list::model::ListItem;
@@ -56,6 +59,10 @@ impl Drop for PendingGuard {
pub(super) struct PreviewOrchestrator {
pub(super) cache: PreviewCache,
pending: Arc<AtomicUsize>,
+ /// Bridges each fill to skim's event loop so a finished compute surfaces
+ /// without a keystroke (see [`PreviewNotifier`]). Shared with the skim
+ /// items, which record their awaited preview; every fill site here notifies.
+ notifier: Arc<PreviewNotifier>,
/// Repository used by preview compute. Captured once at construction
/// so background tasks see a stable repo binding, and so unit tests
/// can inject a `TestRepo`-rooted `Repository` instead of relying on
@@ -70,10 +77,11 @@ pub(super) struct PreviewOrchestrator {
}
impl PreviewOrchestrator {
- pub(super) fn new(repo: Repository) -> Self {
+ pub(super) fn new(repo: Repository, render_tx: Arc<OnceLock<Sender<Event>>>) -> Self {
Self {
cache: Arc::new(DashMap::new()),
pending: Arc::new(AtomicUsize::new(0)),
+ notifier: Arc::new(PreviewNotifier::new(render_tx)),
repo,
}
}
@@ -85,6 +93,29 @@ impl PreviewOrchestrator {
&self.repo
}
+ /// The shared preview notifier, handed to each skim item so its `preview()`
+ /// can record what it's awaiting (see [`PreviewNotifier`]).
+ pub(super) fn notifier(&self) -> &Arc<PreviewNotifier> {
+ &self.notifier
+ }
+
+ /// Insert a computed preview into the cache and surface it if the selected
+ /// row is awaiting exactly this key. The single fill path: every background
+ /// producer routes through this (or the `&self` [`Self::fill_external`]) so a
+ /// finished compute can never reach the cache without giving skim the chance
+ /// to repaint it.
+ fn fill(cache: &PreviewCache, notifier: &PreviewNotifier, key: PreviewCacheKey, value: String) {
+ cache.insert(key.clone(), value);
+ notifier.notify_filled(&key);
+ }
+
+ /// [`Self::fill`] for callers that hold the orchestrator rather than the
+ /// captured `cache` / `notifier` clones — the `--prs` comments path's
+ /// synchronous "unsupported forge" pane.
+ pub(super) fn fill_external(&self, key: PreviewCacheKey, value: String) {
+ Self::fill(&self.cache, &self.notifier, key, value);
+ }
+
/// Spawn a preview compute task. Returns immediately.
///
/// Idempotent on the cache key: if another task already populated it,
@@ -107,6 +138,7 @@ impl PreviewOrchestrator {
dims: (usize, usize),
) {
let cache = Arc::clone(&self.cache);
+ let notifier = Arc::clone(&self.notifier);
let (w, h) = dims;
let repo = self.repo.clone();
let pending = Arc::clone(&self.pending);
@@ -117,12 +149,13 @@ impl PreviewOrchestrator {
}
let (value, log_disk_hit) =
WorktreeSkimItem::compute_and_page_preview(&repo, &item, mode, w, h);
- cache.insert(cache_key, value);
+ Self::fill(&cache, &notifier, cache_key, value);
if log_disk_hit {
pending.fetch_add(1, Ordering::SeqCst);
let guard = PendingGuard(Arc::clone(&pending));
let item = Arc::clone(&item);
let cache = Arc::clone(&cache);
+ let notifier = Arc::clone(&notifier);
let repo = repo.clone();
rayon::spawn_fifo(move || {
let _g = guard;
@@ -131,7 +164,12 @@ impl PreviewOrchestrator {
// doesn't poison the in-memory cache with "" and wipe
// out the value the producer just inserted.
if !rendered.is_empty() {
- cache.insert((item.branch_name().to_string(), PreviewMode::Log), rendered);
+ Self::fill(
+ &cache,
+ &notifier,
+ (item.branch_name().to_string(), PreviewMode::Log),
+ rendered,
+ );
}
});
}
@@ -141,8 +179,15 @@ impl PreviewOrchestrator {
/// Spawn an LLM summary task. Returns immediately.
pub(super) fn spawn_summary(&self, item: Arc<ListItem>, llm_command: String, repo: Repository) {
let cache = Arc::clone(&self.cache);
+ let notifier = Arc::clone(&self.notifier);
self.spawn_task(move || {
- summary::generate_and_cache_summary(&item, &llm_command, &cache, &repo);
+ let summary = summary::generate_summary_for_item(&item, &llm_command, &repo);
+ Self::fill(
+ &cache,
+ &notifier,
+ (item.branch_name().to_string(), PreviewMode::Summary),
+ summary,
+ );
});
}
@@ -171,6 +216,7 @@ impl PreviewOrchestrator {
F: FnOnce(&Repository) -> Option<String> + Send + 'static,
{
let cache = Arc::clone(&self.cache);
+ let notifier = Arc::clone(&self.notifier);
let repo = self.repo.clone();
self.spawn_task(move || {
if cache.contains_key(&key) {
@@ -179,7 +225,7 @@ impl PreviewOrchestrator {
if let Some(value) = compute(&repo)
&& !value.is_empty()
{
- cache.insert(key, value);
+ Self::fill(&cache, &notifier, key, value);
}
});
}
@@ -328,7 +374,9 @@ mod tests {
use worktrunk::testing::TestRepo;
fn orch_for(t: &TestRepo) -> PreviewOrchestrator {
- PreviewOrchestrator::new(Repository::at(t.path()).unwrap())
+ // No render_tx published, so fills don't notify — these tests assert on
+ // the cache, not on skim repaints (see `fill_notifies_only_awaited_key`).
+ PreviewOrchestrator::new(Repository::at(t.path()).unwrap(), Arc::new(OnceLock::new()))
}
fn dirty_worktree_item() -> (TestRepo, Arc<ListItem>) {
@@ -553,6 +601,46 @@ mod tests {
);
}
+ /// A fill injects an `Event::RunPreview` exactly when the selected row is
+ /// awaiting that key, and nothing otherwise — the "surface a finished
+ /// compute, but don't thrash off-screen rows" contract. Drives the notifier
+ /// through a real `tokio` channel as skim's event sender so the assertion is
+ /// on the injected event, not the cache.
+ #[test]
+ fn fill_notifies_only_awaited_key() {
+ let t = TestRepo::new();
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<Event>(8);
+ let render_tx = Arc::new(OnceLock::new());
+ render_tx.set(tx).unwrap();
+ let orch = PreviewOrchestrator::new(Repository::at(t.path()).unwrap(), render_tx);
+
+ // The selected row is showing main's working-tree diff (a cache miss, so
+ // it's awaiting that key).
+ orch.notifier()
+ .note_awaiting("main", PreviewMode::WorkingTree);
+
+ // The awaited compute lands → skim is poked to repaint.
+ orch.fill_external(
+ ("main".to_string(), PreviewMode::WorkingTree),
+ "diff".to_string(),
+ );
+ assert!(
+ matches!(rx.try_recv(), Ok(Event::RunPreview)),
+ "the awaited fill injects a RunPreview"
+ );
+
+ // Fills for other rows / other tabs must not poke — no preview thrash.
+ orch.fill_external(
+ ("feature".to_string(), PreviewMode::WorkingTree),
+ "x".to_string(),
+ );
+ orch.fill_external(("main".to_string(), PreviewMode::Log), "y".to_string());
+ assert!(
+ rx.try_recv().is_err(),
+ "an off-screen / other-tab fill injects nothing"
+ );
+ }
+
#[test]
fn cache_entries_json_format() {
let t = TestRepo::new();
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 0e0238e2c..00e63a67d 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -357,6 +357,7 @@ impl PickerProgressHandler for PickerHandler {
summaries_enabled,
pr_status: pr_status_arc,
local_content: local_content_arc,
+ notifier: Arc::clone(self.orchestrator.notifier()),
}) as Arc<dyn SkimItem>);
}
@@ -440,6 +441,17 @@ impl PickerProgressHandler for PickerHandler {
// `comments` background fetch (once per row) so the `comments` tab loads
// the thread — the same fetch a `--prs` row makes.
self.maybe_spawn_comments(idx, item.branch_name(), &item.pr_status);
+ // `request_render` sends `Event::Render`, which repaints the *list* row
+ // (its CI/status cells just changed) but does NOT re-run the preview.
+ // The slots just mirrored — `pr_status` (the `pr` / `comments` panes) and
+ // `local_content` (the diff tabs' dim state) — feed the preview, so if
+ // this is the selected row also poke a `RunPreview` to re-render it:
+ // that's what flips its `pr` tab from "Fetching PR status…" to the
+ // resolved PR without a keystroke. Scoped to the selected row, so
+ // off-screen updates don't thrash the preview (see `PreviewNotifier`).
+ self.orchestrator
+ .notifier()
+ .notify_row_changed(item.branch_name());
self.request_render(false);
}
@@ -486,7 +498,10 @@ mod tests {
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()));
+ let orchestrator = Arc::new(PreviewOrchestrator::new(
+ test.repo.clone(),
+ Arc::new(OnceLock::new()),
+ ));
let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
let handler = PickerHandler {
tx,
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
index 790c12a6a..35b3e5ecc 100644
--- a/src/commands/picker/prs.rs
+++ b/src/commands/picker/prs.rs
@@ -63,6 +63,7 @@ use super::items::{
};
use super::pr_pane;
use super::preview::{PreviewMode, PreviewStateData};
+use super::preview_notify::PreviewNotifier;
use super::preview_orchestrator::PreviewOrchestrator;
/// One-shot handoff of the picker's column geometry from the collect thread
@@ -291,6 +292,7 @@ fn fetch_and_stream(
layout.list_width,
grid.as_ref(),
&orchestrator.cache,
+ orchestrator.notifier(),
)) as Arc<dyn SkimItem>
})
.collect();
@@ -392,7 +394,7 @@ pub(super) fn spawn_worktree_comments_fetch(
Some(CiPlatform::GitHub) => RefKind::Pr,
Some(CiPlatform::GitLab) => RefKind::Mr,
_ => {
- orchestrator.cache.insert(
+ orchestrator.fill_external(
(branch, PreviewMode::Comments),
comments_unsupported_forge_pane(),
);
@@ -660,9 +662,13 @@ pub(super) struct PrSkimItem {
/// Shared preview cache (same map the worktree rows use), read by the
/// deferred `log` tab. Keyed by `(output_token, mode)`; the background
/// fetch spawned in [`spawn_pr_previews`] populates it off-thread, and a
- /// miss falls back to a loading placeholder (skim re-queries on the next
- /// selection/tab change).
+ /// miss falls back to a loading placeholder (auto-surfaced once the fetch
+ /// lands — see `notifier`).
preview_cache: PreviewCache,
+ /// Surfaces a deferred-tab fetch without a keystroke. `preview()` records
+ /// the row's awaited `(output_token, mode)` here; the orchestrator pokes a
+ /// repaint when that tab's background fetch lands (see [`PreviewNotifier`]).
+ notifier: Arc<PreviewNotifier>,
}
impl PrSkimItem {
@@ -671,6 +677,7 @@ impl PrSkimItem {
list_width: usize,
grid: Option<&ColumnGrid>,
preview_cache: &PreviewCache,
+ notifier: &Arc<PreviewNotifier>,
) -> Self {
let label = entry.kind.shortcut();
let output_token = entry.output_token();
@@ -725,6 +732,7 @@ impl PrSkimItem {
output_token,
pr_pane,
preview_cache: Arc::clone(preview_cache),
+ notifier: Arc::clone(notifier),
}
}
@@ -752,25 +760,24 @@ fn pr_row_empty_placeholder() -> String {
}
/// Placeholder for a deferred forge-fetch tab while its background fetch is still
-/// in flight. skim can't re-query a preview on its own, so the hint points at the
-/// accelerator that re-reads the cache once the fetch lands — the same contract
-/// as the worktree rows' `loading_placeholder`. Shown only during the in-flight
-/// window: once the fetch resolves, a terminal pane replaces it — the rendered
-/// content or [`pr_unavailable_pane`] on failure — so it never persists past the
-/// fetch. Shared with worktree rows' `comments` tab (see
+/// in flight. The pane fills in on its own once the fetch lands — the orchestrator
+/// pokes a repaint for the awaited tab (see [`PreviewNotifier`]) — so the
+/// placeholder just states what's loading, the same contract as the worktree
+/// rows' `loading_placeholder`. Shown only during the in-flight window: once the
+/// fetch resolves, a terminal pane replaces it — the rendered content or
+/// [`pr_unavailable_pane`] on failure — so it never persists past the fetch.
+/// Shared with worktree rows' `comments` tab (see
/// [`super::items::WorktreeSkimItem::render_comments_pane`]) so both row types
/// show the identical in-flight pane.
pub(super) fn pr_deferred_loading(mode: PreviewMode) -> String {
let reset = Reset;
- let (label, key) = match mode {
- PreviewMode::Log => ("commit log", 2u8),
- PreviewMode::Comments => ("comments", 7u8),
+ let label = match mode {
+ PreviewMode::Log => "commit log",
+ PreviewMode::Comments => "comments",
// Only the deferred tabs reach here; other modes render synchronously.
- _ => ("preview", mode as u8),
+ _ => "preview",
};
- cformat!(
- "{INFO_SYMBOL}{reset} Loading {label}… press <bold>alt-{key}</>{reset} again to refresh\n"
- )
+ cformat!("{INFO_SYMBOL}{reset} Loading {label}…\n")
}
/// Terminal pane for a `--prs` deferred tab whose background fetch failed (forge
@@ -1208,6 +1215,11 @@ impl SkimItem for PrSkimItem {
// show a placeholder. The active tab is the same global digit, so an
// empty tab shows its placeholder until the user switches with alt-N / Tab.
let mode = PreviewStateData::read_mode();
+ // Record what this (selected) row is showing before reading the cache, so
+ // a deferred-tab fetch that lands after a miss pokes a repaint (see
+ // `PreviewNotifier`). Keyed by the row's `output_token`, matching the
+ // cache key the fetch fills.
+ self.notifier.note_awaiting(&self.output_token, mode);
let mut result = render_preview_tabs(mode, TabAvailability::listed_pr(), context.width);
match mode {
PreviewMode::Pr => result.push_str(&self.pr_pane),
@@ -1226,7 +1238,13 @@ mod tests {
/// Build a `PrSkimItem` with a throwaway empty preview cache — the deferred
/// `log` tab is exercised separately (see `log_tab_reads_cache_then_placeholder`).
fn pr_item(entry: PrEntry, list_width: usize, grid: Option<&ColumnGrid>) -> PrSkimItem {
- PrSkimItem::new(entry, list_width, grid, &Arc::new(DashMap::new()))
+ PrSkimItem::new(
+ entry,
+ list_width,
+ grid,
+ &Arc::new(DashMap::new()),
+ &PreviewNotifier::detached(),
+ )
}
fn entry(kind: RefKind, number: u32, title: &str) -> PrEntry {
@@ -1687,7 +1705,7 @@ mod tests {
let test = worktrunk::testing::TestRepo::with_initial_commit();
let (tx, _rx): (SkimItemSender, SkimItemReceiver) = unbounded();
let warnings = Mutex::new(Vec::new());
- let orchestrator = PreviewOrchestrator::new(test.repo.clone());
+ let orchestrator = PreviewOrchestrator::new(test.repo.clone(), Arc::new(OnceLock::new()));
let loading = AtomicBool::new(true);
let shared = PrsShared {
grid_slot: Arc::new(GridSlot::new()),
@@ -1832,11 +1850,16 @@ mod tests {
// alt-2); once the background fetch lands a value under that key, the
// pane shows it.
let cache: PreviewCache = Arc::new(DashMap::new());
- let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "t"), 120, None, &cache);
+ let pr = PrSkimItem::new(
+ entry(RefKind::Pr, 42, "t"),
+ 120,
+ None,
+ &cache,
+ &PreviewNotifier::detached(),
+ );
let miss = pr.cached_pane(PreviewMode::Log);
assert!(miss.contains("Loading commit log"), "miss: {miss:?}");
- assert!(miss.contains("alt-2"), "refresh hint: {miss:?}");
cache.insert(
("pr:42".to_string(), PreviewMode::Log),
@@ -1954,11 +1977,16 @@ mod tests {
// keyed by the row's output token, with a loading placeholder (pointing
// at alt-7) on a miss.
let cache: PreviewCache = Arc::new(DashMap::new());
- let pr = PrSkimItem::new(entry(RefKind::Mr, 7, "t"), 120, None, &cache);
+ let pr = PrSkimItem::new(
+ entry(RefKind::Mr, 7, "t"),
+ 120,
+ None,
+ &cache,
+ &PreviewNotifier::detached(),
+ );
let miss = pr.cached_pane(PreviewMode::Comments);
assert!(miss.contains("Loading comments"), "miss: {miss:?}");
- assert!(miss.contains("alt-7"), "refresh hint: {miss:?}");
cache.insert(
("mr:7".to_string(), PreviewMode::Comments),
@@ -1971,10 +1999,10 @@ mod tests {
fn unavailable_pane_reads_as_a_clear_failure() {
// A failed deferred fetch caches this terminal pane instead of leaving
// the slot empty, so the tab shows a clear "couldn't load" rather than
- // `pr_deferred_loading`'s spinner forever. It names the tab, drops the
- // "press alt-N again" refresh hint (there's no in-session retry — only
- // reopening the picker re-fetches), and carries the warning glyph that
- // sets it apart from the benign info states ("No commits"/"No comments").
+ // `pr_deferred_loading`'s "Loading…" forever (there's no in-session retry
+ // — only reopening the picker re-fetches). It names the tab and carries
+ // the warning glyph that sets it apart from the benign info states
+ // ("No commits"/"No comments").
let pane = pr_unavailable_pane("commit log");
let stripped = plain(&pane);
assert!(
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__cache_miss.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__cache_miss.snap
index b64ea15a7..807e87907 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__cache_miss.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__cache_miss.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "cache_miss.preview_for_mode(PreviewMode::Summary, 80, 40)"
---
-○ Generating summary. Press alt-5 again to refresh.
+○ Generating summary…
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_branch_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_branch_diff.snap
index 36ead70a8..34c91b1c9 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_branch_diff.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_branch_diff.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "WorktreeSkimItem::loading_placeholder(mode)"
---
-○ Loading branch diff. Press alt-3 again to refresh.
+○ Loading branch diff…
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_log.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_log.snap
index 99d67fdcf..78ed396d5 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_log.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_log.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "WorktreeSkimItem::loading_placeholder(mode)"
---
-○ Loading log. Press alt-2 again to refresh.
+○ Loading log…
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_summary.snap
index d225d24b1..16ccca393 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_summary.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_summary.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "WorktreeSkimItem::loading_placeholder(mode)"
---
-○ Generating summary. Press alt-5 again to refresh.
+○ Generating summary…
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_upstream_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_upstream_diff.snap
index 7a5ef5308..c9cdf5abc 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_upstream_diff.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_upstream_diff.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "WorktreeSkimItem::loading_placeholder(mode)"
---
-○ Loading upstream diff. Press alt-4 again to refresh.
+○ Loading upstream diff…
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_working_tree.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_working_tree.snap
index c615d1bb2..ff593a5e1 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_working_tree.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_working_tree.snap
@@ -2,4 +2,4 @@
source: src/commands/picker/items.rs
expression: "WorktreeSkimItem::loading_placeholder(mode)"
---
-○ Loading working-tree diff. Press alt-1 again to refresh.
+○ Loading working-tree diff…
diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rs
index 1275517a4..fb33ae6ae 100644
--- a/src/commands/picker/summary.rs
+++ b/src/commands/picker/summary.rs
@@ -3,12 +3,9 @@
//! Thin adapter over `crate::summary` that adds TUI-specific rendering
//! and integrates with the selector's preview cache.
-use dashmap::DashMap;
use worktrunk::git::Repository;
use super::super::list::model::ListItem;
-use super::items::PreviewCacheKey;
-use super::preview::PreviewMode;
/// Render LLM summary for terminal display using the project's markdown theme.
///
@@ -34,21 +31,23 @@ pub(super) fn render_summary(text: &str, width: usize) -> String {
crate::md_help::render_markdown_in_help_with_width(&markdown, Some(width))
}
-/// Generate a summary for one item and insert it into the preview cache.
+/// Generate the Summary-tab pane for one item.
+///
+/// The caller (`PreviewOrchestrator::spawn_summary`) inserts the result into the
+/// shared preview cache through the orchestrator's one fill path, so a finished
+/// summary surfaces in the picker without a keystroke like any other background
+/// preview.
///
/// `generate_summary_core` acquires `LLM_SEMAPHORE` internally, so the
/// no-changes and cache-hit fast paths return without contending.
-pub(super) fn generate_and_cache_summary(
+pub(super) fn generate_summary_for_item(
item: &ListItem,
llm_command: &str,
- preview_cache: &DashMap<PreviewCacheKey, String>,
repo: &Repository,
-) {
+) -> String {
let branch = item.branch_name();
let worktree_path = item.worktree_data().map(|d| d.path.as_path());
- let summary =
- crate::summary::generate_summary(branch, item.head(), worktree_path, llm_command, repo);
- preview_cache.insert((branch.to_string(), PreviewMode::Summary), summary);
+ crate::summary::generate_summary(branch, item.head(), worktree_path, llm_command, repo)
}
#[cfg(test)]
@@ -611,20 +610,13 @@ mod tests {
}
#[test]
- fn test_generate_and_cache_summary_populates_cache() {
+ fn test_generate_summary_for_item_renders_llm_output() {
let (t, repo, head) = temp_repo_with_feature();
let item = feature_item(&head, t.path());
- let cache: DashMap<PreviewCacheKey, String> = DashMap::new();
- generate_and_cache_summary(
- &item,
- "cat >/dev/null && echo 'Add new file'",
- &cache,
- &repo,
- );
+ let summary =
+ generate_summary_for_item(&item, "cat >/dev/null && echo 'Add new file'", &repo);
- let key = ("feature".to_string(), PreviewMode::Summary);
- assert!(cache.contains_key(&key));
- assert_eq!(cache.get(&key).unwrap().value(), "Add new file");
+ assert_eq!(summary, "Add new file");
}
}
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index b966aca69..2cd37b478 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -62,12 +62,6 @@ const STABLE_DURATION: Duration = Duration::from_millis(500);
/// Fast polling ensures tests complete quickly when ready.
const POLL_INTERVAL: Duration = Duration::from_millis(10);
-/// How often [`send_input_awaiting_content`] re-issues a preview-tab keystroke
-/// while its expected content is still absent. Long enough to clear skim's 50ms
-/// preview debounce and give a background preview compute time to land in the
-/// cache; short enough to retry many times within [`STABILIZE_TIMEOUT`].
-const PREVIEW_REISSUE_INTERVAL: Duration = Duration::from_secs(1);
-
/// Columns that split the list and preview panels in the 120-col test terminal.
/// skim 4.x draws the │ separator at col 59, with the list to its left (cols
/// 0..59) and the preview interior to its right (cols 60..120). Slicing around
@@ -451,7 +445,6 @@ fn wait_for_stable_with_content(
parser,
|screen| expected_content.is_none_or(|c| screen.contains(c)),
describe.as_deref(),
- None,
);
}
@@ -481,7 +474,6 @@ fn wait_for_cursor_on_row(rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Pars
.any(|line| line.starts_with('>') && line.contains(name))
},
Some(&describe),
- None,
);
}
@@ -501,16 +493,14 @@ fn wait_for_cursor_on_row(rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Pars
/// readiness condition there is nothing to find, so the screen must settle the
/// hard way (the cosmetic-redraw fallback never engages).
///
-/// `nudge`, when `Some`, is invoked every [`PREVIEW_REISSUE_INTERVAL`] while
-/// `ready` is unmet — used to re-issue a `RunPreview` trigger so a preview that
-/// finished computing after the initial keystroke gets surfaced (see
-/// [`send_input_awaiting_content`]).
+/// No keystroke re-issue is needed to surface late preview content: the picker
+/// repaints a preview on its own once its background compute lands (see
+/// `PreviewNotifier`), so the poll just waits for `ready` to hold.
fn wait_for_stable_until(
rx: &mpsc::Receiver<Vec<u8>>,
parser: &mut vt100::Parser,
ready: impl Fn(&str) -> bool,
describe: Option<&str>,
- nudge: Option<&dyn Fn()>,
) {
let start = Instant::now();
let mut last_change = Instant::now();
@@ -518,7 +508,6 @@ fn wait_for_stable_until(
// 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 mut last_nudge = Instant::now();
let has_condition = describe.is_some();
while start.elapsed() < STABILIZE_TIMEOUT {
@@ -560,19 +549,6 @@ fn wait_for_stable_until(
return;
}
- // While the readiness condition is still unmet, periodically re-issue the
- // RunPreview trigger. skim reads the preview cache only when it runs a
- // preview, so a diff that finished computing after the initial keystroke
- // would otherwise stay stranded behind a "Loading…" placeholder with no
- // event to surface it.
- if !content_ready
- && let Some(nudge) = nudge
- && last_nudge.elapsed() >= PREVIEW_REISSUE_INTERVAL
- {
- nudge();
- last_nudge = Instant::now();
- }
-
std::thread::sleep(POLL_INTERVAL);
}
@@ -596,35 +572,14 @@ fn wait_for_stable_until(
);
}
-/// True for an Alt-<digit> preview-tab switch (`ESC` + one ASCII digit) — the
-/// only inputs safe to re-issue while waiting for preview content. Switching to
-/// the tab you're already on is idempotent, whereas Tab / Shift-Tab cycle and
-/// typed filter text accumulates, so neither may be repeated.
-fn is_alt_digit_tab(input: &str) -> bool {
- let b = input.as_bytes();
- b.len() == 2 && b[0] == 0x1b && b[1].is_ascii_digit()
-}
-
/// Send `input`, then wait for the screen to satisfy the per-input expectation
/// and settle.
///
-/// For an Alt-<digit> preview-tab switch carrying `expected_content`, the wait
-/// re-issues the keystroke every [`PREVIEW_REISSUE_INTERVAL`] until the content
-/// appears. The picker's preview pane is served from a cache populated by
-/// background workers and is re-read only when skim runs a preview, which a
-/// keystroke triggers exactly once (`Event::RunPreview`). If the row's preview
-/// hasn't finished computing, skim paints a "Loading…" placeholder and never
-/// re-queries — the finished preview lands in the cache with no event to surface
-/// it, stranding the placeholder. That is a Windows-CI flake under load, where
-/// the `git diff` / forge compute loses the race against the keystroke (the
-/// surrounding background subprocesses make it worse). Re-issuing the idempotent
-/// tab keystroke forces a fresh `RunPreview` against the now-warm cache,
-/// mirroring the placeholder's own "Press alt-N again to refresh" instruction.
-///
-/// Inputs without an Alt-<digit> shape fall back to a plain
-/// [`wait_for_stable_with_content`]: list content (rows streaming in, filter
-/// matches) repaints on every `Event::Render` and never strands, and the
-/// non-idempotent inputs (Tab, filter text, Enter) must not be repeated.
+/// `expected_content`, when set, is a substring the screen must show before the
+/// input is considered processed. Late preview content needs no special handling:
+/// the picker repaints a preview on its own once its background compute lands
+/// (see `PreviewNotifier`), so a diff or forge fetch that finishes after the
+/// keystroke surfaces without a re-issue — the poll just waits for it.
fn send_input_awaiting_content(
writer: &crate::common::pty::SharedPtyWriter,
rx: &mpsc::Receiver<Vec<u8>>,
@@ -632,26 +587,12 @@ fn send_input_awaiting_content(
input: &str,
expected_content: Option<&str>,
) {
- let send = || {
+ {
let mut w = writer.lock().unwrap();
w.write_all(input.as_bytes()).unwrap();
w.flush().unwrap();
- };
- send();
-
- match expected_content {
- Some(content) if is_alt_digit_tab(input) => {
- let describe = format!("expected content {content:?}");
- wait_for_stable_until(
- rx,
- parser,
- |screen| screen.contains(content),
- Some(&describe),
- Some(&send),
- );
- }
- _ => wait_for_stable_with_content(rx, parser, expected_content),
}
+ wait_for_stable_with_content(rx, parser, expected_content);
}
/// Create insta settings with filters for switch picker snapshot stability.
@@ -1237,6 +1178,14 @@ fn mock_forge_env(
.command("_default", MockResponse::exit(1))
.write(&mock_bin);
+ forge_mock_env_vars(repo, &mock_bin)
+}
+
+/// Env vars (mock-bin on PATH + `MOCK_CONFIG_DIR`) for a PTY `wt` run that should
+/// resolve `gh`/`glab` to a mock written into `mock_bin`. Shared by
+/// [`mock_forge_env`] and tests that build a richer mock (extra `pr view`
+/// responses) directly.
+fn forge_mock_env_vars(repo: &TestRepo, mock_bin: &Path) -> Vec<(String, String)> {
let mut env_vars = repo.test_env_vars();
env_vars.push((
"MOCK_CONFIG_DIR".to_string(),
@@ -1247,7 +1196,7 @@ fn mock_forge_env(
// `gh.exe`/`glab.exe` is never found and the `--prs` fetch silently no-ops.
// `configure_pty_command` sets `PATH` (uppercase), which this entry overrides.
let base_path = std::env::var_os("PATH").unwrap_or_default();
- let mut paths = vec![mock_bin.clone()];
+ let mut paths = vec![mock_bin.to_path_buf()];
paths.extend(std::env::split_paths(&base_path));
let joined = std::env::join_paths(paths).expect("mock-bin joins into PATH");
env_vars.push(("PATH".to_string(), joined.to_string_lossy().into_owned()));
@@ -1341,6 +1290,73 @@ fn test_switch_picker_prs_gitlab_list(mut repo: TestRepo) {
);
}
+/// 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
+/// delay, so when the row is selected and the comments tab is opened the pane is
+/// still on its "Loading comments…" placeholder. The comment then surfaces with
+/// no further input once the delayed fetch resolves and the orchestrator pokes a
+/// repaint (`PreviewNotifier`). Before that product-side poke the placeholder
+/// would strand until the next keystroke — the gap the picker's test harness
+/// used to paper over by re-issuing the tab key.
+#[rstest]
+fn test_switch_picker_preview_auto_refreshes_when_compute_lands(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ // The mock holds `gh pr view` (the comments / log fetch) long enough that the
+ // tab is reliably opened before the fetch resolves — so the pane is observed
+ // mid-load and the appearance of the comment proves the auto-refresh, not a
+ // cache hit. `pr list` is instant so the row lands promptly.
+ let mock_bin = repo.root_path().join("mock-bin");
+ std::fs::create_dir_all(&mock_bin).unwrap();
+ // A short head branch so it isn't truncated in the narrow (preview-shown)
+ // list pane — the test gates on its full text to confirm the row rendered.
+ let pr_json = r#"[{"number":42,"title":"Retry the flaky network test","headRefName":"flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42","body":"body"}]"#;
+ std::fs::write(mock_bin.join("pr_list.json"), pr_json).unwrap();
+ let comments_json = r#"{"comments":[{"author":{"login":"octocat"},"body":"AUTOREFRESHMARK","createdAt":"2025-01-01T00:00:00Z"}]}"#;
+ MockConfig::new("gh")
+ .version("gh version 1.0.0 (mock)")
+ .command("pr list", MockResponse::file("pr_list.json"))
+ .command(
+ "pr view",
+ MockResponse::output(comments_json).with_delay_ms(3000),
+ )
+ .command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+ let env_vars = forge_mock_env_vars(&repo, &mock_bin);
+
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--prs"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ // Wait for the PR row to stream into the list (its head branch shows
+ // in the Branch column), then move the cursor onto it (its preview is
+ // the "not checked out locally" pane), then open the comments tab.
+ ("", Some("flaky")),
+ ("\x1b[B", Some("Not checked out")),
+ // alt-7: comments tab. The fetch is still in flight, so the pane shows
+ // "Loading comments…"; the comment appears with NO further input once
+ // the delayed fetch lands and the picker repaints on its own.
+ ("\x1b7", Some("AUTOREFRESHMARK")),
+ ],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+ let (_list, preview) = result.panels();
+ assert!(
+ preview.contains("AUTOREFRESHMARK"),
+ "comment surfaced on its own once the delayed fetch landed:\n{preview}"
+ );
+}
+
/// `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
@@ -1497,6 +1513,63 @@ fn test_switch_picker_worktree_row_comments_tab_shows_thread(mut repo: TestRepo)
);
}
+/// The `pr` tab auto-resolves from "Fetching PR status…" to the live PR with no
+/// keystroke. A worktree row's CI status is fetched live (`gh pr list --head`),
+/// mocked behind a delay and left UNSEEDED so the tab is observed mid-fetch; when
+/// the status lands, `on_update` pokes a `RunPreview` (`PreviewNotifier`) and the
+/// pane re-renders. Distinct producer from
+/// `test_switch_picker_preview_auto_refreshes_when_compute_lands` (an orchestrator
+/// cache fill): here it's the CI fetch surfaced through `on_update`.
+#[rstest]
+fn test_switch_picker_pr_tab_auto_resolves_from_fetching(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ let mock_bin = repo.root_path().join("mock-bin");
+ std::fs::create_dir_all(&mock_bin).unwrap();
+ // The per-row CI fetch (`gh pr list --head <branch>`), delayed so the `pr`
+ // tab is opened while still "Fetching PR status…"; unseeded, so it starts
+ // there rather than resolving at skeleton from the cache.
+ let pr_list_json = r#"[{"number":654,"title":"PRTABMARK auto-resolve","body":"","comments":[],"statusCheckRollup":[],"url":"https://github.com/owner/test-repo/pull/654","isDraft":false}]"#;
+ std::fs::write(mock_bin.join("pr_list.json"), pr_list_json).unwrap();
+ MockConfig::new("gh")
+ .version("gh version 1.0.0 (mock)")
+ .command(
+ "pr list",
+ MockResponse::file("pr_list.json").with_delay_ms(3000),
+ )
+ .command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+ let env_vars = forge_mock_env_vars(&repo, &mock_bin);
+
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ // alt-6: the `pr` tab. The CI fetch is still in flight (delayed), so
+ // the pane shows the fetching hint.
+ ("\x1b6", Some("Fetching PR status")),
+ // No further input: the resolved PR title appears on its own once the
+ // delayed CI fetch lands and the picker repaints.
+ ("", Some("PRTABMARK")),
+ ],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+ let (_list, preview) = result.panels();
+ assert!(
+ preview.contains("PRTABMARK"),
+ "pr tab resolved from 'Fetching' on its own:\n{preview}"
+ );
+}
+
#[rstest]
fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {
// Tab cycles the preview tab forward. From the default HEAD± tab (1), one