Skip to content

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

Unblock picker first render; add preview dry-run (#2210)

Maximilian Roos185341f7a403
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index e13546785..a6696884e 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -157,19 +157,18 @@ impl WorktreeSkimItem {
/// Render preview for the given mode with specified dimensions.
///
- /// Uses cache if available, otherwise computes and caches. Diff-mode pager
- /// output is included in the cached value (via [`Self::compute_and_page_preview`])
- /// so that skim's event-loop thread — which calls `preview()` synchronously —
- /// never spawns a pager subprocess.
- fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {
+ /// Pure cache read: skim calls this synchronously on the UI thread
+ /// (see `skim::model::draw_preview`), so any blocking here gates the
+ /// entire first render — list included. Background tasks populate the
+ /// cache out-of-band; a miss returns a placeholder, and skim will
+ /// re-query on the next selection/query change.
+ fn preview_for_mode(&self, mode: PreviewMode, width: usize, _height: usize) -> String {
let cache_key = (self.branch_name.clone(), mode);
-
let content = self
.preview_cache
- .entry(cache_key)
- .or_insert_with(|| Self::compute_and_page_preview(&self.item, mode, width, height))
- .value()
- .clone();
+ .get(&cache_key)
+ .map(|v| v.value().clone())
+ .unwrap_or_else(|| Self::loading_placeholder(mode));
match mode {
// Summary post-processing is cheap (string formatting, no subprocess).
@@ -180,6 +179,23 @@ impl WorktreeSkimItem {
}
}
+ /// Placeholder shown while a background task is still computing the
+ /// preview for this mode. Skim has no API to re-query preview from
+ /// outside user interaction (see `skim::previewer::on_item_change` bail
+ /// at `previewer.rs:187`), so the hint tells the user to press the mode
+ /// key again to refresh once the background fill lands.
+ pub(super) fn loading_placeholder(mode: PreviewMode) -> String {
+ let (verb, label) = match mode {
+ PreviewMode::WorkingTree => ("Loading", "working-tree diff"),
+ PreviewMode::Log => ("Loading", "log"),
+ PreviewMode::BranchDiff => ("Loading", "branch diff"),
+ PreviewMode::UpstreamDiff => ("Loading", "upstream diff"),
+ PreviewMode::Summary => ("Generating", "summary"),
+ };
+ let key = mode as u8;
+ format!("○ {verb} {label}. Press {key} again to refresh.\n")
+ }
+
/// Compute preview and apply pager for diff modes.
///
/// Both the inline cache-miss path and background pre-computation use this so
@@ -216,7 +232,7 @@ impl WorktreeSkimItem {
PreviewMode::Log => Self::compute_log_preview(item, width, height),
PreviewMode::BranchDiff => Self::compute_branch_diff_preview(item, width),
PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(item, width),
- PreviewMode::Summary => Self::compute_summary_preview(item),
+ PreviewMode::Summary => Self::loading_placeholder(PreviewMode::Summary),
}
}
@@ -422,18 +438,6 @@ impl WorktreeSkimItem {
output
}
-
- /// Compute Tab 5: Summary preview (LLM-generated branch summary)
- ///
- /// Returns a synchronous placeholder when the background summary generation
- /// hasn't completed yet. The actual summary is generated by background threads
- /// and inserted into the preview cache.
- fn compute_summary_preview(_item: &ListItem) -> String {
- format!(
- "{INFO_SYMBOL} Generating summary...\n\n\
- Press 5 again to refresh once generation completes.\n"
- )
- }
}
#[cfg(test)]
@@ -456,29 +460,20 @@ mod tests {
}
#[test]
- fn test_compute_summary_preview() {
- // All inputs produce the same synchronous placeholder.
- // The background thread produces the real summary (or "No changes to summarize"
- // for the default branch).
- use crate::commands::list::model::{ItemKind, WorktreeData};
-
- let mut main_item = ListItem::new_branch("abc123".to_string(), "main".to_string());
- main_item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- is_main: true,
- ..Default::default()
- }));
-
- let feature_item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
-
- // Direct call and compute_preview dispatch both return the placeholder
- assert_snapshot!(
- "direct",
- WorktreeSkimItem::compute_summary_preview(&main_item)
- );
- assert_snapshot!(
- "via_compute_preview",
- WorktreeSkimItem::compute_preview(&feature_item, PreviewMode::Summary, 80, 40)
- );
+ fn test_loading_placeholder_all_modes() {
+ // Verifies wording and refresh-key hint per mode.
+ for (name, mode) in [
+ ("working_tree", PreviewMode::WorkingTree),
+ ("log", PreviewMode::Log),
+ ("branch_diff", PreviewMode::BranchDiff),
+ ("upstream_diff", PreviewMode::UpstreamDiff),
+ ("summary", PreviewMode::Summary),
+ ] {
+ assert_snapshot!(
+ format!("loading_placeholder_{name}"),
+ WorktreeSkimItem::loading_placeholder(mode)
+ );
+ }
}
#[test]
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index d770dce47..15b71397b 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -6,6 +6,7 @@ mod items;
mod log_formatter;
mod pager;
mod preview;
+mod preview_orchestrator;
mod summary;
use std::cell::RefCell;
@@ -18,7 +19,6 @@ use std::time::Instant;
use anyhow::Context;
// bounded/unbounded/Sender are re-exported by skim::prelude
-use dashmap::DashMap;
use skim::prelude::*;
use skim::reader::CommandCollector;
use worktrunk::git::{Repository, current_or_recover};
@@ -41,6 +41,7 @@ use crate::output::handle_switch_output;
use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};
use preview::{PreviewLayout, PreviewMode, PreviewState};
+use preview_orchestrator::PreviewOrchestrator;
/// Action selected by the user in the picker.
enum PickerAction {
@@ -281,8 +282,10 @@ pub fn handle_picker(
cli_remotes: bool,
change_dir_flag: Option<bool>,
) -> anyhow::Result<()> {
- // Interactive picker requires a terminal for the TUI
- if !std::io::stdin().is_terminal() {
+ // Interactive picker requires a terminal for the TUI. The dry-run path
+ // bypasses skim entirely, so no TTY is required — useful for tests and
+ // for diagnosing the pre-compute pipeline from scripts.
+ if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_none() && !std::io::stdin().is_terminal() {
anyhow::bail!("Interactive picker requires an interactive terminal");
}
@@ -297,6 +300,32 @@ pub fn handle_picker(
// Initialize preview mode state file (auto-cleanup on drop)
let state = PreviewState::new();
+ // Preview cache + dedicated pool are created up-front so the speculative
+ // first-item preview can run in parallel with `collect::collect` below.
+ let orchestrator = PreviewOrchestrator::new();
+ let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
+
+ // Speculative warm-up: the picker sorts the current worktree first, and
+ // the default tab (WorkingTree = `git diff HEAD` in that worktree) is
+ // what skim will render first. Kicking this off before `collect::collect`
+ // overlaps preview compute with list collection (up to 500ms budget).
+ // The real spawn later skips this key via `contains_key`.
+ if let (Ok(Some(branch)), Ok(path)) = (
+ repo.current_worktree().branch(),
+ repo.current_worktree().root(),
+ ) {
+ use super::list::model::{ItemKind, ListItem, WorktreeData};
+ let mut item = ListItem::new_branch(String::new(), branch);
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path,
+ ..Default::default()
+ }));
+ // num_items doesn't matter for Right (dims independent of it); for
+ // Down it only affects height, which doesn't alter pager wrapping.
+ let dims = state.initial_layout.preview_dimensions(0);
+ orchestrator.spawn_preview(Arc::new(item), PreviewMode::WorkingTree, dims);
+ }
+
// Gather list data using simplified collection (buffered mode)
// Skip expensive operations not needed for picker UI
let skip_tasks: std::collections::HashSet<collect::TaskKind> =
@@ -348,9 +377,6 @@ pub fn handle_picker(
let header_display_text = header_line.render();
let header_plain_text = header_line.plain_text();
- // Create shared cache for all preview modes (pre-computed in background)
- let preview_cache: PreviewCache = Arc::new(DashMap::new());
-
// Convert to skim items using the layout system for rendering
// Keep Arc<ListItem> refs for background pre-computation
let mut items_for_precompute: Vec<Arc<super::list::model::ListItem>> = Vec::new();
@@ -518,35 +544,33 @@ pub fn handle_picker(
PreviewMode::UpstreamDiff,
];
- for item in &items_for_precompute {
+ // Spawn order (rayon dispatches FIFO):
+ // 1. First item's modes — user lands here and may tab-cycle immediately.
+ // 2. Mode-major for remaining items — the default tab (WorkingTree)
+ // warms across the full list before any off-default mode starts.
+ let dims = (preview_width, preview_height);
+ if let Some(first) = items_for_precompute.first() {
for mode in modes {
- let cache = Arc::clone(&preview_cache);
- let item = Arc::clone(item);
- rayon::spawn(move || {
- let cache_key = (item.branch_name().to_string(), mode);
- cache.entry(cache_key).or_insert_with(|| {
- WorktreeSkimItem::compute_and_page_preview(
- &item,
- mode,
- preview_width,
- preview_height,
- )
- });
- });
+ orchestrator.spawn_preview(Arc::clone(first), mode, dims);
+ }
+ }
+ for mode in modes {
+ for item in items_for_precompute.iter().skip(1) {
+ orchestrator.spawn_preview(Arc::clone(item), mode, dims);
}
}
- // Queue summary generation after tabs 1-4 so git previews get rayon priority.
+ // Summaries run last: each LLM call can take seconds, so queueing them
+ // behind fast git previews keeps preview tabs warming promptly. First
+ // item's summary still goes first within the summary batch so a user
+ // who sits on the top entry gets a head start.
if config.list.summary() && config.commit_generation.is_configured() {
let llm_command = config.commit_generation.command.clone().unwrap();
- for item in &items_for_precompute {
- let item = Arc::clone(item);
- let cache = Arc::clone(&preview_cache);
- let cmd = llm_command.clone();
- let repo = repo.clone();
- rayon::spawn(move || {
- summary::generate_and_cache_summary(&item, &cmd, &cache, &repo);
- });
+ if let Some(first) = items_for_precompute.first() {
+ orchestrator.spawn_summary(Arc::clone(first), llm_command.clone(), repo.clone());
+ }
+ for item in items_for_precompute.iter().skip(1) {
+ orchestrator.spawn_summary(Arc::clone(item), llm_command.clone(), repo.clone());
}
} else {
// No LLM configured or summaries disabled — insert config hint so the
@@ -569,6 +593,15 @@ pub fn handle_picker(
}
}
+ // Dry-run: wait for all pre-compute tasks and dump the cache as JSON
+ // instead of launching skim. Used by tests and for diagnosing
+ // "previews never load" bugs without a TTY.
+ if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_some() {
+ orchestrator.wait_for_idle();
+ println!("{}", orchestrator.dump_cache_json());
+ return Ok(());
+ }
+
// Run skim (single invocation — alt-r uses reload, not re-launch)
let output = Skim::run_with(&options, Some(rx));
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
new file mode 100644
index 000000000..665e882e9
--- /dev/null
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -0,0 +1,251 @@
+//! Background preview pre-compute orchestration.
+//!
+//! Owns the dedicated rayon pool and preview cache for the picker, so the
+//! pre-compute pipeline is testable without standing up skim. The picker
+//! entry point (`run_picker`) uses this for its real spawns; the dry-run
+//! path (`WORKTRUNK_PICKER_DRY_RUN`) uses it to wait for completion and dump the
+//! cache to stdout.
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Duration;
+
+use dashmap::DashMap;
+use worktrunk::git::Repository;
+
+use super::items::{PreviewCache, WorktreeSkimItem};
+use super::preview::PreviewMode;
+use super::summary;
+use crate::commands::list::model::ListItem;
+
+struct PendingGuard(Arc<AtomicUsize>);
+
+impl Drop for PendingGuard {
+ fn drop(&mut self) {
+ self.0.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+pub(super) struct PreviewOrchestrator {
+ pub(super) cache: PreviewCache,
+ pool: Option<Arc<rayon::ThreadPool>>,
+ pending: Arc<AtomicUsize>,
+}
+
+impl PreviewOrchestrator {
+ pub(super) fn new() -> Self {
+ let cache = Arc::new(DashMap::new());
+ let pool = rayon::ThreadPoolBuilder::new()
+ .num_threads(crate::rayon_thread_count())
+ .thread_name(|i| format!("picker-preview-{i}"))
+ .build()
+ .ok()
+ .map(Arc::new);
+ Self {
+ cache,
+ pool,
+ pending: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+
+ /// Spawn a preview compute task. Returns immediately.
+ ///
+ /// Idempotent on the cache key: if another task already populated it,
+ /// this one short-circuits after the `contains_key` check. Compute
+ /// happens outside any DashMap lock so skim's UI thread (which calls
+ /// `preview()` synchronously and reads via `DashMap::get`) is never
+ /// blocked on a shard write held across git/pager subprocesses.
+ pub(super) fn spawn_preview(
+ &self,
+ item: Arc<ListItem>,
+ mode: PreviewMode,
+ dims: (usize, usize),
+ ) {
+ let cache = Arc::clone(&self.cache);
+ let (w, h) = dims;
+ self.spawn_task(move || {
+ let cache_key = (item.branch_name().to_string(), mode);
+ if cache.contains_key(&cache_key) {
+ return;
+ }
+ let value = WorktreeSkimItem::compute_and_page_preview(&item, mode, w, h);
+ cache.insert(cache_key, value);
+ });
+ }
+
+ /// 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);
+ self.spawn_task(move || {
+ summary::generate_and_cache_summary(&item, &llm_command, &cache, &repo);
+ });
+ }
+
+ fn spawn_task<F: FnOnce() + Send + 'static>(&self, task: F) {
+ self.pending.fetch_add(1, Ordering::SeqCst);
+ let guard = PendingGuard(Arc::clone(&self.pending));
+ let wrapped = move || {
+ // Guard decrements on drop, so a panic inside `task` still
+ // releases the counter — otherwise `wait_for_idle` hangs
+ // forever on any panicking preview task.
+ let _g = guard;
+ task();
+ };
+ match &self.pool {
+ Some(pool) => pool.spawn(wrapped),
+ None => rayon::spawn(wrapped),
+ }
+ }
+
+ /// Block until all 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.
+ pub(super) fn wait_for_idle(&self) {
+ while self.pending.load(Ordering::SeqCst) > 0 {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }
+
+ /// Dump cache state as JSON for dry-run diagnostics. Byte-length only
+ /// (not content) keeps output small and deterministic across terminals.
+ pub(super) fn dump_cache_json(&self) -> String {
+ let mut entries: Vec<_> = self
+ .cache
+ .iter()
+ .map(|e| {
+ let (branch, mode) = e.key();
+ (branch.clone(), *mode as u8, e.value().len())
+ })
+ .collect();
+ entries.sort();
+
+ let items: Vec<String> = entries
+ .iter()
+ .map(|(branch, mode, bytes)| {
+ format!(" {{ \"branch\": {branch:?}, \"mode\": {mode}, \"bytes\": {bytes} }}")
+ })
+ .collect();
+ format!("{{\n \"entries\": [\n{}\n ]\n}}", items.join(",\n"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::commands::list::model::{ItemKind, WorktreeData};
+ use std::fs;
+ use worktrunk::testing::TestRepo;
+
+ fn dirty_worktree_item() -> (TestRepo, Arc<ListItem>) {
+ let t = TestRepo::new();
+ fs::write(t.path().join("README.md"), "# Project\n").unwrap();
+ t.repo.run_command(&["add", "README.md"]).unwrap();
+ t.repo.run_command(&["commit", "-m", "initial"]).unwrap();
+ // Dirty the working tree so WorkingTree diff has content.
+ fs::write(t.path().join("README.md"), "# Project\nmore\n").unwrap();
+
+ let head = t
+ .repo
+ .run_command(&["rev-parse", "HEAD"])
+ .unwrap()
+ .trim()
+ .to_string();
+ let mut item = ListItem::new_branch(head, "main".to_string());
+ item.kind = ItemKind::Worktree(Box::new(WorktreeData {
+ path: t.path().to_path_buf(),
+ ..Default::default()
+ }));
+ (t, Arc::new(item))
+ }
+
+ /// End-to-end: orchestrator spawns real previews, populates the cache.
+ /// Regression test for the "previews never load" class of bugs — if the
+ /// spawn pipeline silently fails, this catches it without needing skim.
+ #[test]
+ fn orchestrator_populates_cache_for_real_worktree() {
+ let (_t, item) = dirty_worktree_item();
+
+ let orch = PreviewOrchestrator::new();
+ orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));
+ orch.spawn_preview(Arc::clone(&item), PreviewMode::Log, (80, 24));
+ orch.wait_for_idle();
+
+ let wt_key = ("main".to_string(), PreviewMode::WorkingTree);
+ let log_key = ("main".to_string(), PreviewMode::Log);
+ assert!(
+ orch.cache.contains_key(&wt_key),
+ "WorkingTree preview not cached"
+ );
+ assert!(orch.cache.contains_key(&log_key), "Log preview not cached");
+ assert!(
+ !orch.cache.get(&wt_key).unwrap().is_empty(),
+ "WorkingTree preview was empty"
+ );
+ }
+
+ #[test]
+ fn duplicate_spawn_short_circuits() {
+ let (_t, item) = dirty_worktree_item();
+
+ let orch = PreviewOrchestrator::new();
+ orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));
+ orch.wait_for_idle();
+ let first = orch
+ .cache
+ .get(&("main".to_string(), PreviewMode::WorkingTree))
+ .unwrap()
+ .value()
+ .clone();
+
+ // Second spawn should hit `contains_key` and skip.
+ orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));
+ orch.wait_for_idle();
+ let second = orch
+ .cache
+ .get(&("main".to_string(), PreviewMode::WorkingTree))
+ .unwrap()
+ .value()
+ .clone();
+ assert_eq!(first, second);
+ }
+
+ /// `spawn_summary` delegates to the same spawn-task machinery as
+ /// `spawn_preview`, but via the LLM summary path. The test uses `/bin/cat`
+ /// as a fake LLM command (it echoes the prompt back), so the test stays
+ /// hermetic — no real LLM is invoked, but the cache receives a Summary
+ /// entry proving the task ran to completion.
+ #[test]
+ fn spawn_summary_populates_cache() {
+ let (t, item) = dirty_worktree_item();
+ let repo = worktrunk::git::Repository::at(t.path()).unwrap();
+
+ let orch = PreviewOrchestrator::new();
+ orch.spawn_summary(Arc::clone(&item), "/bin/cat".to_string(), repo);
+ orch.wait_for_idle();
+
+ assert!(
+ orch.cache
+ .contains_key(&("main".to_string(), PreviewMode::Summary)),
+ "Summary entry not cached"
+ );
+ }
+
+ #[test]
+ fn dump_cache_json_format() {
+ let orch = PreviewOrchestrator::new();
+ orch.cache.insert(
+ ("branch-a".to_string(), PreviewMode::WorkingTree),
+ "x".to_string(),
+ );
+ orch.cache
+ .insert(("branch-b".to_string(), PreviewMode::Log), "xy".to_string());
+ let json = orch.dump_cache_json();
+ // Structural assertion — future field additions shouldn't flake the test.
+ let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 2);
+ }
+}
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 f75be4676..857335c0d 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,6 +2,4 @@
source: src/commands/picker/items.rs
expression: "cache_miss.preview_for_mode(PreviewMode::Summary, 80, 40)"
---
-○ Generating summary...
-
-Press 5 again to refresh once generation completes.
+○ Generating summary. Press 5 again to refresh.
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__direct.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__direct.snap
deleted file mode 100644
index 8dea121a3..000000000
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__direct.snap
+++ /dev/null
@@ -1,7 +0,0 @@
----
-source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::compute_summary_preview(&main_item)"
----
-○ Generating summary...
-
-Press 5 again to refresh once generation completes.
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
new file mode 100644
index 000000000..a035cbc70
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_branch_diff.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/picker/items.rs
+expression: "WorktreeSkimItem::loading_placeholder(mode)"
+---
+○ Loading branch diff. Press 3 again to refresh.
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
new file mode 100644
index 000000000..d19bea017
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_log.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/picker/items.rs
+expression: "WorktreeSkimItem::loading_placeholder(mode)"
+---
+○ Loading log. Press 2 again to refresh.
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
new file mode 100644
index 000000000..4599a5d66
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_summary.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/picker/items.rs
+expression: "WorktreeSkimItem::loading_placeholder(mode)"
+---
+○ Generating summary. Press 5 again to refresh.
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
new file mode 100644
index 000000000..e4a13b76f
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_upstream_diff.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/picker/items.rs
+expression: "WorktreeSkimItem::loading_placeholder(mode)"
+---
+○ Loading upstream diff. Press 4 again to refresh.
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
new file mode 100644
index 000000000..5ac020294
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__loading_placeholder_working_tree.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/picker/items.rs
+expression: "WorktreeSkimItem::loading_placeholder(mode)"
+---
+○ Loading working-tree diff. Press 1 again to refresh.
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__via_compute_preview.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__via_compute_preview.snap
deleted file mode 100644
index 015d5bbf1..000000000
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__via_compute_preview.snap
+++ /dev/null
@@ -1,7 +0,0 @@
----
-source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::compute_preview(&feature_item, PreviewMode::Summary, 80, 40)"
----
-○ Generating summary...
-
-Press 5 again to refresh once generation completes.
diff --git a/src/main.rs b/src/main.rs
index 2be8e11a7..bff348234 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -914,19 +914,24 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
})
}
+/// Rayon thread count sized for mixed git+network I/O workloads.
+///
+/// `wt list` and the picker's preview pre-compute both run git subprocesses
+/// (often blocked on pipe reads) alongside occasional network requests. 2x CPU
+/// cores lets threads waiting on I/O overlap with compute work without excessive
+/// context-switch overhead.
+pub(crate) fn rayon_thread_count() -> usize {
+ std::thread::available_parallelism()
+ .map(|n| n.get() * 2)
+ .unwrap_or(8)
+}
+
fn init_rayon_thread_pool() {
- // Configure Rayon's global thread pool for mixed I/O workloads.
- // The `wt list` command runs git operations (CPU + disk I/O) and network
- // requests (CI status, URL health checks) in parallel. Using 2x CPU cores
- // allows threads blocked on I/O to overlap with compute work.
- //
// Override with RAYON_NUM_THREADS=N for benchmarking.
let num_threads = if std::env::var_os("RAYON_NUM_THREADS").is_some() {
0 // Let Rayon handle the env var (includes validation)
} else {
- std::thread::available_parallelism()
- .map(|n| n.get() * 2)
- .unwrap_or(8)
+ rayon_thread_count()
};
let _ = rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 27d4c0d85..933fbaf94 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -64,4 +64,5 @@ pub mod step_prune;
pub mod step_relocate;
pub mod switch;
pub mod switch_picker;
+pub mod switch_picker_dry_run;
pub mod user_hooks;
diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rs
new file mode 100644
index 000000000..04ff22cba
--- /dev/null
+++ b/tests/integration_tests/switch_picker_dry_run.rs
@@ -0,0 +1,99 @@
+//! Integration tests for the picker's `WORKTRUNK_PICKER_DRY_RUN` path.
+//!
+//! Setting the env var bypasses skim entirely: the picker runs the full
+//! pre-compute pipeline (speculative first-item spawn, collect, full spawn
+//! loop, summaries), waits for all tasks, prints the cache inventory as JSON,
+//! and exits. This exercises the non-TUI wiring inside `handle_picker`
+//! without needing a PTY.
+//!
+//! Unix-only: `wt switch` rejects the interactive picker on Windows
+//! ("Interactive picker is not available on Windows") before the dry-run
+//! bypass is consulted.
+
+#![cfg(unix)]
+
+use crate::common::{TestRepo, repo};
+use rstest::rstest;
+
+/// Runs the dry-run picker with summaries disabled (default). Covers the
+/// base cache-dump path and the `else` branch that inserts a config hint
+/// in place of real summaries.
+#[rstest]
+fn test_picker_dry_run_dumps_cache_json(mut repo: TestRepo) {
+ repo.add_worktree("feature-a");
+ repo.add_worktree("feature-b");
+
+ let output = repo
+ .wt_command()
+ .args(["switch"])
+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "dry-run should exit 0; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
+ let entries = parsed["entries"]
+ .as_array()
+ .expect("top-level `entries` array");
+
+ assert!(
+ !entries.is_empty(),
+ "expected at least one cache entry, got: {stdout}"
+ );
+
+ // Every entry has {branch: string, mode: u8, bytes: usize}. Asserting
+ // schema (not specific branches/modes) keeps the test robust to fixture
+ // changes while still covering the dump format.
+ for e in entries {
+ assert!(e["branch"].is_string(), "entry missing branch: {e}");
+ assert!(e["mode"].is_number(), "entry missing mode: {e}");
+ assert!(e["bytes"].is_number(), "entry missing bytes: {e}");
+ }
+}
+
+/// Same as above but with `list.summary=true` and a fake LLM command
+/// configured, to exercise the `spawn_summary` branch in `handle_picker`.
+/// Uses `/bin/cat` as the LLM: it reads stdin and writes it back, so the
+/// summary pipeline runs end-to-end without a real model.
+#[rstest]
+fn test_picker_dry_run_with_summary(mut repo: TestRepo) {
+ repo.add_worktree("feature-a");
+
+ let output = repo
+ .wt_command()
+ .args(["switch"])
+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")
+ .env("WORKTRUNK_LIST__SUMMARY", "true")
+ .env("WORKTRUNK_COMMIT__GENERATION__COMMAND", "/bin/cat")
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "dry-run should exit 0; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
+ let entries = parsed["entries"]
+ .as_array()
+ .expect("top-level `entries` array");
+
+ // Summary mode is `5` (see `PreviewMode` in `src/commands/picker/preview.rs`).
+ // At least one entry should be a summary when summaries are enabled —
+ // that proves the summary spawn branch ran to completion. Mode 4
+ // (UpstreamDiff) is always present as part of the normal preview
+ // modes array, so asserting on it would not prove anything about
+ // the summary path.
+ assert!(
+ entries.iter().any(|e| e["mode"] == 5),
+ "expected at least one Summary entry, got: {stdout}"
+ );
+}