Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(picker): stop burning a core while background collect is pending (#3534)
Maximilian Roose47132966b02
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 789ceb2dc..62d99a30b 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1403,10 +1403,12 @@ struct SpawnedPipeline {impl PipelineFactory {/// Build a fresh handler + item channel, start the `picker-collect` thread/// (and the `picker-prs` thread when `--prs` is active), and hand back the- /// receiver skim reads. The handler holds the only non-thread `tx` clone, so- /// once the spawned threads finish the channel closes and skim's reader sees- /// EOF — the "background work done → picker idle" contract, which a refresh- /// relies on to end its `reload`.+ /// receiver skim reads. Every sender drops as soon as its batch is sent —+ /// the handler's at the skeleton send, the `--prs` thread's when its rows+ /// land — so skim's reader sees EOF once the last batch is in, which is+ /// what ends a refresh's `reload`. Collect keeps grinding past that point+ /// (CI fetches, summaries) through in-place row updates that never touch+ /// the channel./// `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 run `PreviewOrchestrator::refresh` —@@ -1481,7 +1483,7 @@ impl PipelineFactory {let handler: Arc<progressive_handler::PickerHandler> =Arc::new(progressive_handler::PickerHandler {- tx: tx.clone(),+ tx: Mutex::new(Some(tx.clone())),render_tx: Arc::clone(&self.render_tx),last_render_poke: Mutex::new(Instant::now()),shared_items: Arc::clone(&self.shared_items),@@ -1577,8 +1579,9 @@ impl PipelineFactory {None};- // Drop the local `tx` so the handler's clone (and the threads' clones)- // are the only senders left — their drop is what signals EOF to skim.+ // Drop the local `tx` so the handler's clone (consumed at the skeleton+ // send) and the `--prs` thread's clone are the only senders left —+ // their release is what signals EOF to skim.drop(tx);Ok(SpawnedPipeline {@@ -2052,11 +2055,12 @@ summary = trueinstall_remove_keybinding(&mut options.keymap, alt_x_remover);worktrunk::trace::instant("Picker skim options built");- // Spawn the collect pipeline (and the `--prs` thread when active). The- // handler holds the only non-thread `tx` clone; when the bg threads exit,- // `tx` drops, skim's reader sees EOF, and the picker goes idle. The initial- // spawn reuses the startup-primed inventory (`false`); every alt-r refresh- // re-runs `factory.spawn(true)` to re-enumerate — see `PipelineFactory`.+ // Spawn the collect pipeline (and the `--prs` thread when active). Each+ // sender drops with its one batch sent (skeleton, PR rows), so skim's+ // reader sees EOF as soon as the last batch lands — see+ // `PipelineFactory::spawn`. The initial spawn reuses the startup-primed+ // inventory (`false`); every alt-r refresh re-runs `factory.spawn(true)`+ // to re-enumerate.let SpawnedPipeline {rx,handler,diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex a67077e17..db502bd0e 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -1,8 +1,8 @@//! Progressive-rendering glue between `collect::collect` and the skim picker.//!-//! Each event funnels into three places: skim's item stream (`tx`, alive-//! while updates may arrive so the picker stays non-idle), each item's-//! shared `rendered` mutex (in-place redraws), and `shared_items` used by+//! Each event funnels into three places: skim's item stream (`tx`, consumed+//! by the skeleton batch — the handler's only send), each item's shared+//! `rendered` mutex (in-place redraws), and `shared_items` used by//! `PickerCollector` for alt-x.//!//! # Why updates poke a render@@ -64,13 +64,17 @@ use crate::commands::list::model::{BranchScope, ItemKind, ListItem};/// Handler owned by the background collect thread. Implements the/// `PickerProgressHandler` trait that `collect` drives.-///-/// The `tx` clone lives as long as this handler is referenced — dropping the-/// handler (when the collect thread exits) drops the last sender, which signals-/// EOF to skim's reader. That's the explicit contract: once background work is-/// done, the picker can go idle.pub(super) struct PickerHandler {- pub(super) tx: SkimItemSender,+ /// skim's item channel, consumed by `on_skeleton`'s single send. Sending+ /// the skeleton batch takes the sender out and drops it, so the channel+ /// closes as soon as the last live sender (the `--prs` thread's clone, if+ /// any) finishes — not when the handler itself drops. Row updates after the+ /// skeleton are in-place (`rendered` mutexes + `request_render`), never+ /// resent, so nothing needs the channel past that send, and holding it open+ /// is expensive: skim's reader polls an open-but-empty channel with kanal's+ /// `recv_timeout`, whose wait yields instead of parking — a full core spun+ /// for as long as collect still grinds (a slow CI fetch, an LLM summary).+ pub(super) tx: Mutex<Option<SkimItemSender>>,/// skim's event sender, published by the picker once `Skim::init_tui` has/// run. `None` until then — early skeleton sends drive the first paint via/// the item channel, so a missed poke before the TUI exists is harmless.@@ -510,8 +514,13 @@ impl PickerProgressHandler for PickerHandler {// the first paint. Later field updates happen in place through each// item's shared `rendered` mutex and are *not* resent — they surface via// `request_render` (see module docstring), since skim won't repaint a- // silent in-place mutation on its own.- let _ = self.tx.send(skim_items);+ // silent in-place mutation on its own. Sending consumes the sender+ // (see the `tx` field doc): this is the handler's only send, and+ // releasing it here lets skim's reader stop polling the channel while+ // collect's remaining tasks grind on.+ if let Some(tx) = self.tx.lock().unwrap().take() {+ let _ = tx.send(skim_items);+ }// Skeleton is in skim's channel; now wake the `--prs` thread (see the// `shown_branches` note above). Its rows append after the skeleton, so a PR@@ -683,7 +692,7 @@ mod tests {let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);let spawn_gen = orchestrator.generation();PickerHandler {- tx,+ tx: Mutex::new(Some(tx)),render_tx,last_render_poke: Mutex::new(Instant::now()),shared_items: Arc::new(Mutex::new(Vec::new())),@@ -864,6 +873,34 @@ mod tests {assert_eq!(*slots[1].lock().unwrap(), "rev-two");}+ /// The skeleton send consumes the handler's sender (see the `tx` field+ /// doc): with no `--prs` clone in play, the channel closes at the skeleton+ /// batch even though the handler — and the collect thread driving it —+ /// lives on. Held open instead, skim's reader would spin a full core on the+ /// empty channel (kanal's `recv_timeout` yields rather than parking) for as+ /// long as collect's slower tasks (a CI fetch, an LLM summary) keep running.+ #[test]+ fn skeleton_send_consumes_sender_and_closes_channel() {+ let (handler, _test, rx) = make_handler();+ handler.on_skeleton(+ vec![ListItem::new_branch("abc".into(), "one".into())],+ vec!["skel".into()],+ header("hdr"),+ grid(),+ );++ let received = rx.recv().expect("skeleton batch");+ assert_eq!(received.len(), 2, "expected header + 1 item");+ assert!(+ rx.recv().is_err(),+ "channel should be closed after the skeleton send"+ );+ assert!(+ handler.tx.lock().unwrap().is_none(),+ "the sender should be consumed, not merely unused"+ );+ }+/// `on_update` mirrors a row's live CI status into the preview-feeding slots,/// then pokes `Event::RunPreview` so the selected row's `pr` / `comments` tab/// re-renders from the new status without a keystroke. This is the loop thediff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex cf3a768b5..50d158b58 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -13,9 +13,9 @@//! The list is a single forge call (`gh pr list` / `glab mr list`) run on a//! dedicated thread that holds a clone of skim's item channel. The picker//! frame paints instantly from local worktree data; PR rows appear when the-//! call returns (~1s). The thread's sender drop is part of the picker's-//! EOF contract — skim's reader sees end-of-stream only once every sender-//! drops — see [`super::handle_picker`].+//! call returns (~1s). The thread's sender is the last one standing — the+//! handler's is consumed at the skeleton send — so its drop is what shows+//! skim's reader end-of-stream; see [`super::handle_picker`].//!//! # Alignment//!