Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(picker): serve the selected preview tab on demand (#3439)
Maximilian Roos83ec4ea3f7ae
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex bedce267f..8bdcb0aac 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -29,6 +29,7 @@ use super::pr_pane;use super::preview::{PreviewMode, PreviewStateData};use super::preview_cache;use super::preview_notify::PreviewNotifier;+use super::preview_orchestrator::{PreviewDemand, SpawnGeneration};/// 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@@ -485,6 +486,21 @@ pub(super) struct PickerRow {/// renders its local-checkout tabs (working-tree, branch-diff, upstream,/// summary) as placeholders.pub(super) struct LocalCheckout {+ /// The row's snapshot `ListItem`, for the demand worker: a `preview()`+ /// cache miss on a local-git tab sends this item to [`PreviewDemand`] so+ /// the awaited tab is computed immediately instead of waiting for the+ /// precompute queue. The same frozen skeleton-time snapshot the+ /// orchestrator's precompute captures.+ pub item: Arc<ListItem>,+ /// The orchestrator's demand channel (see [`PreviewDemand`]), shared by+ /// every local row like the notifier.+ pub demand: Arc<PreviewDemand>,+ /// The spawn this row belongs to. Carried into every demand request so+ /// the channel can refuse a row an `alt-r` rebuild superseded — a+ /// pre-refresh row repainting during the reload window would otherwise+ /// re-seed the just-cleared cache from its frozen `item` (see the+ /// orchestrator's *Spawn generations* docs).+ pub spawn_gen: SpawnGeneration,/// Whether this branch has an upstream tracking ref, for the tab-4/// (remote⇅) empty state. A SYNCHRONOUS skeleton-time fact read from/// `Repository::local_branches()` at construction — never from the async@@ -581,6 +597,30 @@ impl SkimItem for PickerRow {// (branch for a worktree row, `pr:N` for a `--prs` row) so the awaited// key matches the one the background fill writes.self.notifier.note_awaiting(self.preview_key(), mode);+ // A miss on a local-git tab means the placeholder below would sit+ // until background precompute reaches this (row, mode) — in a large+ // repo, seconds. Ask the demand worker to compute it now; the fill+ // then repaints via the awaited key recorded above. A morphed row is+ // excluded like in `output()`: its frozen item still points at the+ // worktree the alt-x removal is deleting, and a compute from it+ // would cache an actively wrong pane under the kept branch. (Best+ // effort: a request parked in the instant before the morph is still+ // served from the frozen item.) A row an `alt-r` rebuild superseded+ // is refused at the channel via the spawn token it posts.+ if let Some(local) = &self.local+ && mode.is_local_git()+ && !local.morphed.load(Ordering::Relaxed)+ && !self+ .preview_cache+ .contains_key(&(self.preview_key().to_string(), mode))+ {+ local.demand.request(+ Arc::clone(&local.item),+ mode,+ (context.width, context.height),+ local.spawn_gen.clone(),+ );+ }ItemPreview::AnsiText(self.render_preview(mode, context.width, context.height))}}@@ -1790,6 +1830,25 @@ mod tests {assert_eq!(out.spans[3].style.fg, None);}+ /// A minimal `LocalCheckout` for row construction in tests: a branch-only+ /// snapshot item, a demand channel with no worker behind it (requests+ /// recorded, never served), and defaulted local signals (no upstream, no+ /// summaries, unknown diff content).+ fn test_local_checkout(branch: &str) -> LocalCheckout {+ LocalCheckout {+ item: Arc::new(ListItem::new_branch(+ "0000000".to_string(),+ branch.to_string(),+ )),+ demand: PreviewDemand::new(),+ spawn_gen: SpawnGeneration::default(),+ has_upstream: false,+ summaries_enabled: false,+ local_content: Arc::new(Mutex::new(LocalContent::default())),+ morphed: Arc::new(AtomicBool::new(false)),+ }+ }+/// Build a worktree-backed [`PickerRow`] (`local: Some`) for tests, with the/// given branch, preview cache, and live `pr_status` slot value; the local/// signals default (no upstream, no summaries, unknown diff content).@@ -1807,12 +1866,7 @@ mod tests {preview_cache,pr_status: Arc::new(Mutex::new(pr_status)),notifier: PreviewNotifier::detached(),- local: Some(LocalCheckout {- has_upstream: false,- summaries_enabled: false,- local_content: Arc::new(Mutex::new(LocalContent::default())),- morphed: Arc::new(AtomicBool::new(false)),- }),+ local: Some(test_local_checkout(branch)),}}@@ -2669,12 +2723,7 @@ mod tests {preview_cache: Arc::clone(&cache),pr_status: Arc::clone(&slot),notifier: PreviewNotifier::detached(),- local: Some(LocalCheckout {- has_upstream: false,- summaries_enabled: false,- local_content: Arc::new(Mutex::new(LocalContent::default())),- morphed: Arc::new(AtomicBool::new(false)),- }),+ local: Some(test_local_checkout("feature")),};// First render populates the shared cache.diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex a6fd2ee0b..789ceb2dc 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1278,6 +1278,13 @@ impl CommandCollector for PickerCollector {// drop and skim's reload sees EOF. The returned handler and join handles// are kept alive by those threads, so let them drop here. On a spawn// failure we fall through and re-stream the current items unchanged.+ // If the failure hit after `PreviewOrchestrator::refresh` ran (a+ // thread-spawn error — resource-exhaustion territory), those rows'+ // tokens are already superseded against a cleared cache, so their+ // previews sit on placeholders until the next successful refresh.+ // Accepted: un-bumping the generation would instead break a+ // partially-started spawn's live producers (the collect thread can+ // already be running when the `--prs` thread spawn is what failed).//// `alt-x` removal does NOT route here — it runs synchronously through// [`AltXRemover`] / [`resync_pool`] instead of a `reload`, so `refresh` is@@ -1359,12 +1366,6 @@ struct PipelineFactory {repo: Repository,render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>>,shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,- /// Monotonic spawn counter. Each [`spawn`](Self::spawn) bumps it and hands- /// the value to that spawn's `--prs` thread, which appends its PR/MR rows to- /// `shared_items` only while the counter still matches — so a stale forge call- /// from a pre-refresh spawn can't pollute the list a later spawn rebuilt. See- /// [`prs::PrsShared`].- prs_epoch: Arc<AtomicUsize>,shortcut_table: ShortcutTable,preview_cache: PreviewCache,orchestrator: Arc<PreviewOrchestrator>,@@ -1408,7 +1409,9 @@ impl PipelineFactory {/// relies on to end its `reload`./// `rebuild_repo` controls the worktree/branch inventory source. A refresh/// (`alt-r`) passes `true` to rebuild a fresh `Repository`, re-enumerating- /// after an in-picker removal, and to clear the in-memory preview cache so+ /// after an in-picker removal, and to run `PreviewOrchestrator::refresh` —+ /// which supersedes the prior spawn's preview producers, rebinds preview+ /// compute to the fresh repo, and clears the in-memory preview cache so/// previews recompute (see the `spawn_repo` binding, and the/// `preview_orchestrator` spec for what a refresh does and doesn't refresh)./// The initial spawn passes `false` to reuse the startup repo, whose cache@@ -1446,22 +1449,26 @@ impl PipelineFactory {// The in-memory preview cache is keyed by `(branch, mode)` with no// SHA — the working-tree diff has no stable hash to key on — so a// warm entry outlives the branch's commits or working tree moving- // and would re-serve a stale diff / log / summary. Dropping it lets- // each rebuilt row recompute against its current `item.head()` from- // the rebuilt inventory; the on-disk caches (SHA-keyed for log /- // branch-diff / upstream, diff-hash-keyed for the summary) make an- // unchanged branch a cheap re-read, so only genuinely changed content- // pays a recompute. The `pr` / `comments` tabs already self-invalidate- // on the CI path; clearing them here too just means a refresh also- // re-fetches their forge data. Precompute still runs against the- // orchestrator's startup repo, so a moved default-branch base isn't- // picked up and a narrow stale-fill race remains — see the- // `preview_orchestrator` module spec ("Refresh") for both.- self.preview_cache.clear();- Repository::at(self.repo.discovery_path())?+ // and would re-serve a stale diff / log / summary. `refresh`+ // supersedes the prior spawn's still-in-flight producers, rebinds+ // preview compute to this fresh repo, and clears the cache, so+ // each rebuilt row recomputes against its current `item.head()`+ // from the rebuilt inventory; the on-disk caches (SHA-keyed for+ // log / branch-diff / upstream, diff-hash-keyed for the summary)+ // make an unchanged branch a cheap re-read, so only genuinely+ // changed content pays a recompute. The `pr` / `comments` tabs+ // already self-invalidate on the CI path; clearing them here too+ // just means a refresh also re-fetches their forge data. See the+ // `preview_orchestrator` module spec ("Spawn generations").+ let repo = Repository::at(self.repo.discovery_path())?;+ self.orchestrator.refresh(repo.clone());+ repo} else {self.repo.clone()};+ // This spawn's identity token, carried by everything the spawn+ // starts and superseded by the next refresh (see `SpawnGeneration`).+ let spawn_gen = self.orchestrator.generation();// The skeleton→`--prs` handoff (column geometry + the branches already// shown for dedup). Fresh per spawn so an alt-r reload's `--prs` thread@@ -1486,6 +1493,7 @@ impl PipelineFactory {preview_cache: Arc::clone(&self.preview_cache),repo: spawn_repo.clone(),orchestrator: Arc::clone(&self.orchestrator),+ spawn_gen: spawn_gen.clone(),preview_dims: self.preview_dims,llm_command: self.llm_command.clone(),summary_hint: self.summary_hint.clone(),@@ -1532,18 +1540,15 @@ impl PipelineFactory {let prs_warnings = Arc::clone(&self.stashed_warnings);let prs_orchestrator = Arc::clone(&self.orchestrator);let prs_render_tx = Arc::clone(&self.render_tx);- // Bump the spawn counter and capture this spawn's value: the `--prs`- // thread appends its rows to `shared_items` only while the counter- // still matches, so an earlier spawn's still-in-flight forge call- // can't add rows to this (or a later) spawn's list. See- // `PipelineFactory::prs_epoch` and `prs::PrsShared`.- let current_epoch = self.prs_epoch.fetch_add(1, Ordering::SeqCst) + 1;let prs_shared = prs::PrsShared {grid_slot: Arc::clone(&grid_slot),shortcut_table: Arc::clone(&self.shortcut_table),shared_items: Arc::clone(&self.shared_items),- epoch: Arc::clone(&self.prs_epoch),- current_epoch,+ // This spawn's token: the thread appends its rows (and fans+ // out per-row fetches) only while it is still current, so an+ // earlier spawn's still-in-flight forge call can't add rows+ // to this (or a later) spawn's list. See `prs::PrsShared`.+ spawn_gen: spawn_gen.clone(),};let prs_layout = prs::PrsLayout {list_width: self.skim_list_width,@@ -1700,7 +1705,12 @@ pub fn handle_picker(let dims = state.initial_layout.dimensions_for(term_width, term_height, 0);- orchestrator.spawn_preview(Arc::new(item), PreviewMode::WorkingTree, dims);+ orchestrator.spawn_preview(+ &orchestrator.generation(),+ Arc::new(item),+ PreviewMode::WorkingTree,+ dims,+ );}// The picker runs every task — it is `wt list --full` (`ShowConfig::Resolved`@@ -1853,7 +1863,6 @@ summary = truerepo: repo.clone(),render_tx: Arc::clone(&render_tx),shared_items: Arc::clone(&shared_items),- prs_epoch: Arc::new(AtomicUsize::new(0)),shortcut_table: Arc::clone(&shortcut_table),preview_cache: Arc::clone(&preview_cache),orchestrator: Arc::clone(&orchestrator),@@ -2908,6 +2917,7 @@ pub mod tests {/// Build a `PickerRow` from a snapshot `ListItem`.fn picker_item(branch_name: &str, item: ListItem) -> Arc<dyn SkimItem> {+ let item = Arc::new(item);let pr_status = Arc::new(Mutex::new(item.pr_status.clone()));let output_token = worktree_output_token(&item, branch_name);Arc::new(PickerRow {@@ -2920,6 +2930,9 @@ pub mod tests {pr_status,notifier: super::preview_notify::PreviewNotifier::detached(),local: Some(LocalCheckout {+ item,+ demand: super::preview_orchestrator::PreviewDemand::new(),+ spawn_gen: super::preview_orchestrator::SpawnGeneration::default(),has_upstream: false,summaries_enabled: false,local_content: Arc::new(Mutex::new(LocalContent::default())),@@ -2993,6 +3006,9 @@ pub mod tests {pr_status: Arc::new(Mutex::new(None)),notifier: super::preview_notify::PreviewNotifier::detached(),local: Some(LocalCheckout {+ item: Arc::clone(&item_arc),+ demand: super::preview_orchestrator::PreviewDemand::new(),+ spawn_gen: super::preview_orchestrator::SpawnGeneration::default(),has_upstream: false,summaries_enabled: false,local_content: Arc::clone(&local_content),@@ -3045,7 +3061,6 @@ pub mod tests {repo,render_tx,shared_items: Arc::new(Mutex::new(Vec::new())),- prs_epoch: Arc::new(std::sync::atomic::AtomicUsize::new(0)),shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),preview_cache,orchestrator,diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex 9adf7733e..29c28dfb6 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -65,8 +65,26 @@ impl PreviewMode {pub(super) fn prev(self) -> Self {Self::from_u8(if self as u8 <= 1 { 7 } else { self as u8 - 1 })}++ /// Whether this tab is in [`LOCAL_GIT_MODES`].+ pub(super) fn is_local_git(self) -> bool {+ LOCAL_GIT_MODES.contains(&self)+ }}+/// The four tabs computed from local git alone — the one canonical set both+/// preview producers consume: the orchestrator precomputes exactly these+/// (plus summaries), and the demand worker serves them on a cache miss (see+/// `PreviewDemand`), so the two can't drift. Summary is excluded (an LLM+/// call on tab navigation would be a surprise cost); Pr and Comments+/// render/fetch through their own paths.+pub(super) const LOCAL_GIT_MODES: [PreviewMode; 4] = [+ PreviewMode::WorkingTree,+ PreviewMode::Log,+ PreviewMode::BranchDiff,+ PreviewMode::UpstreamDiff,+];+/// Typical terminal character aspect ratio (width/height).////// Terminal characters are taller than wide - typically around 0.5 (twice as tall as wide).diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex 996390ab3..7742fcbc7 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -53,30 +53,53 @@//! - **WorkingTree / Log / BranchDiff / UpstreamDiff / Summary** have *no*//! per-event in-memory invalidation. Within a session they are reconciled with//! moved content only by a refresh.-//! - **Refresh (`alt-r`)** clears the entire in-memory cache (in-//! `PipelineFactory::spawn`, gated on `rebuild_repo`). What then refreshes is-//! bounded by what the recompute sees: the rebuilt inventory gives each row a-//! current `item.head()`, so the live working-tree diff, the log, and a branch-//! whose own commits moved all recompute correctly. But precompute runs against-//! the orchestrator's *startup* repo — it's built once and shared (`Arc`),-//! never rebuilt — so values read from its `RepoCache`, notably the-//! default-branch base SHA for BranchDiff, stay at session start; a default-//! branch that moved externally isn't picked up until the picker reopens. The-//! disk tiers keep an unchanged branch cheap; only genuinely changed content-//! pays.+//! - **Refresh (`alt-r`)** calls [`PreviewOrchestrator::refresh`] (from+//! `PipelineFactory::spawn`, gated on `rebuild_repo`), which supersedes the+//! prior spawn's producers, rebinds the compute repo to the rebuilt spawn's,+//! and clears the entire in-memory cache — see *Spawn generations* below.+//! The rebuilt inventory gives each row a current `item.head()` and the+//! rebound repo a fresh `RepoCache` (notably the default-branch base SHA for+//! BranchDiff), so recompute sees current state, not session-start state.+//! The disk tiers keep an unchanged branch cheap; only genuinely changed+//! content pays.//!-//! Two known limitations follow from that once-built orchestrator: (1) the-//! stale base SHA above; (2) a narrow race — a prior spawn's still-draining-//! precompute task computes against its captured (now stale) `item.head()` and,-//! because the clear emptied the cache, *fills* it instead of short-circuiting,-//! after which the new spawn's task short-circuits on that stale entry, which-//! then persists until the next refresh. The window opens only when a refresh-//! fires while a prior spawn's precompute is still draining (large repo / slow-//! summaries) and the row's content moved in that window — the common "I edited-//! the branch I'm viewing" case doesn't hit it, since that branch's precompute-//! finished when the picker opened. The structural fix for both is to give the-//! orchestrator the current spawn's repo plus a spawn generation (mirroring-//! `prs_epoch`) so a superseded fill drops.+//! What's left unrefreshed is only the in-between: content that moves+//! mid-session without an `alt-r` waits for the next refresh (or reopen) by+//! design — the refresh *is* the reconciliation point.+//!+//! # Spawn generations+//!+//! A refresh doesn't wait for the previous spawn's producers — precompute+//! tasks still draining `COLLECT_POOL`, a `--prs` forge call in flight, a+//! demand request parked or mid-compute — and each of those holds a frozen+//! `Arc<ListItem>` whose `head()` the refresh may have made stale. Left+//! alone, such a producer would land its stale content in the just-cleared+//! cache, and the new spawn's own producer would then short-circuit on the+//! entry instead of recomputing. [`SpawnGeneration`] closes this: each+//! pipeline spawn mints a token (`PipelineFactory::spawn`), everything that+//! spawn starts carries it, and [`PreviewOrchestrator::fill`] — the one+//! insert path — drops a write whose token a later+//! [`PreviewOrchestrator::refresh`] superseded. `refresh` bumps the+//! generation *first*, then rebinds the compute repo to the new spawn's (so+//! recompute resolves bases from a fresh `RepoCache`, not session-start+//! state), then clears the cache. `fill` checks the token while holding the+//! key's shard write lock, which makes its check-and-insert atomic against+//! the bump-then-clear: a check that passes happened before the bump, so+//! the clear always lands after (and wipes) that insert, and a check after+//! the bump refuses the write — a stale fill cannot straddle the refresh.+//!+//! The same token gates every other cross-spawn effect, all enforcement+//! secondary to `fill`'s: a superseded row's demand is refused at the+//! channel ([`PreviewDemand::request`]) instead of re-seeding the cache+//! from its frozen item on every repaint; superseded queued tasks skip+//! their git/LLM compute rather than paying for doomed work; a superseded+//! `--prs` batch is dropped whole (row appends re-check inside the+//! `shared_items` lock — see `prs::PrsShared`); and a superseded skeleton+//! neither overwrites the session-shared row list / shortcut table nor+//! seeds summary hints (the one documented `fill` bypass). A superseded+//! handler's `maybe_spawn_comments` is inert for the same reason its fill+//! would drop: its *eviction* of the shared Comments entry would otherwise+//! delete the live spawn's fetch with no producer left to refill it.//!//! # Filling and surfacing//!@@ -93,6 +116,13 @@//! always recomputes — cheap, since `crate::summary` is gated by its own//! diff-hash disk cache.//!+//! Precompute is best-effort background work; the tab the user is *looking+//! at* is served by a third producer, the demand worker ([`PreviewDemand`]):+//! a `preview()` cache miss on a local-git tab posts the row's item to a+//! dedicated thread that computes just that key, off `COLLECT_POOL`, so the+//! selected tab costs its own compute rather than a position in the+//! precompute queue.+//!//! # Orchestration//!//! Routes preview tasks to the dedicated [`COLLECT_POOL`] (shared with the@@ -112,7 +142,7 @@//! entry point (`handle_picker`) uses this for its real spawns.use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, Condvar, Mutex, OnceLock};use std::time::Duration;use dashmap::DashMap;@@ -121,7 +151,7 @@ use tokio::sync::mpsc::Sender;use worktrunk::git::Repository;use super::items::{PickerRow, PreviewCache, PreviewCacheKey};-use super::preview::PreviewMode;+use super::preview::{LOCAL_GIT_MODES, PreviewMode};use super::preview_notify::PreviewNotifier;use super::summary;use crate::commands::list::collect::COLLECT_POOL;@@ -130,19 +160,12 @@ use crate::commands::list::model::ListItem;/// The picker's initial preview tab — `WorkingTree`, shown when the/// picker opens. Pre-computed for every row at skeleton time so j/k/// navigation lands on warm content without paying the 4-mode bulk cost-/// per row during the row-fill window.+/// per row during the row-fill window. The remaining [`LOCAL_GIT_MODES`]+/// for items 1..N are deferred until `spawn_deferred_precompute` fires+/// (after row drain); for the landing row they fire at skeleton time so+/// tab-cycling is responsive immediately.const INITIAL_MODE: PreviewMode = PreviewMode::WorkingTree;-/// Modes other than [`INITIAL_MODE`]. For the user's landing row (item 0)-/// these pre-compute at skeleton time alongside `INITIAL_MODE` so-/// tab-cycling is responsive immediately. For items 1..N they're-/// deferred until `spawn_deferred_precompute` fires (after row drain).-const SECONDARY_MODES: [PreviewMode; 3] = [- PreviewMode::Log,- PreviewMode::BranchDiff,- PreviewMode::UpstreamDiff,-];-struct PendingGuard(Arc<AtomicUsize>);impl Drop for PendingGuard {@@ -151,6 +174,158 @@ impl Drop for PendingGuard {}}+/// Identity of one pipeline spawn, held by everything that spawn starts —+/// precompute tasks, `--prs` fetches, demand requests, the handler, and the+/// skim rows themselves. [`PreviewOrchestrator::refresh`] supersedes all+/// outstanding tokens by bumping the shared counter; a producer whose token+/// is no longer current has its cache write dropped at+/// [`PreviewOrchestrator::fill`], its demand refused at+/// [`PreviewDemand::request`], its queued work skipped before compute, and+/// its writes to the session-shared row list / shortcut table declined — so+/// a refresh can never be undone by a stale straggler. Minted per spawn in+/// `PipelineFactory::spawn` (see the *Spawn generations* section of the+/// module docs).+#[derive(Clone)]+pub(super) struct SpawnGeneration {+ current: Arc<AtomicUsize>,+ value: usize,+}++impl SpawnGeneration {+ /// Whether the spawn this token identifies is still the live one.+ pub(super) fn is_current(&self) -> bool {+ self.current.load(Ordering::SeqCst) == self.value+ }+}++/// A generation with no refresh lifecycle behind it — nothing ever+/// supersedes it, so it is always current. For rows built outside a picker+/// session; tests building skim rows directly use this the way they use+/// [`PreviewDemand::new`].+impl Default for SpawnGeneration {+ fn default() -> Self {+ Self {+ current: Arc::new(AtomicUsize::new(0)),+ value: 0,+ }+ }+}++/// On-demand compute channel for the preview the user is looking at *right+/// now* — a one-slot, latest-wins handoff from skim's UI thread to a+/// dedicated worker thread.+///+/// Precompute alone leaves a gap: `SkimItem::preview` never computes (it only+/// reads the in-memory cache), so a tab whose precompute hasn't landed sits on+/// its loading placeholder until the background queue reaches it — behind the+/// row pipeline, its network tail (`COLLECT_POOL` workers park on blocking+/// `gh` subprocesses, and rayon has no task priorities), and the mode-major+/// deferred tier. In a large repo with many worktrees that's several seconds+/// of queue for a tab the user is staring at. The demand worker closes the+/// gap: `preview()` routes a cache miss on a local-git tab here+/// ([`PreviewMode::is_local_git`]), and the worker computes exactly that key,+/// off `COLLECT_POOL` entirely — so the looked-at tab costs one disk-cache+/// read (~ms when previously computed) or one git command, not a queue+/// position.+///+/// One slot is the point: `preview()` only ever misses on the *selected*+/// row's current tab, so the newest request supersedes any unserved one and+/// rows skimmed past are never computed. A request whose key a racing pool+/// task already filled is dropped on the worker's `contains_key` check. A+/// simultaneous double-compute — the pool task for the same key mid-flight+/// when the demand is taken — is accepted rather than tracked: it's common+/// exactly once per spawn (the landing row's default tab at first paint,+/// before its skeleton-time precompute lands) and harmless (both producers+/// route through `fill` with identical content); an in-flight key set shared+/// across producers isn't worth that one duplicate `git diff`.+pub(super) struct PreviewDemand {+ state: Mutex<DemandState>,+ cond: Condvar,+}++/// The slot plus the close flag, under the one mutex the condvar guards.+#[derive(Default)]+struct DemandState {+ request: Option<DemandRequest>,+ closed: bool,+}++/// One demand: compute `mode` for `item` at the preview pane's `dims`, on+/// behalf of the spawn identified by `spawn_gen`. Self-contained (the row hands+/// over its own `Arc<ListItem>` and spawn token), so the worker needs no item+/// registry that could drift from the rows skim holds.+struct DemandRequest {+ item: Arc<ListItem>,+ mode: PreviewMode,+ dims: (usize, usize),+ spawn_gen: SpawnGeneration,+}++impl PreviewDemand {+ /// The channel only — the orchestrator spawns the worker that drains it.+ /// Tests building skim rows without an orchestrator use this directly:+ /// requests are recorded and never served.+ pub(super) fn new() -> Arc<Self> {+ Arc::new(Self {+ state: Mutex::new(DemandState::default()),+ cond: Condvar::new(),+ })+ }++ /// Publish the selected row's awaited preview, replacing any unserved+ /// request. Called from skim's UI thread on every `preview()` cache miss,+ /// so it must stay non-blocking (a brief uncontended lock).+ ///+ /// A request whose spawn a refresh superseded is refused: after `alt-r`+ /// clears the cache, the pre-refresh rows keep missing (and posting) on+ /// every repaint until the rebuilt skeleton replaces them, and each of+ /// those computes would be dropped at `fill` anyway — refusing at the+ /// channel keeps the worker free for the live spawn's first demand.+ pub(super) fn request(+ &self,+ item: Arc<ListItem>,+ mode: PreviewMode,+ dims: (usize, usize),+ spawn_gen: SpawnGeneration,+ ) {+ let mut state = self.state.lock().unwrap();+ if state.closed || !spawn_gen.is_current() {+ return;+ }+ state.request = Some(DemandRequest {+ item,+ mode,+ dims,+ spawn_gen,+ });+ self.cond.notify_one();+ }++ /// Close the channel: the worker drains out and releases its captures.+ /// Called when the orchestrator drops (the picker is done), so the parked+ /// thread doesn't pin the preview cache and repo until process exit.+ fn close(&self) {+ self.state.lock().unwrap().closed = true;+ self.cond.notify_one();+ }++ /// Worker side: block until a request is available and take it, or+ /// return `None` once the channel is closed (a parked request is+ /// dropped — the picker is gone, nothing would read the fill).+ fn take_blocking(&self) -> Option<DemandRequest> {+ let mut state = self.state.lock().unwrap();+ loop {+ if state.closed {+ return None;+ }+ if let Some(req) = state.request.take() {+ return Some(req);+ }+ state = self.cond.wait(state).unwrap();+ }+ }+}+pub(super) struct PreviewOrchestrator {pub(super) cache: PreviewCache,pending: Arc<AtomicUsize>,@@ -158,34 +333,155 @@ pub(super) struct PreviewOrchestrator {/// 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- /// process CWD.+ /// Repository used by preview compute. Bound at construction (unit tests+ /// inject a `TestRepo`-rooted `Repository` instead of relying on process+ /// CWD) and rebound by [`Self::refresh`] to each rebuilt spawn's repo, so+ /// recompute reads a current `RepoCache` rather than session-start state.///- /// Cloned into each spawned task so they share the underlying- /// `Arc<RepoCache>` — including the memoized comparison base that- /// [`Repository::branch_diff_spec`] resolves from a single `for-each-ref`- /// scan. That shared cache is how the BranchDiff preview avoids- /// re-scanning refs per item.- repo: Repository,+ /// Cloned out of the cell into each spawned task, so one spawn's tasks+ /// share the underlying `Arc<RepoCache>` — including the memoized+ /// comparison base that [`Repository::branch_diff_spec`] resolves from a+ /// single `for-each-ref` scan. That shared cache is how the BranchDiff+ /// preview avoids re-scanning refs per item. The lock is held only for+ /// the clone, never across a compute.+ repo: Arc<Mutex<Repository>>,+ /// The live spawn's generation; [`Self::generation`] mints tokens at this+ /// value and [`Self::refresh`] bumps it to supersede them. See+ /// [`SpawnGeneration`].+ generation: Arc<AtomicUsize>,+ /// The on-demand channel serving the selected row's awaited tab (see+ /// [`PreviewDemand`]). Handed to each worktree-backed row at+ /// construction; its worker thread is spawned once here and shared+ /// across `alt-r` spawns, like the cache.+ demand: Arc<PreviewDemand>,}impl PreviewOrchestrator {pub(super) fn new(repo: Repository, render_tx: Arc<OnceLock<Sender<Event>>>) -> Self {+ let cache: PreviewCache = Arc::new(DashMap::new());+ let pending = Arc::new(AtomicUsize::new(0));+ let notifier = Arc::new(PreviewNotifier::new(render_tx));+ let demand = PreviewDemand::new();+ let repo = Arc::new(Mutex::new(repo));+ {+ let demand = Arc::clone(&demand);+ let cache = Arc::clone(&cache);+ let notifier = Arc::clone(¬ifier);+ let pending = Arc::clone(&pending);+ let repo = Arc::clone(&repo);+ // Detached worker thread: it parks on the condvar between+ // requests and exits when the orchestrator's `Drop` closes the+ // channel. Spawn failure degrades to the pre-demand behavior —+ // the tab fills when precompute reaches it.+ let _ = std::thread::Builder::new()+ .name("wt-preview-demand".into())+ .spawn(move || {+ while let Some(req) = demand.take_blocking() {+ // Read the repo cell per request, not once at spawn:+ // a refresh rebinds it, and a demand from the rebuilt+ // spawn must compute against the rebuilt repo.+ let repo = repo.lock().unwrap().clone();+ Self::serve_demand(&cache, ¬ifier, &pending, &repo, req);+ }+ });+ }Self {- cache: Arc::new(DashMap::new()),- pending: Arc::new(AtomicUsize::new(0)),- notifier: Arc::new(PreviewNotifier::new(render_tx)),+ cache,+ pending,+ notifier,repo,+ generation: Arc::new(AtomicUsize::new(0)),+ demand,+ }+ }++ /// Supersede the previous spawn's producers and rebind compute state to a+ /// rebuilt spawn's `repo`. Called from `PipelineFactory::spawn` on every+ /// `alt-r` rebuild, before the new spawn starts any producer.+ ///+ /// Order matters: the generation bump comes first, so a stale in-flight+ /// fill racing this call either lands before the clear (wiped by it) or+ /// after (dropped by [`Self::fill`]'s check) — clear-then-bump would+ /// leave a window where a stale fill lands post-clear and survives until+ /// the next refresh.+ pub(super) fn refresh(&self, repo: Repository) {+ self.generation.fetch_add(1, Ordering::SeqCst);+ *self.repo.lock().unwrap() = repo;+ self.cache.clear();+ }++ /// Mint a token for the live spawn. Everything the spawn starts carries a+ /// clone; a later [`Self::refresh`] invalidates them all at once.+ pub(super) fn generation(&self) -> SpawnGeneration {+ SpawnGeneration {+ current: Arc::clone(&self.generation),+ value: self.generation.load(Ordering::SeqCst),+ }+ }++ /// Serve one demand request: compute the awaited preview and fill the+ /// cache. The demand worker's whole loop body, factored out so each arm+ /// is unit-testable without racing the thread.+ ///+ /// Skips a key a racing pool task already filled, and a request parked+ /// across a refresh (posted while its spawn was still current, taken+ /// after it was superseded) — computing the latter would make the live+ /// spawn's first demand queue behind a git call whose fill is doomed to+ /// drop. A panicking compute is contained to its key: on a rayon worker+ /// it would abort the process, but here it would only unwind the worker+ /// thread — and a dead worker silently regresses every later navigation+ /// to queue-wait latency for the rest of the session — so log and keep+ /// serving.+ fn serve_demand(+ cache: &PreviewCache,+ notifier: &Arc<PreviewNotifier>,+ pending: &Arc<AtomicUsize>,+ repo: &Repository,+ req: DemandRequest,+ ) {+ if !req.spawn_gen.is_current() {+ return;+ }+ let key = (req.item.branch_name().to_string(), req.mode);+ if cache.contains_key(&key) {+ return;+ }+ let (w, h) = req.dims;+ let computed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ PickerRow::compute_and_page_preview(repo, &req.item, req.mode, w, h)+ }));+ let Ok((value, log_disk_hit)) = computed else {+ tracing::debug!(+ branch = key.0,+ mode = ?key.1,+ "preview demand compute panicked; leaving the tab to precompute"+ );+ return;+ };+ Self::fill(cache, notifier, &req.spawn_gen, key, value);+ if log_disk_hit {+ Self::spawn_log_refresh(+ cache,+ notifier,+ pending,+ &req.spawn_gen,+ req.item,+ repo,+ (w, h),+ );}}- /// The repository this orchestrator computes previews against. Exposed so- /// `on_skeleton` can read the cached local-branch inventory- /// (`local_branches()`) for synchronous tab-availability facts.- pub(super) fn repo(&self) -> &Repository {- &self.repo+ /// The shared demand channel, handed to each worktree-backed skim row so+ /// its `preview()` can request the awaited tab on a cache miss.+ pub(super) fn demand(&self) -> &Arc<PreviewDemand> {+ &self.demand+ }++ /// The repository the live spawn computes previews against (a clone out+ /// of the rebindable cell — see the `repo` field).+ pub(super) fn repo(&self) -> Repository {+ self.repo.lock().unwrap().clone()}/// The shared preview notifier, handed to each skim item so its `preview()`@@ -198,17 +494,46 @@ impl PreviewOrchestrator {/// 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);+ /// to repaint it — and, symmetrically, so a producer whose spawn a refresh+ /// superseded can never re-seed the just-cleared cache with stale content+ /// (the write is dropped, and nothing notifies).+ fn fill(+ cache: &PreviewCache,+ notifier: &PreviewNotifier,+ spawn_gen: &SpawnGeneration,+ key: PreviewCacheKey,+ value: String,+ ) {+ {+ // The generation check and the insert hold the key's shard write+ // lock together (`entry` acquires it), making them atomic against+ // `refresh`'s bump-then-clear: a check that passes here happened+ // before the bump, so the clear — which starts after the bump and+ // must wait for this shard lock — always runs after the insert+ // and wipes it. A plain check-then-insert would leave a third+ // interleaving (check passes pre-bump, insert lands post-clear)+ // where the stale entry survives. Compute has already finished by+ // now, so the lock spans only the check and the insert — never a+ // subprocess — keeping skim's UI-thread reads unblocked.+ let entry = cache.entry(key.clone());+ if !spawn_gen.is_current() {+ return;+ }+ entry.insert(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);+ pub(super) fn fill_external(+ &self,+ spawn_gen: &SpawnGeneration,+ key: PreviewCacheKey,+ value: String,+ ) {+ Self::fill(&self.cache, &self.notifier, spawn_gen, key, value);}/// Spawn a preview compute task. Returns immediately.@@ -219,15 +544,12 @@ impl PreviewOrchestrator {/// `preview()` synchronously and reads via `DashMap::get`) is never/// blocked on a shard write held across git/pager subprocesses.///- /// Log mode that hits the disk cache also enqueues a refresh task- /// (via `rayon::spawn_fifo`, so it lands behind in-flight foreground- /// precompute) to recompute the embedded ref decorations before the- /// next visit. The `spawn_fifo` runs from inside a `COLLECT_POOL`- /// worker, so it inherits that pool rather than the global one. See the- /// `LogCacheEntry` docstring for why the disk cache itself is- /// SHA-keyed but decoration text drifts.+ /// Log mode that hits the disk cache also enqueues a refresh task to+ /// recompute the embedded ref decorations before the next visit (see+ /// [`Self::spawn_log_refresh`]).pub(super) fn spawn_preview(&self,+ spawn_gen: &SpawnGeneration,item: Arc<ListItem>,mode: PreviewMode,dims: (usize, usize),@@ -235,51 +557,102 @@ impl PreviewOrchestrator {let cache = Arc::clone(&self.cache);let notifier = Arc::clone(&self.notifier);let (w, h) = dims;- let repo = self.repo.clone();+ let repo = self.repo();let pending = Arc::clone(&self.pending);+ let spawn_gen = spawn_gen.clone();self.spawn_task(move || {+ // A superseded spawn's queued task is doomed — its fill would+ // drop — so skip the compute, not just the write. `fill` remains+ // the correctness gate; this (and the same check in the other+ // task bodies) only stops a refresh from paying for the prior+ // spawn's still-queued git/LLM work.+ if !spawn_gen.is_current() {+ return;+ }let cache_key = (item.branch_name().to_string(), mode);if cache.contains_key(&cache_key) {return;}let (value, log_disk_hit) =PickerRow::compute_and_page_preview(&repo, &item, mode, w, h);- Self::fill(&cache, ¬ifier, cache_key, value);+ Self::fill(&cache, ¬ifier, &spawn_gen, 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(¬ifier);- let repo = repo.clone();- rayon::spawn_fifo(move || {- let _g = guard;- let rendered = PickerRow::refresh_log_preview(&repo, &item, w, h);- // Skip empty results so a transient `git log` failure- // doesn't poison the in-memory cache with "" and wipe- // out the value the producer just inserted.- if !rendered.is_empty() {- Self::fill(- &cache,- ¬ifier,- (item.branch_name().to_string(), PreviewMode::Log),- rendered,- );- }- });+ Self::spawn_log_refresh(+ &cache,+ ¬ifier,+ &pending,+ &spawn_gen,+ item,+ &repo,+ (w, h),+ );+ }+ });+ }++ /// Enqueue the background re-render that follows a Log disk-cache hit+ /// (recomputing the embedded ref decorations — see the `LogCacheEntry`+ /// docstring for why the SHA-keyed cache drifts). Lands on+ /// `COLLECT_POOL`'s FIFO injector, behind in-flight foreground+ /// precompute. Shared by the pool producer (`spawn_preview`) and the+ /// demand worker.+ fn spawn_log_refresh(+ cache: &PreviewCache,+ notifier: &Arc<PreviewNotifier>,+ pending: &Arc<AtomicUsize>,+ spawn_gen: &SpawnGeneration,+ item: Arc<ListItem>,+ repo: &Repository,+ dims: (usize, usize),+ ) {+ pending.fetch_add(1, Ordering::SeqCst);+ let guard = PendingGuard(Arc::clone(pending));+ let cache = Arc::clone(cache);+ let notifier = Arc::clone(notifier);+ let repo = repo.clone();+ let spawn_gen = spawn_gen.clone();+ COLLECT_POOL.spawn_fifo(move || {+ let _g = guard;+ if !spawn_gen.is_current() {+ return;+ }+ let (w, h) = dims;+ let rendered = PickerRow::refresh_log_preview(&repo, &item, w, h);+ // Skip empty results so a transient `git log` failure+ // doesn't poison the in-memory cache with "" and wipe+ // out the value the producer just inserted.+ if !rendered.is_empty() {+ Self::fill(+ &cache,+ ¬ifier,+ &spawn_gen,+ (item.branch_name().to_string(), PreviewMode::Log),+ rendered,+ );}});}/// Spawn an LLM summary task. Returns immediately.- pub(super) fn spawn_summary(&self, item: Arc<ListItem>, llm_command: String, repo: Repository) {+ pub(super) fn spawn_summary(+ &self,+ spawn_gen: &SpawnGeneration,+ item: Arc<ListItem>,+ llm_command: String,+ ) {let cache = Arc::clone(&self.cache);let notifier = Arc::clone(&self.notifier);+ let repo = self.repo();+ let spawn_gen = spawn_gen.clone();self.spawn_task(move || {+ if !spawn_gen.is_current() {+ return;+ }let summary = summary::generate_summary_for_item(&item, &llm_command, &repo);Self::fill(&cache,¬ifier,+ &spawn_gen,(item.branch_name().to_string(), PreviewMode::Summary),summary,);@@ -306,21 +679,26 @@ impl PreviewOrchestrator {/// failed fetch into a terminal "couldn't load" pane and hand that back as/// `Some(..)` rather than `None` — an uncached `None` would strand the tab on/// its loading placeholder until the picker reopens.- pub(super) fn spawn_compute<F>(&self, key: PreviewCacheKey, compute: F)- where+ pub(super) fn spawn_compute<F>(+ &self,+ spawn_gen: &SpawnGeneration,+ key: PreviewCacheKey,+ compute: F,+ ) whereF: FnOnce(&Repository) -> Option<String> + Send + 'static,{let cache = Arc::clone(&self.cache);let notifier = Arc::clone(&self.notifier);- let repo = self.repo.clone();+ let repo = self.repo();+ let spawn_gen = spawn_gen.clone();self.spawn_task(move || {- if cache.contains_key(&key) {+ if !spawn_gen.is_current() || cache.contains_key(&key) {return;}if let Some(value) = compute(&repo)&& !value.is_empty(){- Self::fill(&cache, ¬ifier, key, value);+ Self::fill(&cache, ¬ifier, &spawn_gen, key, value);}});}@@ -334,11 +712,12 @@ impl PreviewOrchestrator {/// for every row so quick j/k navigation hits cached content,/// bounded contention with the row pipeline (~N tasks).///- /// The remaining [`SECONDARY_MODES`] for items 1..N and their summaries+ /// The remaining [`LOCAL_GIT_MODES`] for items 1..N and their summaries/// are deferred to [`Self::spawn_deferred_precompute`], which fires/// after the row pipeline tears down.pub(super) fn spawn_initial_precompute(&self,+ spawn_gen: &SpawnGeneration,items: &[Arc<ListItem>],preview_dims: (usize, usize),llm_command: Option<&str>,@@ -346,17 +725,16 @@ impl PreviewOrchestrator {let Some(first) = items.first() else { return };// First item: all modes + summary.- self.spawn_preview(Arc::clone(first), INITIAL_MODE, preview_dims);- for mode in SECONDARY_MODES {- self.spawn_preview(Arc::clone(first), mode, preview_dims);+ for mode in LOCAL_GIT_MODES {+ self.spawn_preview(spawn_gen, Arc::clone(first), mode, preview_dims);}if let Some(llm) = llm_command {- self.spawn_summary(Arc::clone(first), llm.to_string(), self.repo.clone());+ self.spawn_summary(spawn_gen, Arc::clone(first), llm.to_string());}// Items 1..N: default tab only. Other modes wait for drain.for item in items.iter().skip(1) {- self.spawn_preview(Arc::clone(item), INITIAL_MODE, preview_dims);+ self.spawn_preview(spawn_gen, Arc::clone(item), INITIAL_MODE, preview_dims);}}@@ -368,8 +746,8 @@ impl PreviewOrchestrator {/// tier keeps these submissions out of that pool's injector while/// row tasks are still landing on workers' local deques. The/// default tab for these rows already fired at skeleton time via- /// [`Self::spawn_initial_precompute`]; what's left is- /// [`SECONDARY_MODES`] plus summaries.+ /// [`Self::spawn_initial_precompute`]; what's left is the rest of+ /// [`LOCAL_GIT_MODES`] plus summaries.////// Spawn order: mode-major across previews, then summaries last —/// each LLM call can take seconds. Called from outside any rayon@@ -377,18 +755,19 @@ impl PreviewOrchestrator {/// rayon's FIFO injector and workers pick previews before summaries.pub(super) fn spawn_deferred_precompute(&self,+ spawn_gen: &SpawnGeneration,rest: &[Arc<ListItem>],preview_dims: (usize, usize),llm_command: Option<&str>,) {- for mode in SECONDARY_MODES {+ for mode in LOCAL_GIT_MODES.into_iter().filter(|m| *m != INITIAL_MODE) {for item in rest {- self.spawn_preview(Arc::clone(item), mode, preview_dims);+ self.spawn_preview(spawn_gen, Arc::clone(item), mode, preview_dims);}}if let Some(llm) = llm_command {for item in rest {- self.spawn_summary(Arc::clone(item), llm.to_string(), self.repo.clone());+ self.spawn_summary(spawn_gen, Arc::clone(item), llm.to_string());}}}@@ -426,12 +805,19 @@ impl PreviewOrchestrator {COLLECT_POOL.spawn(wrapped);}- /// Block until all spawned tasks complete.+ /// Block until all pool-spawned tasks complete.////// Used by the dry-run path and tests; production never waits — tasks/// are fire-and-forget while skim runs. Polls at 10ms resolution; tasks/// typically take tens to hundreds of ms, so a condvar isn't worth the/// complexity.+ ///+ /// Scope: the `pending` counter covers everything spawned through+ /// [`Self::spawn_task`] and [`Self::spawn_log_refresh`]. The demand+ /// worker's own computes are outside it — they're keystroke-driven, and+ /// neither the dry-run path nor `wait_for_idle` callers drive+ /// `preview()`; a test exercising the demand path polls the cache+ /// instead (see `preview_miss_is_served_by_demand_worker`).pub(super) fn wait_for_idle(&self) {while self.pending.load(Ordering::SeqCst) > 0 {std::thread::sleep(Duration::from_millis(10));@@ -461,6 +847,16 @@ impl PreviewOrchestrator {}}+impl Drop for PreviewOrchestrator {+ /// Close the demand channel so the worker exits and drops its captures+ /// (preview cache, repo) when the picker ends — `wt switch` keeps+ /// running (hooks, the switch itself) after the picker returns, and a+ /// parked thread would otherwise pin them until process exit.+ fn drop(&mut self) {+ self.demand.close();+ }+}+#[cfg(test)]mod tests {use super::*;@@ -504,8 +900,18 @@ mod tests {let (t, item) = dirty_worktree_item();let orch = orch_for(&t);- orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));- orch.spawn_preview(Arc::clone(&item), PreviewMode::Log, (80, 24));+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::WorkingTree,+ (80, 24),+ );+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::Log,+ (80, 24),+ );orch.wait_for_idle();let wt_key = ("main".to_string(), PreviewMode::WorkingTree);@@ -526,7 +932,12 @@ mod tests {let (t, item) = dirty_worktree_item();let orch = orch_for(&t);- orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::WorkingTree,+ (80, 24),+ );orch.wait_for_idle();let first = orch.cache@@ -536,7 +947,12 @@ mod tests {.clone();// Second spawn should hit `contains_key` and skip.- orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::WorkingTree,+ (80, 24),+ );orch.wait_for_idle();let second = orch.cache@@ -555,10 +971,13 @@ mod tests {#[test]fn spawn_summary_populates_cache() {let (t, item) = dirty_worktree_item();- let repo = Repository::at(t.path()).unwrap();let orch = orch_for(&t);- orch.spawn_summary(Arc::clone(&item), "/bin/cat".to_string(), repo);+ orch.spawn_summary(+ &orch.generation(),+ Arc::clone(&item),+ "/bin/cat".to_string(),+ );orch.wait_for_idle();assert!(@@ -590,7 +1009,12 @@ mod tests {super::super::preview_cache::write_log(&repo, item.head(), 80, 24, &stale);let orch = orch_for(&t);- orch.spawn_preview(Arc::clone(&item), PreviewMode::Log, (80, 24));+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::Log,+ (80, 24),+ );orch.wait_for_idle();let disk = super::super::preview_cache::read_log(&repo, item.head(), 80, 24)@@ -630,7 +1054,12 @@ mod tests {super::super::preview_cache::write_log(&repo, item.head(), 80, 24, &stale);let orch = orch_for(&t);- orch.spawn_preview(Arc::clone(&item), PreviewMode::BranchDiff, (80, 24));+ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::BranchDiff,+ (80, 24),+ );orch.wait_for_idle();let disk = super::super::preview_cache::read_log(&repo, item.head(), 80, 24)@@ -651,9 +1080,11 @@ mod tests {let orch = orch_for(&t);// A populated value lands in the cache under its key.- orch.spawn_compute(("pr:7".to_string(), PreviewMode::Log), |_| {- Some("commit list".to_string())- });+ orch.spawn_compute(+ &orch.generation(),+ ("pr:7".to_string(), PreviewMode::Log),+ |_| Some("commit list".to_string()),+ );orch.wait_for_idle();assert_eq!(orch.cache@@ -664,9 +1095,11 @@ mod tests {// A second spawn for the same key short-circuits on `contains_key`, so// the original value survives even though this closure would overwrite.- orch.spawn_compute(("pr:7".to_string(), PreviewMode::Log), |_| {- Some("REPLACED".to_string())- });+ orch.spawn_compute(+ &orch.generation(),+ ("pr:7".to_string(), PreviewMode::Log),+ |_| Some("REPLACED".to_string()),+ );orch.wait_for_idle();assert_eq!(orch.cache@@ -677,10 +1110,16 @@ mod tests {);// `None` (forge failure) and `Some("")` both leave the slot empty.- orch.spawn_compute(("pr:9".to_string(), PreviewMode::Log), |_| None);- orch.spawn_compute(("pr:8".to_string(), PreviewMode::Log), |_| {- Some(String::new())- });+ orch.spawn_compute(+ &orch.generation(),+ ("pr:9".to_string(), PreviewMode::Log),+ |_| None,+ );+ orch.spawn_compute(+ &orch.generation(),+ ("pr:8".to_string(), PreviewMode::Log),+ |_| Some(String::new()),+ );orch.wait_for_idle();assert!(!orch@@ -696,6 +1135,338 @@ mod tests {);}+ /// End-to-end demand path: a `preview()` cache miss on a local-git tab is+ /// computed by the demand worker and served — without any precompute+ /// spawn touching the pool. Pins the fix for the "navigated-to tab waits+ /// behind the whole precompute queue" latency: the placeholder used to+ /// sit until the deferred tier happened to reach the key.+ #[test]+ fn preview_miss_is_served_by_demand_worker() {+ use super::super::items::{LocalCheckout, LocalContent, PickerRow};+ use skim::prelude::{PreviewContext, SkimItem};+ use std::sync::Mutex;+ use std::sync::atomic::AtomicBool;++ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);++ let row = PickerRow {+ search_base: String::new(),+ gutter: '@',+ rendered: Arc::new(Mutex::new(String::new())),+ branch_name: "main".to_string(),+ output_token: "main".to_string(),+ preview_cache: Arc::clone(&orch.cache),+ pr_status: Arc::new(Mutex::new(None)),+ notifier: Arc::clone(orch.notifier()),+ local: Some(LocalCheckout {+ item: Arc::clone(&item),+ demand: Arc::clone(orch.demand()),+ spawn_gen: orch.generation(),+ has_upstream: false,+ summaries_enabled: false,+ local_content: Arc::new(Mutex::new(LocalContent::default())),+ morphed: Arc::new(AtomicBool::new(false)),+ }),+ };++ // The picker opens on WorkingTree — the process-global default tab,+ // which this test deliberately leaves untouched (other tests read+ // it). This render misses and posts the demand. No assertion on the+ // returned placeholder: the worker races the render's own cache read+ // by design, so on a stalled thread the first render could already+ // carry the diff.+ let ctx = PreviewContext {+ query: "",+ cmd_query: "",+ width: 80,+ height: 24,+ current_index: 0,+ current_selection: "",+ selected_indices: &[],+ selections: &[],+ };+ drop(row.preview(ctx));++ // The demand worker fills the key with the real diff. Bounded poll so+ // a dead worker fails instead of hanging the suite.+ let key = ("main".to_string(), PreviewMode::WorkingTree);+ let deadline = std::time::Instant::now() + Duration::from_secs(60);+ while !orch.cache.contains_key(&key) {+ assert!(+ std::time::Instant::now() < deadline,+ "demand worker never filled the awaited key"+ );+ std::thread::sleep(Duration::from_millis(10));+ }+ let served = orch.cache.get(&key).unwrap().clone();+ assert!(+ served.contains("README"),+ "demand-computed working-tree diff served: {served:?}"+ );+ }++ /// A key a racing pool task already filled is not recomputed: serve_demand+ /// (the worker's loop body, driven directly so nothing races) returns+ /// before compute and the existing value survives.+ #[test]+ fn serve_demand_skips_already_filled_key() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);+ let key = ("main".to_string(), PreviewMode::WorkingTree);+ orch.fill_external(&orch.generation(), key.clone(), "already here".to_string());++ PreviewOrchestrator::serve_demand(+ &orch.cache,+ orch.notifier(),+ &orch.pending,+ &orch.repo(),+ DemandRequest {+ item,+ mode: PreviewMode::WorkingTree,+ dims: (80, 24),+ spawn_gen: orch.generation(),+ },+ );++ assert_eq!(+ orch.cache.get(&key).unwrap().clone(),+ "already here",+ "a filled key is skipped, not recomputed"+ );+ }++ /// A panicking compute must not unwind out of serve_demand — on the real+ /// worker thread that would silently kill demand serving for the rest of+ /// the session. `Pr` mode's compute arm is `unreachable!`, a deterministic+ /// panic source; the panic is contained and the key stays unfilled.+ #[test]+ fn serve_demand_contains_a_panicking_compute() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);++ PreviewOrchestrator::serve_demand(+ &orch.cache,+ orch.notifier(),+ &orch.pending,+ &orch.repo(),+ DemandRequest {+ item,+ mode: PreviewMode::Pr,+ dims: (80, 24),+ spawn_gen: orch.generation(),+ },+ );++ assert!(+ !orch+ .cache+ .contains_key(&("main".to_string(), PreviewMode::Pr)),+ "a panicked compute fills nothing"+ );+ }++ /// A Log disk hit served on demand enqueues the same decoration refresh+ /// the pool path does (see `log_disk_hit_triggers_background_refresh`):+ /// the stale seeded entry is overwritten once the pending-tracked refresh+ /// drains.+ #[test]+ fn serve_demand_log_disk_hit_enqueues_refresh() {+ let (t, item) = dirty_worktree_item();+ let repo = Repository::at(t.path()).unwrap();++ let stale = super::super::preview_cache::LogCacheEntry {+ raw_log: "STALE_MARKER\n".to_string(),+ stats: std::collections::HashMap::new(),+ };+ super::super::preview_cache::write_log(&repo, item.head(), 80, 24, &stale);++ let orch = orch_for(&t);+ PreviewOrchestrator::serve_demand(+ &orch.cache,+ orch.notifier(),+ &orch.pending,+ &orch.repo(),+ DemandRequest {+ item,+ mode: PreviewMode::Log,+ dims: (80, 24),+ spawn_gen: orch.generation(),+ },+ );+ orch.wait_for_idle();++ let in_memory = orch+ .cache+ .get(&("main".to_string(), PreviewMode::Log))+ .expect("in-memory entry present")+ .clone();+ assert!(+ !in_memory.contains("STALE_MARKER"),+ "the demand-served disk hit was refreshed: {in_memory:?}"+ );+ }++ /// A refresh supersedes the prior spawn's producers: every producer path+ /// carrying the pre-refresh token — pool preview/summary/compute tasks,+ /// the log-refresh follow-up, and the `fill` choke point itself — leaves+ /// the cleared cache untouched, while the rebuilt spawn's token fills+ /// normally. Pins the fix for the stale-drain race the module docs'+ /// *Spawn generations* section describes.+ #[test]+ fn refresh_supersedes_stale_spawn_fills() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);+ let stale = orch.generation();++ orch.refresh(Repository::at(t.path()).unwrap());++ // Queued task bodies drop the doomed work before computing.+ orch.spawn_preview(+ &stale,+ Arc::clone(&item),+ PreviewMode::WorkingTree,+ (80, 24),+ );+ orch.spawn_summary(&stale, Arc::clone(&item), "/bin/cat".to_string());+ orch.spawn_compute(&stale, ("pr:1".to_string(), PreviewMode::Log), |_| {+ Some("stale".to_string())+ });+ PreviewOrchestrator::spawn_log_refresh(+ &orch.cache,+ orch.notifier(),+ &orch.pending,+ &stale,+ Arc::clone(&item),+ &orch.repo(),+ (80, 24),+ );+ orch.wait_for_idle();+ // The choke point drops a stale write even when a task slipped past+ // the early checks (queued while current, filling after the bump).+ PreviewOrchestrator::fill(+ &orch.cache,+ orch.notifier(),+ &stale,+ ("main".to_string(), PreviewMode::WorkingTree),+ "stale".to_string(),+ );+ assert!(+ orch.cache.is_empty(),+ "a superseded spawn must not re-seed the cleared cache"+ );++ orch.spawn_preview(+ &orch.generation(),+ Arc::clone(&item),+ PreviewMode::WorkingTree,+ (80, 24),+ );+ orch.wait_for_idle();+ assert!(+ orch.cache+ .contains_key(&("main".to_string(), PreviewMode::WorkingTree)),+ "the live spawn's fill lands"+ );+ }++ /// `refresh` rebinds the compute repo, so post-refresh producers (and the+ /// demand worker's per-request read) resolve `RepoCache` values — notably+ /// the BranchDiff comparison base — from the rebuilt spawn's repo, not+ /// session-start state.+ #[test]+ fn refresh_rebinds_compute_repo() {+ let t = TestRepo::new();+ let orch = orch_for(&t);+ let t2 = TestRepo::new();+ let repo2 = Repository::at(t2.path()).unwrap();++ orch.refresh(repo2.clone());++ assert_eq!(+ orch.repo().discovery_path(),+ repo2.discovery_path(),+ "repo cell rebound to the rebuilt spawn's repo"+ );+ }++ /// A request from a row a refresh superseded is refused at the channel+ /// (its compute would drop at `fill` anyway); the live spawn's request+ /// parks. Driven on a worker-less channel so the parked/empty slot can be+ /// asserted without racing a serve.+ #[test]+ fn stale_generation_request_is_refused() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);+ let demand = PreviewDemand::new();+ let stale = orch.generation();++ orch.refresh(Repository::at(t.path()).unwrap());++ demand.request(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24), stale);+ assert!(+ demand.state.lock().unwrap().request.is_none(),+ "a superseded row's request is refused"+ );++ demand.request(item, PreviewMode::WorkingTree, (80, 24), orch.generation());+ assert!(+ demand.state.lock().unwrap().request.is_some(),+ "the live spawn's request parks"+ );+ }++ /// The one stale demand that can outlive `request`'s check — parked while+ /// its spawn was current, taken after a refresh — is dropped before its+ /// compute, so the live spawn's first demand never queues behind it and+ /// the cleared cache stays untouched.+ #[test]+ fn parked_request_across_refresh_is_dropped() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);+ let stale = orch.generation();++ orch.refresh(Repository::at(t.path()).unwrap());+ PreviewOrchestrator::serve_demand(+ &orch.cache,+ orch.notifier(),+ &orch.pending,+ &orch.repo(),+ DemandRequest {+ item,+ mode: PreviewMode::WorkingTree,+ dims: (80, 24),+ spawn_gen: stale,+ },+ );++ assert!(+ orch.cache.is_empty(),+ "a request parked across a refresh computes but its fill drops"+ );+ }++ /// Rows hold the demand channel beyond the orchestrator's life (skim can+ /// still call `preview()` while teardown races), so a request after+ /// `Drop` closed the channel must be inert, not parked forever.+ #[test]+ fn request_after_orchestrator_drop_is_inert() {+ let (t, item) = dirty_worktree_item();+ let orch = orch_for(&t);+ let demand = Arc::clone(orch.demand());+ let cache = Arc::clone(&orch.cache);+ let spawn_gen = orch.generation();+ drop(orch);++ demand.request(item, PreviewMode::WorkingTree, (80, 24), spawn_gen);++ assert!(+ demand.state.lock().unwrap().request.is_none(),+ "a closed channel records nothing"+ );+ assert!(cache.is_empty(), "nothing fills after close");+ }+/// 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@@ -716,6 +1487,7 @@ mod tests {// The awaited compute lands → skim is poked to repaint.orch.fill_external(+ &orch.generation(),("main".to_string(), PreviewMode::WorkingTree),"diff".to_string(),);@@ -726,10 +1498,15 @@ mod tests {// Fills for other rows / other tabs must not poke — no preview thrash.orch.fill_external(+ &orch.generation(),("feature".to_string(), PreviewMode::WorkingTree),"x".to_string(),);- orch.fill_external(("main".to_string(), PreviewMode::Log), "y".to_string());+ orch.fill_external(+ &orch.generation(),+ ("main".to_string(), PreviewMode::Log),+ "y".to_string(),+ );assert!(rx.try_recv().is_err(),"an off-screen / other-tab fill injects nothing"diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex 642ffde08..a67077e17 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -58,7 +58,7 @@ use super::items::{};use super::preview::PreviewMode;use super::preview_notify::PrStatusDelta;-use super::preview_orchestrator::PreviewOrchestrator;+use super::preview_orchestrator::{PreviewOrchestrator, SpawnGeneration};use crate::commands::list::collect::PickerProgressHandler;use crate::commands::list::model::{BranchScope, ItemKind, ListItem};@@ -112,16 +112,21 @@ pub(super) struct PickerHandler {pub(super) local_content_slots: OnceLock<Box<[LocalContentSlot]>>,pub(super) preview_cache: PreviewCache,/// Fresh `Repository` for this spawn, used for the mutation-sensitive- /// `on_skeleton` reads (`list_worktrees`, `local_branches`). The- /// `orchestrator` carries its own startup-cloned repo shared across every- /// spawn — reading worktrees/branches through that re-probes a- /// `RepoCache.worktrees`/`local_branches` `OnceCell` primed at startup and- /// never invalidated, so after an in-picker removal it would yield the stale- /// pre-removal set. `spawn` rebuilds this repo per pass (same `spawn_repo`- /// the collect/prs threads use); read inventories through it, not through- /// `orchestrator.repo()`.+ /// `on_skeleton` reads (`list_worktrees`, `local_branches`) — a+ /// `RepoCache` is a set of `OnceCell`s that are never invalidated, so+ /// these reads must go through a repo rebuilt after any in-picker+ /// removal, or they'd yield the stale pre-removal inventory. `spawn`+ /// rebuilds this repo per pass: the same `spawn_repo` the collect/prs+ /// threads use and `PreviewOrchestrator::refresh` rebinds for preview+ /// compute; this field is the handler's direct handle to it.pub(super) repo: Repository,pub(super) orchestrator: Arc<PreviewOrchestrator>,+ /// This spawn's producer token (see [`SpawnGeneration`]): every+ /// precompute spawn, comments fetch, and skim row this handler starts+ /// carries it, so a refresh that supersedes this spawn also supersedes+ /// everything it still has in flight — including this handler's own+ /// `on_collect_complete` firing after the refresh.+ pub(super) spawn_gen: SpawnGeneration,pub(super) preview_dims: (usize, usize),pub(super) llm_command: Option<String>,/// Filled into the Summary preview cache for every item when summaries@@ -195,6 +200,16 @@ impl PickerHandler {branch_name: &str,pr_status: &Option<Option<PrStatus>>,) {+ // A superseded handler (its collect thread draining past an `alt-r`)+ // must not act at all: its corrected-number path below *removes* the+ // shared `(branch, Comments)` entry — possibly the one the live spawn+ // just fetched — and its replacement fetch would then drop at `fill`+ // on the stale token, stranding the tab on its loading placeholder+ // (nothing else refills Comments; the live handler's dedup slot+ // already records the number). Gate the removal with the fetch.+ if !self.spawn_gen.is_current() {+ return;+ }let Some(Some(status)) = pr_status else {return;};@@ -227,6 +242,7 @@ impl PickerHandler {}super::prs::spawn_worktree_comments_fetch(&self.orchestrator,+ &self.spawn_gen,branch_name.to_string(),number as u32,status.updated_at.clone(),@@ -331,7 +347,7 @@ impl PickerProgressHandler for PickerHandler {// 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());+ let noun = super::prs::forge_noun(&self.repo);HeaderLoading {pending: Arc::clone(pending),marker_ansi: cformat!("{HINT_SYMBOL} <dim>Loading open {noun}…</>"),@@ -449,6 +465,9 @@ impl PickerProgressHandler for PickerHandler {pr_status: pr_status_arc,notifier: Arc::clone(self.orchestrator.notifier()),local: Some(LocalCheckout {+ item: Arc::clone(&item_arc),+ demand: Arc::clone(self.orchestrator.demand()),+ spawn_gen: self.spawn_gen.clone(),has_upstream,summaries_enabled,local_content: local_content_arc,@@ -466,8 +485,25 @@ impl PickerProgressHandler for PickerHandler {let _ = self.local_content_slots.set(local_content_slots.into_boxed_slice());- *self.shared_items.lock().unwrap() = skim_items.clone();- *self.shortcut_table.lock().unwrap() = shortcut_map;+ // The session-shared list and shortcut table take only the live+ // spawn's rows: a superseded skeleton landing late (its collect+ // thread scheduled after a rapid second `alt-r`'s spawn already+ // published) would otherwise overwrite them with pre-refresh rows,+ // and a later `alt-x` resync or `alt-y`/`alt-o` would act on those.+ // Checked inside each lock so the check pairs with the live spawn's+ // own overwrite — its generation bump precedes its publish.+ {+ let mut list = self.shared_items.lock().unwrap();+ if self.spawn_gen.is_current() {+ *list = skim_items.clone();+ }+ }+ {+ let mut table = self.shortcut_table.lock().unwrap();+ if self.spawn_gen.is_current() {+ *table = shortcut_map;+ }+ }// skim 4.x's item channel carries Vec batches; the skeleton is a single// batch. This append wakes skim's reader (`items_available`) and drives@@ -492,6 +528,7 @@ impl PickerProgressHandler for PickerHandler {// of row tasks in `COLLECT_POOL`'s injector while workers are still// grinding through the row work.self.orchestrator.spawn_initial_precompute(+ &self.spawn_gen,&list_items,self.preview_dims,self.llm_command.as_deref(),@@ -504,8 +541,12 @@ impl PickerProgressHandler for PickerHandler {}// Static Summary hint is a synchronous in-memory insert, no// contention concern. Pre-fill every row at skeleton time so the- // Summary tab is usable for any selection immediately.+ // Summary tab is usable for any selection immediately. Gated like+ // the shared publish above: the seeding bypasses `fill` (static+ // content, documented exception), so a superseded skeleton would+ // otherwise write its stale rows' keys into the refreshed cache.if self.llm_command.is_none()+ && self.spawn_gen.is_current()&& let Some(hint) = self.summary_hint.as_deref(){self.orchestrator.seed_summary_hints(&list_items, hint);@@ -612,6 +653,7 @@ impl PickerProgressHandler for PickerHandler {return;}self.orchestrator.spawn_deferred_precompute(+ &self.spawn_gen,&items[1..],self.preview_dims,self.llm_command.as_deref(),@@ -639,6 +681,7 @@ mod tests {render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>>,) -> PickerHandler {let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);+ let spawn_gen = orchestrator.generation();PickerHandler {tx,render_tx,@@ -652,6 +695,7 @@ mod tests {preview_cache,repo,orchestrator,+ spawn_gen,preview_dims: (80, 24),llm_command: None,summary_hint: Some("disabled".to_string()),@@ -1633,4 +1677,102 @@ mod tests {"on_collect_complete must not spawn additional work for a single-item skeleton");}++ /// A handler superseded by a refresh must not publish its skeleton into+ /// the session-shared row list / shortcut table, nor seed summary hints:+ /// a rapid second `alt-r` can schedule the new spawn's skeleton before a+ /// slow prior spawn's, and the stale skeleton landing second would+ /// otherwise overwrite the live rows (feeding a later `alt-x` resync and+ /// the `alt-y`/`alt-o` lookups) and write stale-row hint keys into the+ /// refreshed cache.+ #[test]+ fn superseded_skeleton_leaves_shared_state_alone() {+ let (handler, test, rx) = make_handler();+ handler.orchestrator.refresh(test.repo.clone());++ handler.on_skeleton(+ vec![ListItem::new_branch("abc".into(), "stale".into())],+ vec!["skel".into()],+ header("hdr"),+ grid(),+ );+ handler.orchestrator.wait_for_idle();++ // The rows still stream to this spawn's (dead) skim channel...+ let received = rx.recv().expect("skeleton batch");+ assert_eq!(received.len(), 2, "header + row still sent");+ // ...but nothing session-shared takes them.+ assert!(+ handler.shared_items.lock().unwrap().is_empty(),+ "superseded skeleton must not overwrite the shared row list"+ );+ assert!(+ handler.shortcut_table.lock().unwrap().is_empty(),+ "superseded skeleton must not overwrite the shortcut table"+ );+ assert!(+ handler.preview_cache.is_empty(),+ "superseded skeleton must not seed hints into the refreshed cache"+ );+ }++ /// A superseded handler's `maybe_spawn_comments` is fully inert. Its+ /// corrected-number path would otherwise evict the live spawn's+ /// `(branch, Comments)` entry from the shared cache while its own refetch+ /// drops at `fill` on the stale token — stranding the tab on its loading+ /// placeholder, since the live handler's dedup slot already records the+ /// number and nothing else refills Comments.+ #[test]+ fn superseded_handler_does_not_evict_live_comments() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, PrStatus};++ let status = |n: u64| {+ Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming: false,+ url: None,+ number: Some(PrRef::pr(n)),+ review_state: None,+ title: None,+ body: None,+ author: None,+ comment_count: None,+ updated_at: None,+ }))+ };++ let (handler, test, rx) = make_handler();+ handler.on_skeleton(+ vec![ListItem::new_branch("abc".into(), "b".into())],+ vec!["skel".into()],+ header("hdr"),+ grid(),+ );+ let _ = rx.recv();+ // Record PR #5 in this handler's dedup slot (the fetch resolves+ // synchronously to the "unsupported forge" pane — the test repo has+ // no forge remote — only the recorded number matters here).+ handler.maybe_spawn_comments(0, "b", &status(5));++ // A refresh supersedes this handler; the live spawn fetches the thread.+ handler.orchestrator.refresh(test.repo.clone());+ let key = ("b".to_string(), PreviewMode::Comments);+ handler.orchestrator.fill_external(+ &handler.orchestrator.generation(),+ key.clone(),+ "live thread".to_string(),+ );++ // The stale handler observing a corrected number must not touch the+ // live spawn's entry.+ handler.maybe_spawn_comments(0, "b", &status(6));+ handler.orchestrator.wait_for_idle();+ assert_eq!(+ handler.preview_cache.get(&key).map(|v| v.clone()),+ Some("live thread".to_string()),+ "a superseded handler must not evict the live spawn's Comments entry"+ );+ }}diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex 4e1334662..cf3a768b5 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -37,7 +37,7 @@use std::collections::HashSet;use std::path::Path;-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Condvar, Mutex, OnceLock};use std::time::Duration;@@ -61,7 +61,7 @@ use super::pr_pane;use super::preview::PreviewMode;use super::preview_cache::CommentEntry;use super::preview_notify::PreviewNotifier;-use super::preview_orchestrator::PreviewOrchestrator;+use super::preview_orchestrator::{PreviewOrchestrator, SpawnGeneration};/// One-shot handoff from the collect thread (which builds the skeleton) to the/// `--prs` thread: the picker's column geometry, so PR rows align to the@@ -266,15 +266,15 @@ pub(super) struct PrsShared {/// that — so PR rows always land after the worktree rows, never in the/// reserved header slot.pub shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,- /// Session-shared spawn counter (`PipelineFactory::prs_epoch`); each spawn- /// bumps it. Read together with `current_epoch` to decide whether this- /// thread's append is still wanted — see the append in [`fetch_and_stream`].- pub epoch: Arc<AtomicUsize>,- /// This spawn's `epoch` value, captured when the thread was spawned. The- /// append into `shared_items` runs only while `epoch` still equals it, so a- /// stale forge call from a pre-refresh spawn (whose skim channel is already- /// dropped) can't pollute the list a newer spawn rebuilt.- pub current_epoch: usize,+ /// This spawn's identity token (see [`SpawnGeneration`]), gating every+ /// cross-spawn effect this thread has: the whole row batch is dropped+ /// once superseded (see the bail in [`fetch_and_stream`]), the append+ /// into `shared_items` re-checks inside the lock so a stale forge call+ /// from a pre-refresh spawn (whose skim channel is already dropped)+ /// can't pollute the list a newer spawn rebuilt, and the per-row+ /// `log`/`comments` fetches carry it so their fills can't land in the+ /// preview cache a refresh cleared.+ pub spawn_gen: SpawnGeneration,}/// Stream the open PRs/MRs into the picker, then clear the header's "loading…"@@ -356,6 +356,16 @@ fn fetch_and_stream(return;}+ // An `alt-r` during the forge call supersedes this spawn: the rebuilt+ // spawn's own `--prs` thread refetches everything, so building rows here+ // would only fan out per-row fetches (up to 2×`MAX_PRS` forge+ // subprocesses) whose fills all drop at the generation check, plus a+ // doomed append below. Drop the whole batch instead. The check inside+ // the `shared_items` lock below stays authoritative for the append.+ if !shared.spawn_gen.is_current() {+ return;+ }+// The forge call above (~1s) almost always outlasts the skeleton// (~50ms), so this returns immediately; the wait covers a mocked forge// CLI winning the race. A `None` (collect errored / zero rows) leaves both@@ -385,19 +395,27 @@ fn fetch_and_stream(let items: Vec<Arc<dyn SkimItem>> = entries.into_iter().map(|entry| {- spawn_pr_previews(orchestrator, &entry, layout.preview_dims);+ spawn_pr_previews(orchestrator, &shared.spawn_gen, &entry, layout.preview_dims);// Shortcut lookup for this row: `alt-y` copies the PR/MR head- // branch, `alt-o` opens its already-known web URL.- shared.shortcut_table.lock().unwrap().insert(- entry.output_token(),- RowShortcutData {- branch: Some(entry.head_branch.clone()),- url: RowUrl::Static(entry.url.clone()),- // A `--prs` row has no local worktree to remove, so `alt-x`- // can't morph it.- morph: None,- },- );+ // branch, `alt-o` opens its already-known web URL. Re-checked+ // inside the lock like the `shared_items` append below — an+ // `alt-r` landing mid-build must not write this spawn's entries+ // into the table the new spawn rebuilt.+ {+ let mut table = shared.shortcut_table.lock().unwrap();+ if shared.spawn_gen.is_current() {+ table.insert(+ entry.output_token(),+ RowShortcutData {+ branch: Some(entry.head_branch.clone()),+ url: RowUrl::Static(entry.url.clone()),+ // A `--prs` row has no local worktree to remove,+ // so `alt-x` can't morph it.+ morph: None,+ },+ );+ }+ }Arc::new(listed_pr_row(&entry,grid.as_ref(),@@ -412,15 +430,16 @@ fn fetch_and_stream(// pool rebuild (`resync_pool`) keeps them — they reach skim through its own// channel below, which the rebuild never reads. The skeleton has already// populated `shared_items` (the `grid_slot.wait` above gates on it), so this- // appends after the worktree rows. Done under the lock and gated on the spawn- // epoch: a stale forge call from a pre-refresh spawn (its skim channel already- // dropped) must not add rows to the list a newer spawn rebuilt — reading the- // epoch inside the lock pairs the check with the next spawn's `on_skeleton`- // overwrite, which holds the same lock. Ordered before `tx.send` so the rows- // reach `shared_items` no later than they reach skim's pool.+ // appends after the worktree rows. Done under the lock and gated on the+ // spawn generation: a stale forge call from a pre-refresh spawn (its skim+ // channel already dropped) must not add rows to the list a newer spawn+ // rebuilt — re-checking inside the lock pairs the check with the next+ // spawn's `on_skeleton` overwrite, which holds the same lock (its+ // generation bump precedes its overwrite). Ordered before `tx.send` so the+ // rows reach `shared_items` no later than they reach skim's pool.{let mut list = shared.shared_items.lock().unwrap();- if shared.epoch.load(Ordering::SeqCst) == shared.current_epoch {+ if shared.spawn_gen.is_current() {list.extend(items.iter().map(Arc::clone));}}@@ -495,6 +514,7 @@ fn listed_pr_row(/// (a worktree row renders its `log` tab from the local object store instead).fn spawn_pr_previews(orchestrator: &PreviewOrchestrator,+ spawn_gen: &SpawnGeneration,entry: &PrEntry,preview_dims: (usize, usize),) {@@ -503,7 +523,7 @@ fn spawn_pr_previews(let (width, height) = preview_dims;let head_oid = entry.head_oid.clone();let head_branch = entry.head_branch.clone();- orchestrator.spawn_compute((token.clone(), PreviewMode::Log), move |repo| {+ orchestrator.spawn_compute(spawn_gen, (token.clone(), PreviewMode::Log), move |repo| {Some(compute_pr_log(repo,@@ -519,6 +539,7 @@ fn spawn_pr_previews(});spawn_comments_fetch(orchestrator,+ spawn_gen,token,entry.kind,entry.number,@@ -546,13 +567,14 @@ fn spawn_pr_previews(/// runs and nothing is written to disk — see [`compute_pr_comments`].fn spawn_comments_fetch(orchestrator: &PreviewOrchestrator,+ spawn_gen: &SpawnGeneration,key_token: String,kind: RefKind,number: u32,updated_at: Option<String>,width: usize,) {- orchestrator.spawn_compute((key_token, PreviewMode::Comments), move |repo| {+ orchestrator.spawn_compute(spawn_gen, (key_token, PreviewMode::Comments), move |repo| {Some(compute_pr_comments(repo, kind, number, updated_at.as_deref(), width).unwrap_or_else(|| pr_unavailable_pane("comments")),@@ -572,6 +594,7 @@ fn spawn_comments_fetch(/// forever. `ci_platform` reads the cached remote URL — no network.pub(super) fn spawn_worktree_comments_fetch(orchestrator: &PreviewOrchestrator,+ spawn_gen: &SpawnGeneration,branch: String,number: u32,updated_at: Option<String>,@@ -582,13 +605,22 @@ pub(super) fn spawn_worktree_comments_fetch(Some(CiPlatform::GitLab) => RefKind::Mr,_ => {orchestrator.fill_external(+ spawn_gen,(branch, PreviewMode::Comments),comments_unsupported_forge_pane(),);return;}};- spawn_comments_fetch(orchestrator, branch, kind, number, updated_at, width);+ spawn_comments_fetch(+ orchestrator,+ spawn_gen,+ branch,+ kind,+ number,+ updated_at,+ width,+ );}/// The `comments` tab pane for a worktree row whose branch has a PR on a forge@@ -1847,8 +1879,7 @@ mod tests {grid_slot: Arc::new(GridSlot::new()),shortcut_table: Arc::new(Mutex::new(std::collections::HashMap::new())),shared_items: Arc::new(Mutex::new(Vec::new())),- epoch: Arc::new(AtomicUsize::new(1)),- current_epoch: 1,+ spawn_gen: orchestrator.generation(),};let (rtx, mut rrx) = tokio::sync::mpsc::channel(8);let render_tx = OnceLock::new();