Skip to content

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

Progressive rendering in wt switch picker (#2231)

Maximilian Roos71a8c53736ef
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 87c4ff57c..47dd89695 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -117,7 +117,7 @@
#
# [switch.picker]
# pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-# timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+# timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
#
# ### Step
#
diff --git a/docs/content/config.md b/docs/content/config.md
index 6eccf8fd8..1e700ccb1 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -206,7 +206,7 @@ cd = true # Change directory after switching (--no-cd to skip)
[switch.picker]
pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
```
### Step
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index cc3a6c9db..cb1d666d8 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -205,7 +205,7 @@ cd = true # Change directory after switching (--no-cd to skip)
[switch.picker]
pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
```
### Step
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index bdc03e627..f117f1258 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1903,7 +1903,7 @@ cd = true # Change directory after switching (--no-cd to skip)
[switch.picker]
pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
```
### Step
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index a783893cd..dfd1d48c4 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -269,6 +269,38 @@ fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> HashSet<&str> {
.collect()
}
+/// Progressive callback used by the picker to mirror `wt list`'s skeleton-first
+/// rendering into the skim TUI.
+///
+/// `collect()` owns the layout and re-renders each row as task results land.
+/// The handler receives pre-rendered strings so it doesn't need to share the
+/// layout across threads (`LayoutConfig` is `!Sync` via an interior
+/// `Cell<&'static str>`).
+#[cfg_attr(not(unix), allow(dead_code))]
+pub trait PickerProgressHandler: Send + Sync {
+ /// Fired once after items are initialized and layout is computed, but
+ /// before any task results arrive. `rendered` is one entry per item,
+ /// with fast fields (branch, path, head) populated and blank
+ /// placeholders for slow cells. `header` is the column-header line;
+ /// the handler calls `render()` / `plain_text()` as needed.
+ fn on_skeleton(
+ &self,
+ items: Vec<super::model::ListItem>,
+ rendered: Vec<String>,
+ header: worktrunk::styling::StyledLine,
+ );
+
+ /// Fired after a single task result updates row `idx`. `rendered` is the
+ /// new line — write it through the item's shared state so skim picks it
+ /// up on the next heartbeat.
+ fn on_update(&self, idx: usize, rendered: String);
+
+ /// Fired at the 200ms reveal deadline. Entry per row: `Some(line)` for
+ /// rows still at skeleton state (placeholder needs promoting to `·`),
+ /// `None` for rows that already received real data via `on_update`.
+ fn on_reveal(&self, rendered: Vec<Option<String>>);
+}
+
/// Controls how show flags (branches/remotes/full) are determined in [`collect`].
#[cfg_attr(not(unix), allow(dead_code))]
pub enum ShowConfig {
@@ -281,6 +313,14 @@ pub enum ShowConfig {
/// Wall-clock deadline for the collect phase. `None` uses the default
/// [`DRAIN_TIMEOUT`](results::DRAIN_TIMEOUT) and shows a warning on timeout.
collect_deadline: Option<std::time::Instant>,
+ /// Width used when computing the layout. `None` falls back to the
+ /// terminal width; the picker passes an explicit width because the
+ /// list only gets part of the terminal (the rest is preview).
+ list_width: Option<usize>,
+ /// Progressive callback for the picker. When set, `collect` emits
+ /// skeleton + per-update events through it. Results still flow into
+ /// the returned `ListData` as usual.
+ progressive_handler: Option<std::sync::Arc<dyn PickerProgressHandler>>,
},
/// Raw CLI flags; config resolution deferred to collect's parallel phase
/// so project_identifier runs concurrently with other git operations.
@@ -292,6 +332,66 @@ pub enum ShowConfig {
},
}
+/// Per-row render cache shared by the `wt list` progressive table and the
+/// picker's `PickerProgressHandler`. Both sinks write through the same dedup
+/// path so one rendering pass serves both.
+///
+/// `set_result` records a new render and returns `Some(line)` only when it
+/// differs from the cached value.
+///
+/// `set_reveal` runs after `layout.placeholder` is promoted from blank to
+/// `·`. Every row is re-rendered (skeleton for rows with no data yet to
+/// avoid surfacing seeded defaults like "55y"; `format_list_item_line` for
+/// rows that received at least one result, so still-pending cells pick up
+/// the promoted `·`). Dedup against the cache keeps emitted updates minimal.
+struct RowCache {
+ last: Vec<String>,
+ has_data: Vec<bool>,
+}
+
+impl RowCache {
+ fn new(n: usize) -> Self {
+ Self {
+ last: vec![String::new(); n],
+ has_data: vec![false; n],
+ }
+ }
+
+ fn set_result(&mut self, idx: usize, rendered: String) -> Option<String> {
+ self.has_data[idx] = true;
+ if self.last[idx] == rendered {
+ None
+ } else {
+ self.last[idx] = rendered.clone();
+ Some(rendered)
+ }
+ }
+
+ fn set_reveal(
+ &mut self,
+ items: &[super::model::ListItem],
+ layout: &super::layout::LayoutConfig,
+ ) -> Vec<Option<String>> {
+ items
+ .iter()
+ .enumerate()
+ .map(|(idx, item)| {
+ let new = if self.has_data[idx] {
+ layout.format_list_item_line(item)
+ } else {
+ layout.render_skeleton_row(item).render()
+ };
+ if self.last[idx] == new {
+ None
+ } else {
+ self.last[idx] = new.clone();
+ Some(new)
+ }
+ })
+ .collect()
+ }
+}
+
/// Build the progressive-table footer shown while the drain is stalled.
///
/// Pure so it can be snapshot-tested without spinning up the live table.
@@ -420,58 +520,71 @@ pub fn collect(
let url_template = url_template_cell.into_inner().unwrap();
// Resolve show flags: merge CLI overrides with config (warmed in parallel phase)
- let (show_branches, show_remotes, skip_tasks, command_timeout, collect_deadline) =
- match show_config {
- ShowConfig::Resolved {
- show_branches,
- show_remotes,
- skip_tasks,
- command_timeout,
- collect_deadline,
- } => (
+ let (
+ show_branches,
+ show_remotes,
+ skip_tasks,
+ command_timeout,
+ collect_deadline,
+ list_width,
+ progressive_handler,
+ ) = match show_config {
+ ShowConfig::Resolved {
+ show_branches,
+ show_remotes,
+ skip_tasks,
+ command_timeout,
+ collect_deadline,
+ list_width,
+ progressive_handler,
+ } => (
+ show_branches,
+ show_remotes,
+ skip_tasks,
+ command_timeout,
+ collect_deadline,
+ list_width,
+ progressive_handler,
+ ),
+ ShowConfig::DeferredToParallel {
+ cli_branches,
+ cli_remotes,
+ cli_full,
+ } => {
+ let config = repo.config();
+ let show_branches = cli_branches || config.list.branches();
+ let show_remotes = cli_remotes || config.list.remotes();
+ let show_full = cli_full || config.list.full();
+ let skip_tasks: HashSet<TaskKind> = if show_full {
+ HashSet::new()
+ } else {
+ [
+ TaskKind::BranchDiff,
+ TaskKind::CiStatus,
+ TaskKind::SummaryGenerate,
+ ]
+ .into_iter()
+ .collect()
+ };
+ // Resolve timeouts from merged config (--full disables both)
+ let (command_timeout, collect_deadline) = if show_full {
+ (None, None)
+ } else {
+ let task_timeout = config.list.task_timeout();
+ let deadline = config.list.timeout().map(|d| std::time::Instant::now() + d);
+ (task_timeout, deadline)
+ };
+ (
show_branches,
show_remotes,
skip_tasks,
command_timeout,
collect_deadline,
- ),
- ShowConfig::DeferredToParallel {
- cli_branches,
- cli_remotes,
- cli_full,
- } => {
- let config = repo.config();
- let show_branches = cli_branches || config.list.branches();
- let show_remotes = cli_remotes || config.list.remotes();
- let show_full = cli_full || config.list.full();
- let skip_tasks: HashSet<TaskKind> = if show_full {
- HashSet::new()
- } else {
- [
- TaskKind::BranchDiff,
- TaskKind::CiStatus,
- TaskKind::SummaryGenerate,
- ]
- .into_iter()
- .collect()
- };
- // Resolve timeouts from merged config (--full disables both)
- let (command_timeout, collect_deadline) = if show_full {
- (None, None)
- } else {
- let task_timeout = config.list.task_timeout();
- let deadline = config.list.timeout().map(|d| std::time::Instant::now() + d);
- (task_timeout, deadline)
- };
- (
- show_branches,
- show_remotes,
- skip_tasks,
- command_timeout,
- collect_deadline,
- )
- }
- };
+ None,
+ None,
+ )
+ }
+ };
// Filter local branches to those without worktrees (CPU-only, no git commands)
let branches_without_worktrees = if show_branches {
@@ -651,19 +764,29 @@ pub fn collect(
effective_skip_tasks.insert(TaskKind::SummaryGenerate);
}
- // Calculate layout from items (worktrees, local branches, and remote branches)
- let layout = super::layout::calculate_layout_from_basics(
- &all_items,
- &effective_skip_tasks,
- &main_worktree.path,
- url_template.as_deref(),
- );
+ // Calculate layout from items (worktrees, local branches, and remote branches).
+ // The picker passes an explicit width because the list only gets part of the
+ // terminal — the rest belongs to the preview pane.
+ let layout = match list_width {
+ Some(width) => super::layout::calculate_layout_with_width(
+ &all_items,
+ &effective_skip_tasks,
+ width,
+ &main_worktree.path,
+ url_template.as_deref(),
+ ),
+ None => super::layout::calculate_layout_from_basics(
+ &all_items,
+ &effective_skip_tasks,
+ &main_worktree.path,
+ url_template.as_deref(),
+ ),
+ };
// Single-line invariant: use safe width to prevent line wrapping
let max_width = crate::display::terminal_width();
// Create collection options from skip set
- let returned_skip_tasks = effective_skip_tasks.clone();
let options = CollectOptions {
skip_tasks: effective_skip_tasks,
url_template: url_template.clone(),
@@ -728,6 +851,26 @@ pub fn collect(
None
};
+ // Picker mirrors `wt list`'s blank→`·` reveal. The placeholder starts
+ // blank so fast completions don't flash loading dots; the Reveal event
+ // below promotes it to `·` at 200ms. `show_progress=false` (the picker
+ // path today) skips the block above, so set it here unconditionally
+ // when a handler is present.
+ if progressive_handler.is_some() {
+ layout.placeholder.set(super::render::PLACEHOLDER_BLANK);
+ }
+
+ // Deliver the skeleton to the picker handler. Rendered strings use the
+ // blank placeholder so skim's initial render mirrors the `wt list`
+ // pre-reveal look.
+ if let Some(handler) = progressive_handler.as_ref() {
+ let skeletons: Vec<String> = all_items
+ .iter()
+ .map(|item| layout.render_skeleton_row(item).render())
+ .collect();
+ handler.on_skeleton(all_items.clone(), skeletons, layout.render_header_line());
+ }
+
/// Delay before the `·` loading indicator replaces blank placeholders.
/// Tuned so commands that finish promptly never flash the dots.
/// Overridable at runtime via `WORKTRUNK_PLACEHOLDER_REVEAL_MS` (milliseconds)
@@ -912,9 +1055,11 @@ pub fn collect(
// reveal, and stall hints) can mutate it. Events never run concurrently —
// they fire between channel recvs — so the runtime borrow checks are an
// invariant formalism, never a source of panics.
+ // Table-specific state: footer progress counter, overflow guard,
+ // first-result tracing. `ProgressiveTable` itself owns stdout so the
+ // whole thing is local and non-`Send`.
struct ProgressiveState {
table: ProgressiveTable,
- last_rendered_lines: Vec<String>,
completed_results: usize,
progress_overflow: bool,
first_result_traced: bool,
@@ -924,17 +1069,19 @@ pub fn collect(
let progressive_state = progressive_table.take().map(|table| {
std::cell::RefCell::new(ProgressiveState {
table,
- last_rendered_lines: vec![String::new(); n_items],
completed_results: 0,
progress_overflow: false,
first_result_traced: false,
})
});
+ let mut row_cache = RowCache::new(n_items);
let drain_deadline =
collect_deadline.unwrap_or_else(|| std::time::Instant::now() + results::DRAIN_TIMEOUT);
- let reveal_at = progressive_state.as_ref().map(|_| placeholder_reveal_at);
+ // Reveal fires only when a downstream consumer is listening.
+ let reveal_at = (progressive_state.is_some() || progressive_handler.is_some())
+ .then_some(placeholder_reveal_at);
let drain_outcome = drain_results(
rx,
@@ -944,69 +1091,71 @@ pub fn collect(
drain_deadline,
integration_target.as_deref(),
|event| {
- let Some(state_cell) = progressive_state.as_ref() else {
- return;
- };
- let mut s = state_cell.borrow_mut();
let dim = Style::new().dimmed();
let total_results = expected_results.count();
match event {
results::DrainEvent::Result { item_idx, item } => {
- if !s.first_result_traced {
- s.first_result_traced = true;
- worktrunk::shell_exec::trace_instant("First result received");
- }
+ let rendered = layout.format_list_item_line(item);
+ let changed = row_cache.set_result(item_idx, rendered);
- s.completed_results += 1;
+ if let Some(state_cell) = progressive_state.as_ref() {
+ let mut s = state_cell.borrow_mut();
+ if !s.first_result_traced {
+ s.first_result_traced = true;
+ worktrunk::shell_exec::trace_instant("First result received");
+ }
- debug_assert!(
- s.completed_results <= total_results,
- "completed ({}) > expected ({}): task result sent without registering expectation",
- s.completed_results,
- total_results
- );
- if s.completed_results > total_results {
- s.progress_overflow = true;
- }
+ s.completed_results += 1;
+ debug_assert!(
+ s.completed_results <= total_results,
+ "completed ({}) > expected ({}): task result sent without registering expectation",
+ s.completed_results,
+ total_results
+ );
+ if s.completed_results > total_results {
+ s.progress_overflow = true;
+ }
- let completed = s.completed_results;
- let footer_msg = format!(
- "{INFO_SYMBOL} {dim}{footer_base} ({completed}/{total_results} loaded){dim:#}"
- );
- s.table.update_footer(footer_msg);
+ let completed = s.completed_results;
+ let footer_msg = format!(
+ "{INFO_SYMBOL} {dim}{footer_base} ({completed}/{total_results} loaded){dim:#}"
+ );
+ s.table.update_footer(footer_msg);
- let rendered = layout.format_list_item_line(item);
- if rendered != s.last_rendered_lines[item_idx] {
- s.last_rendered_lines[item_idx] = rendered.clone();
- s.table.update_row(item_idx, rendered);
+ if let Some(line) = &changed {
+ s.table.update_row(item_idx, line.clone());
+ }
+
+ if let Err(e) = s.table.flush() {
+ log::debug!("Progressive table flush failed: {}", e);
+ }
}
- if let Err(e) = s.table.flush() {
- log::debug!("Progressive table flush failed: {}", e);
+ if let Some(handler) = progressive_handler.as_ref()
+ && let Some(line) = changed
+ {
+ handler.on_update(item_idx, line);
}
}
results::DrainEvent::Reveal { items } => {
- // T+200ms reveal: promote blank placeholders to `·` and
- // re-render every row so still-pending cells pick up
- // the dot. Rows that received a result use
- // `format_list_item_line`; untouched rows use
- // `render_skeleton_row` (which avoids surfacing seeded
- // defaults like "55y" for skipped tasks).
layout.placeholder.set(super::render::PLACEHOLDER);
- for (idx, item) in items.iter().enumerate() {
- let rendered = if s.last_rendered_lines[idx].is_empty() {
- layout.render_skeleton_row(item).render()
- } else {
- layout.format_list_item_line(item)
- };
- if rendered != s.last_rendered_lines[idx] {
- s.last_rendered_lines[idx] = rendered.clone();
- s.table.update_row(idx, rendered);
+ let updates = row_cache.set_reveal(items, &layout);
+
+ if let Some(state_cell) = progressive_state.as_ref() {
+ let mut s = state_cell.borrow_mut();
+ for (idx, update) in updates.iter().enumerate() {
+ if let Some(line) = update {
+ s.table.update_row(idx, line.clone());
+ }
+ }
+ if let Err(e) = s.table.flush() {
+ log::debug!("Progressive table reveal flush failed: {}", e);
}
}
- if let Err(e) = s.table.flush() {
- log::debug!("Progressive table reveal flush failed: {}", e);
+
+ if let Some(handler) = progressive_handler.as_ref() {
+ handler.on_reveal(updates);
}
}
results::DrainEvent::Stall {
@@ -1018,19 +1167,23 @@ pub fn collect(
// Name the signal (silence) rather than claiming "stalled":
// the event fires on any 5s lull and reports outstanding
// work, not a root cause.
- let footer_msg = format_stall_footer(
- &footer_base,
- s.completed_results,
- total_results,
- pending_count,
- first_kind,
- first_name,
- );
- if s.table.update_footer(footer_msg)
- && let Err(e) = s.table.flush()
- {
- log::debug!("Progressive table flush failed: {}", e);
+ if let Some(state_cell) = progressive_state.as_ref() {
+ let mut s = state_cell.borrow_mut();
+ let footer_msg = format_stall_footer(
+ &footer_base,
+ s.completed_results,
+ total_results,
+ pending_count,
+ first_kind,
+ first_name,
+ );
+ if s.table.update_footer(footer_msg)
+ && let Err(e) = s.table.flush()
+ {
+ log::debug!("Progressive table flush failed: {}", e);
+ }
}
+ // Picker has no stall UI; heartbeat keeps it responsive.
}
}
},
@@ -1185,11 +1338,7 @@ pub fn collect(
// JSON mode (render_table=false): no rendering, data returned for serialization
worktrunk::shell_exec::trace_instant("List collect complete");
- Ok(Some(super::model::ListData {
- items,
- main_worktree_path: main_worktree.path.clone(),
- skip_tasks: returned_skip_tasks,
- }))
+ Ok(Some(super::model::ListData { items }))
}
// ============================================================================
@@ -1450,4 +1599,58 @@ mod tests {
@"○ Showing 3 worktrees (5/12 loaded, no recent progress; waiting on 3 tasks, including ci-status for feat)"
);
}
+
+ /// `set_result` marks the row as having data and dedups by comparing
+ /// against the cached render; `set_reveal` picks skeleton-vs-format
+ /// per row based on `has_data` and also dedups. These two behaviors
+ /// are load-bearing for the picker's partial-row reveal correctness
+ /// (see the RowCache doc comment).
+ #[test]
+ fn test_row_cache_dedup_and_reveal() {
+ use super::super::layout::calculate_layout_with_width;
+ use super::super::model::ListItem;
+ use std::collections::HashSet;
+ use std::path::Path;
+
+ let items = vec![
+ ListItem::new_branch("aaa".into(), "row-zero".into()),
+ ListItem::new_branch("bbb".into(), "row-one".into()),
+ ];
+ let skip_tasks: HashSet<TaskKind> = HashSet::new();
+ let layout = calculate_layout_with_width(&items, &skip_tasks, 80, Path::new("/tmp"), None);
+
+ let mut cache = RowCache::new(2);
+
+ // First set_result: cache was empty, so the new line is emitted.
+ let first = cache.set_result(0, "row-zero-line-v1".into());
+ assert_eq!(first.as_deref(), Some("row-zero-line-v1"));
+
+ // Same render again → dedup: None.
+ let dup = cache.set_result(0, "row-zero-line-v1".into());
+ assert_eq!(dup, None);
+
+ // Different render → Some again.
+ let changed = cache.set_result(0, "row-zero-line-v2".into());
+ assert_eq!(changed.as_deref(), Some("row-zero-line-v2"));
+
+ // set_reveal after the placeholder flip. Row 0 has data: use
+ // format_list_item_line; the result is different from the cached
+ // synthetic string above so it's emitted as Some. Row 1 has no
+ // data: use render_skeleton_row; cache was empty so it's emitted.
+ layout.placeholder.set(super::super::render::PLACEHOLDER);
+ let updates = cache.set_reveal(&items, &layout);
+ assert_eq!(updates.len(), 2);
+ assert!(
+ updates[0].is_some(),
+ "row 0 had data but cached string was synthetic; reveal must emit new render"
+ );
+ assert!(
+ updates[1].is_some(),
+ "row 1 had no data; reveal must emit skeleton render"
+ );
+
+ // Second reveal with no intervening changes: both rows dedup to None.
+ let updates2 = cache.set_reveal(&items, &layout);
+ assert_eq!(updates2, vec![None, None]);
+ }
}
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 6fb184a84..235068b5e 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -178,7 +178,7 @@ impl WorktreeData {
/// WorktreeData is boxed to reduce the size of ItemKind enum (304 bytes → 24 bytes).
/// This reduces stack pressure when passing ListItem by value and improves cache locality
/// in `Vec<ListItem>` by keeping the discriminant and common fields together.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, Clone)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ItemKind {
Worktree(Box<WorktreeData>),
@@ -191,7 +191,7 @@ pub enum ItemKind {
/// was collected (`None` = not loaded, render shows placeholder). The inner type `U` is
/// whatever the data naturally is — e.g., `AheadBehind` (always has a value, even if zero)
/// or `Option<PrStatus>` (CI may not exist).
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, Clone)]
pub struct ListItem {
// Common fields (present for both worktrees and branches)
#[serde(rename = "head_sha")]
@@ -289,14 +289,6 @@ pub struct ListItem {
/// Container for list command results.
pub struct ListData {
pub items: Vec<ListItem>,
- /// Path to the main worktree, used for computing relative paths in display.
- #[cfg_attr(windows, allow(dead_code))] // Used only by picker module (unix-only)
- pub main_worktree_path: std::path::PathBuf,
- /// Tasks that were skipped during collection (includes runtime gating like
- /// SummaryGenerate disabled when no LLM configured). Callers that recalculate
- /// layout (e.g., the picker at a different width) should use this set.
- #[cfg_attr(windows, allow(dead_code))] // Used only by picker module (unix-only)
- pub skip_tasks: std::collections::HashSet<super::super::collect::TaskKind>,
}
impl ListItem {
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 28a516917..5d6597c12 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -17,9 +17,8 @@ use super::model::{ListItem, PositionMask};
/// is too visually loud for a tight column where most cells are in one state
/// or the other during a render. Revisit and pick a subtle second glyph
/// (e.g. `·` for one, `–` or braille dot for the other) once we can evaluate
-/// them side-by-side in real tables. See `render_list_item_stale` — the
-/// picker-side entry point is preserved so the re-split doesn't need a caller
-/// audit. Also update `src/cli/mod.rs` status-column help table when resplit.
+/// them side-by-side in real tables. Also update `src/cli/mod.rs`
+/// status-column help table when resplit.
pub const PLACEHOLDER: &str = "·";
/// Blank placeholder used by `wt list` during the first ~200ms of progressive
@@ -260,16 +259,6 @@ impl LayoutConfig {
self.render_item_with_placeholder(item, self.placeholder.get())
}
- /// Render with stale placeholders for items where data collection was truncated.
- ///
- /// Currently uses the same `·` as `render_list_item_line`. Kept as a
- /// separate entry point so picker callers signal the semantic difference
- /// (data won't arrive vs. still loading) — see [`PLACEHOLDER`].
- #[cfg_attr(windows, allow(dead_code))] // Used only by picker module (unix-only)
- pub fn render_list_item_stale(&self, item: &ListItem) -> StyledLine {
- self.render_item_with_placeholder(item, self.placeholder.get())
- }
-
fn render_item_with_placeholder(&self, item: &ListItem, placeholder: &str) -> StyledLine {
self.render_line(|column| {
column.render_cell(
@@ -417,8 +406,7 @@ impl ColumnLayout {
// position for unresolved gates, so a row whose Status
// cell is partially loaded renders e.g. `+! · ↕ | ·`
// rather than a cell-level placeholder. The `placeholder`
- // arg comes from `render_list_item_line` or
- // `render_list_item_stale` (both pass `·` today — see
+ // arg comes from `render_list_item_line` (`·` today — see
// `PLACEHOLDER`).
let mut cell = StyledLine::new();
cell.push_raw(
@@ -1324,14 +1312,11 @@ mod tests {
}
#[test]
- fn test_loading_and_stale_both_use_middle_dot() {
+ fn test_loading_uses_middle_dot() {
use super::super::layout::{ColumnLayout, LayoutConfig};
use super::super::model::{ListItem, PositionMask};
use std::path::PathBuf;
- // Both entry points emit `·` today; this is a canary for the
- // temporary collapse (see `PLACEHOLDER`). When the re-split lands,
- // this test gets replaced with one asserting the two glyphs differ.
let layout = LayoutConfig {
columns: vec![ColumnLayout {
kind: ColumnKind::Summary,
@@ -1353,10 +1338,6 @@ mod tests {
let line = layout.render_list_item_line(&item).render();
assert!(line.contains('·'), "expected `·` in: {line}");
assert!(!line.contains('⋯'), "unexpected `⋯` in: {line}");
-
- let stale = layout.render_list_item_stale(&item).render();
- assert!(stale.contains('·'), "expected `·` in: {stale}");
- assert!(!stale.contains('⋯'), "unexpected `⋯` in: {stale}");
}
#[test]
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 9eab40050..cb486eba7 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -4,7 +4,7 @@
use std::borrow::Cow;
use std::collections::HashSet;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use anstyle::Reset;
use color_print::cformat;
@@ -81,11 +81,29 @@ fn compute_diff_preview(args: &[&str], no_changes_msg: &str, width: usize) -> St
output
}
-/// Wrapper to implement SkimItem for ListItem
+/// Wrapper to implement SkimItem for ListItem.
+///
+/// Progressive updates live inside `rendered` — the picker handler rewrites
+/// the ANSI-colored display string in place as task results arrive. Skim
+/// redraws from `display()` on its 100ms heartbeat, so new values surface
+/// without any explicit re-send through the item channel.
+///
+/// `search_text` (what the matcher sees) stays based on fast-only fields
+/// so cached ranks don't need to re-compute when a slow field lands.
pub(super) struct WorktreeSkimItem {
- pub display_text: String,
- pub display_text_with_ansi: String,
+ /// Stable text used for fuzzy matching — branch name + path. Keeping
+ /// this independent of the rendered display means skim's matcher
+ /// cache survives progressive updates.
+ pub search_text: String,
+ /// Current ANSI-colored display line. Starts as the skeleton render;
+ /// replaced in place as data arrives.
+ pub rendered: Arc<Mutex<String>>,
+ /// Branch name — also what `output()` returns when this item is
+ /// selected.
pub branch_name: String,
+ /// Skeleton-snapshot of the underlying ListItem. Used by preview
+ /// computation, which kicks off at skeleton time and doesn't re-run
+ /// as slow fields arrive.
pub item: Arc<ListItem>,
/// Shared cache for pre-computed previews (all modes)
pub preview_cache: PreviewCache,
@@ -93,11 +111,15 @@ pub(super) struct WorktreeSkimItem {
impl SkimItem for WorktreeSkimItem {
fn text(&self) -> Cow<'_, str> {
- Cow::Borrowed(&self.display_text)
+ Cow::Borrowed(&self.search_text)
}
fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {
- skim::AnsiString::parse(&self.display_text_with_ansi)
+ // Clone-under-lock so AnsiString's input outlives the guard.
+ // `AnsiString::parse` returns `AnsiString<'static>`, so the borrow
+ // ends with this function.
+ let snapshot = self.rendered.lock().unwrap().clone();
+ skim::AnsiString::parse(&snapshot)
}
fn output(&self) -> Cow<'_, str> {
@@ -513,8 +535,8 @@ mod tests {
"Add auth module\n\nImplements JWT-based authentication.".to_string(),
);
WorktreeSkimItem {
- display_text: String::new(),
- display_text_with_ansi: String::new(),
+ search_text: String::new(),
+ rendered: Arc::new(Mutex::new(String::new())),
branch_name: "feature".to_string(),
item: Arc::clone(&item),
preview_cache,
@@ -524,8 +546,8 @@ mod tests {
let cache_miss = {
let preview_cache: PreviewCache = Arc::new(DashMap::new());
WorktreeSkimItem {
- display_text: String::new(),
- display_text_with_ansi: String::new(),
+ search_text: String::new(),
+ rendered: Arc::new(Mutex::new(String::new())),
branch_name: "feature".to_string(),
item: Arc::clone(&item),
preview_cache,
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index e0b21a009..9b533603a 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -7,6 +7,7 @@ mod log_formatter;
mod pager;
mod preview;
mod preview_orchestrator;
+mod progressive_handler;
mod summary;
use std::cell::RefCell;
@@ -15,7 +16,6 @@ use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Mutex};
-use std::time::Instant;
use anyhow::Context;
// bounded/unbounded/Sender are re-exported by skim::prelude
@@ -41,7 +41,7 @@ use worktrunk::git::{
BranchDeletionMode, RemoveOptions, delete_branch_if_safe, remove_worktree_with_cleanup,
};
-use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};
+use items::{PreviewCache, WorktreeSkimItem};
use preview::{PreviewLayout, PreviewMode, PreviewState};
use preview_orchestrator::PreviewOrchestrator;
@@ -306,7 +306,9 @@ pub fn handle_picker(
// 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();
+ // Wrapped in `Arc` because the progressive handler (running on the
+ // collect background thread) also calls `spawn_preview`.
+ let orchestrator = Arc::new(PreviewOrchestrator::new());
let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
// Speculative warm-up: the picker sorts the current worktree first, and
@@ -330,119 +332,81 @@ pub fn handle_picker(
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
+ // Skip expensive operations — BranchDiff walks history per item,
+ // CiStatus hits the network. Both are slow enough that waiting for
+ // them adds perceptible cost for a modest column-population win.
let skip_tasks: std::collections::HashSet<collect::TaskKind> =
[collect::TaskKind::BranchDiff, collect::TaskKind::CiStatus]
.into_iter()
.collect();
- // Per-task command timeout from shared [list] config.
+ // Per-task command timeout (bounds any single git invocation) from
+ // shared `[list]` config. Still applies in progressive mode.
let command_timeout = config.list.task_timeout();
- // Wall-clock budget for the entire collect phase (default: 500ms).
- let collect_deadline = config.switch_picker.timeout().map(|d| Instant::now() + d);
-
- let Some(list_data) = collect::collect(
- &repo,
- collect::ShowConfig::Resolved {
- show_branches,
- show_remotes,
- skip_tasks: skip_tasks.clone(),
- command_timeout,
- collect_deadline,
- },
- false, // show_progress (no progress bars)
- false, // render_table (picker renders its own UI)
- )?
- else {
- return Ok(());
- };
+ // Progressive rendering means the picker never blocks waiting for
+ // collect — so there's no UI-freeze budget to bound. The drain runs
+ // until its results channel closes or the fallback DRAIN_TIMEOUT
+ // (120s) fires. The legacy `switch.picker.timeout-ms` config field is
+ // still parsed for schema compat but no longer read.
- // Use the same layout system as `wt list` for proper column alignment
- // List width depends on preview position:
- // - Right layout: skim splits ~50% for list, ~50% for preview
- // - Down layout: list gets full width, preview is below
+ // List width depends on the preview position. Right splits the terminal
+ // ~50/50; Down gives the list the full width. Passed to `collect` so
+ // the skeleton layout matches the picker's actual render width.
let terminal_width = crate::display::terminal_width();
let skim_list_width = match state.initial_layout {
PreviewLayout::Right => terminal_width / 2,
PreviewLayout::Down => terminal_width,
};
- let layout = super::list::layout::calculate_layout_with_width(
- &list_data.items,
- &list_data.skip_tasks,
- skim_list_width,
- &list_data.main_worktree_path,
- None, // URL column not shown in picker
- );
-
- // Render header using layout system (need both plain and styled text for skim)
- let header_line = layout.render_header_line();
- let header_display_text = header_line.render();
- let header_plain_text = header_line.plain_text();
-
- // 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();
- let mut items: Vec<Arc<dyn SkimItem>> = list_data
- .items
- .into_iter()
- .map(|item| {
- let branch_name = item.branch_name().to_string();
-
- // The picker doesn't update progressively, so any column whose data
- // didn't arrive in time won't fill in later. Use the stale placeholder
- // entry point; its glyph is the same `·` as the loading placeholder
- // today but the semantic split is preserved for a future re-divergence.
- let rendered_line = layout.render_list_item_stale(&item);
- let display_text_with_ansi = rendered_line.render();
- let display_text = rendered_line.plain_text();
-
- let item = Arc::new(item);
- items_for_precompute.push(Arc::clone(&item));
-
- Arc::new(WorktreeSkimItem {
- display_text,
- display_text_with_ansi,
- branch_name,
- item,
- preview_cache: Arc::clone(&preview_cache),
- }) as Arc<dyn SkimItem>
- })
- .collect();
-
- // Insert header row at the beginning (will be non-selectable via header_lines option)
- items.insert(
- 0,
- Arc::new(HeaderSkimItem {
- display_text: header_plain_text,
- display_text_with_ansi: header_display_text,
- }) as Arc<dyn SkimItem>,
- );
- // Get state path for key bindings (shell-escaped for safety)
- let state_path_display = state.path.display().to_string();
- let state_path_str = shell_escape::escape(state_path_display.into()).into_owned();
-
- // Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%
- let half_page = terminal_size::terminal_size()
- .map(|(_, terminal_size::Height(h))| (h as usize * 45 / 100).max(5))
- .unwrap_or(10);
+ // Estimate item count for the preview window spec (only the Down
+ // layout depends on it). A cheap `list_worktrees` call gives an exact
+ // count for worktrees; branches are unknown up front, so we cap at
+ // MAX_VISIBLE_ITEMS for the Down height computation — users with more
+ // worktrees than fit on screen get the minimum preview height, which
+ // is the same result the old synchronous path produced.
+ let num_items_estimate = repo
+ .list_worktrees()
+ .map(|w| w.len())
+ .unwrap_or(preview::MAX_VISIBLE_ITEMS);
+ let preview_window_spec = state
+ .initial_layout
+ .to_preview_window_spec(num_items_estimate);
+ let preview_dims = state.initial_layout.preview_dimensions(num_items_estimate);
+
+ // Summary hint: when summaries are disabled, prime the Summary cache
+ // with config guidance instead of showing a perpetual "Generating…"
+ // placeholder.
+ let (llm_command, summary_hint) =
+ if config.list.summary() && config.commit_generation.is_configured() {
+ (config.commit_generation.command.clone(), None)
+ } else {
+ let hint = if !config.commit_generation.is_configured() {
+ "Configure [commit.generation] command to enable LLM summaries.\n\n\
+ Example in ~/.config/worktrunk/config.toml:\n\n\
+ [commit.generation]\n\
+ command = \"llm -m haiku\"\n\n\
+ [list]\n\
+ summary = true\n"
+ } else {
+ "Enable summaries in ~/.config/worktrunk/config.toml:\n\n\
+ [list]\n\
+ summary = true\n"
+ };
+ (None, Some(hint.to_string()))
+ };
- // Calculate preview window spec based on auto-detected layout
- // items.len() - 1 because we added a header row
- let num_items = items.len().saturating_sub(1);
- let preview_window_spec = state.initial_layout.to_preview_window_spec(num_items);
+ // Shared items list: populated by the handler's `on_skeleton` and read
+ // by `PickerCollector` on alt-r reload. Starts empty — the collector's
+ // `invoke` only fires after skim has displayed items, by which time
+ // the handler has already published them.
+ let shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>> = Arc::new(Mutex::new(Vec::new()));
- // Signal file for alt-r removal communication. execute-silent writes the branch
- // name here; the PickerCollector reads it on reload. Cleaned up in PreviewState::Drop.
+ // Signal file for alt-r removal communication. execute-silent writes
+ // the branch name here; the PickerCollector reads it on reload.
+ // Cleaned up in PreviewState::Drop.
let signal_path = state.path.with_extension("remove");
- // Shared items list: the PickerCollector reads and modifies this on reload.
- let shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>> = Arc::new(Mutex::new(items));
-
- // Custom collector for skim's reload action — performs removal and streams
- // updated items back, all without leaving the picker.
let collector = PickerCollector {
items: Arc::clone(&shared_items),
signal_path: signal_path.clone(),
@@ -452,6 +416,15 @@ pub fn handle_picker(
let signal_path_escaped =
shell_escape::escape(signal_path.display().to_string().into()).into_owned();
+ // Get state path for key bindings (shell-escaped for safety)
+ let state_path_display = state.path.display().to_string();
+ let state_path_str = shell_escape::escape(state_path_display.into()).into_owned();
+
+ // Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%
+ let half_page = terminal_size::terminal_size()
+ .map(|(_, terminal_size::Height(h))| (h as usize * 45 / 100).max(5))
+ .unwrap_or(10);
+
// Configure skim options with Rust-based preview and mode switching keybindings
let options = SkimOptionsBuilder::default()
.height("90%".to_string())
@@ -521,89 +494,71 @@ pub fn handle_picker(
.build()
.map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;
- // Send initial items to skim via channel
- let items = shared_items.lock().unwrap();
let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
- for item in items.iter() {
- tx.send(Arc::clone(item))
- .map_err(|e| anyhow::anyhow!("Failed to send item to skim: {}", e))?;
- }
- drop(tx);
- drop(items);
-
- // Pre-compute all preview modes for all worktrees in parallel via rayon.
- // Each (worktree, mode) pair is a separate rayon task, allowing the thread pool
- // to overlap I/O-bound git commands. Tasks are fire-and-forget — ongoing
- // git commands are harmless read-only operations even if skim exits early.
- let (preview_width, preview_height) = state.initial_layout.preview_dimensions(num_items);
-
- let modes = [
- PreviewMode::WorkingTree,
- PreviewMode::Log,
- PreviewMode::BranchDiff,
- PreviewMode::UpstreamDiff,
- ];
-
- // 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 {
- 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);
- }
- }
- // 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();
- 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
- // tab shows a useful message instead of a perpetual "Generating..." placeholder.
- let hint = if !config.commit_generation.is_configured() {
- "Configure [commit.generation] command to enable LLM summaries.\n\n\
- Example in ~/.config/worktrunk/config.toml:\n\n\
- [commit.generation]\n\
- command = \"llm -m haiku\"\n\n\
- [list]\n\
- summary = true\n"
- } else {
- "Enable summaries in ~/.config/worktrunk/config.toml:\n\n\
- [list]\n\
- summary = true\n"
- };
- for item in &items_for_precompute {
- let branch = item.branch_name().to_string();
- preview_cache.insert((branch, PreviewMode::Summary), hint.to_string());
- }
- }
+ let handler: Arc<dyn collect::PickerProgressHandler> =
+ Arc::new(progressive_handler::PickerHandler {
+ tx: tx.clone(),
+ shared_items: Arc::clone(&shared_items),
+ rendered_slots: std::sync::OnceLock::new(),
+ preview_cache: Arc::clone(&preview_cache),
+ orchestrator: Arc::clone(&orchestrator),
+ preview_dims,
+ llm_command,
+ repo: repo.clone(),
+ summary_hint,
+ });
+
+ // Spawn collect on a background thread. The handler holds the only
+ // remaining `tx` clone; when the bg thread exits, `tx` drops, and skim's
+ // heartbeat stops. Contract: background work done → picker idle.
+ let bg_handler = Arc::clone(&handler);
+ let bg_repo = repo.clone();
+ let bg_skip_tasks = skip_tasks.clone();
+ let bg_handle = std::thread::Builder::new()
+ .name("picker-collect".into())
+ .spawn(move || {
+ let _ = collect::collect(
+ &bg_repo,
+ collect::ShowConfig::Resolved {
+ show_branches,
+ show_remotes,
+ skip_tasks: bg_skip_tasks,
+ command_timeout,
+ collect_deadline: None,
+ list_width: Some(skim_list_width),
+ progressive_handler: Some(bg_handler),
+ },
+ false, // show_progress (picker renders its own UI)
+ false, // render_table
+ );
+ })
+ .context("Failed to spawn picker-collect thread")?;
+
+ // Drop main-thread copies so the bg thread's `tx` clone is the last
+ // sender (its drop is what stops skim's heartbeat).
+ drop(tx);
+ drop(handler);
- // 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.
+ // Dry-run: skim is bypassed. Wait for collect (which spawns previews
+ // via the handler), then for the preview pool, then dump the cache.
if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_some() {
+ drop(rx);
+ let _ = bg_handle.join();
orchestrator.wait_for_idle();
println!("{}", orchestrator.dump_cache_json());
return Ok(());
}
- // Run skim (single invocation — alt-r uses reload, not re-launch)
+ // Run skim (single invocation — alt-r uses reload, not re-launch).
+ // Skim receives items as the bg thread's handler sends them.
+ //
+ // Don't join `bg_handle` after skim exits: drain may still be running
+ // network tasks, and joining would block exit for up to DRAIN_TIMEOUT
+ // (120s). Process exit terminates the bg thread; its git subprocesses
+ // are read-only.
let output = Skim::run_with(&options, Some(rx));
+ drop(bg_handle);
// Handle selection (signal file cleaned up by PreviewState::Drop)
if let Some(out) = output
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
new file mode 100644
index 000000000..c28962bee
--- /dev/null
+++ b/src/commands/picker/progressive_handler.rs
@@ -0,0 +1,282 @@
+//! 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 100ms heartbeat keeps firing), each
+//! item's shared `rendered` mutex (in-place redraws picked up by the
+//! heartbeat), and `shared_items` used by `PickerCollector` for alt-r.
+//!
+//! Preview + summary pre-compute kicks off at skeleton time so the first
+//! preview the user opens is already warm.
+
+use std::sync::{Arc, Mutex, OnceLock};
+
+use skim::prelude::*;
+use worktrunk::git::Repository;
+use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};
+
+use super::items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};
+use super::preview::PreviewMode;
+use super::preview_orchestrator::PreviewOrchestrator;
+use crate::commands::list::collect::PickerProgressHandler;
+use crate::commands::list::model::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
+/// stops skim's heartbeat. That's the explicit contract: once background
+/// work is done, the picker can go idle.
+pub(super) struct PickerHandler {
+ pub(super) tx: SkimItemSender,
+ /// Mirror of the skim item vec visible to `PickerCollector`. Populated
+ /// atomically in `on_skeleton`.
+ pub(super) shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,
+ /// One `Arc<Mutex<String>>` per data row — same Arcs `WorktreeSkimItem`
+ /// holds. Set once in `on_skeleton`, read lock-free thereafter.
+ pub(super) rendered_slots: OnceLock<Box<[Arc<Mutex<String>>]>>,
+ pub(super) preview_cache: PreviewCache,
+ pub(super) orchestrator: Arc<PreviewOrchestrator>,
+ pub(super) preview_dims: (usize, usize),
+ pub(super) llm_command: Option<String>,
+ pub(super) repo: Repository,
+ /// Filled into the Summary preview cache for every item when summaries
+ /// are disabled — gives the Summary tab something useful instead of a
+ /// perpetual "Generating…" placeholder.
+ pub(super) summary_hint: Option<String>,
+}
+
+impl PickerProgressHandler for PickerHandler {
+ fn on_skeleton(&self, items: Vec<ListItem>, rendered: Vec<String>, header: StyledLine) {
+ debug_assert_eq!(items.len(), rendered.len());
+
+ let mut slots: Vec<Arc<Mutex<String>>> = Vec::with_capacity(items.len());
+ let mut skim_items: Vec<Arc<dyn SkimItem>> = Vec::with_capacity(items.len() + 1);
+ let mut list_items: Vec<Arc<ListItem>> = Vec::with_capacity(items.len());
+
+ // Header row — non-selectable via `header_lines(1)` on the options.
+ skim_items.push(Arc::new(HeaderSkimItem {
+ display_text: header.plain_text(),
+ display_text_with_ansi: header.render(),
+ }) as Arc<dyn SkimItem>);
+
+ for (item, rendered_line) in items.into_iter().zip(rendered) {
+ let branch_name = item.branch_name().to_string();
+ let path_str = item
+ .worktree_path()
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ // `search_text` is what the matcher sees — fuzzy ranks stay
+ // stable across progressive updates because this field only
+ // depends on fast data (branch + path).
+ let search_text = if path_str.is_empty() {
+ branch_name.clone()
+ } else {
+ format!("{branch_name} {path_str}")
+ };
+
+ // Strip OSC 8 hyperlinks — skim's pipeline mangles them into
+ // garbage like `^[8;;…`. Colors (SGR codes) are preserved.
+ let rendered_arc = Arc::new(Mutex::new(strip_osc8_hyperlinks(&rendered_line)));
+ slots.push(Arc::clone(&rendered_arc));
+
+ let item_arc = Arc::new(item);
+ list_items.push(Arc::clone(&item_arc));
+
+ skim_items.push(Arc::new(WorktreeSkimItem {
+ search_text,
+ rendered: rendered_arc,
+ branch_name,
+ item: item_arc,
+ preview_cache: Arc::clone(&self.preview_cache),
+ }) as Arc<dyn SkimItem>);
+ }
+
+ // Publish slots + skim items before sending to skim so alt-r reload
+ // (which reads `shared_items`) sees a populated list the moment
+ // skim calls `CommandCollector::invoke`.
+ let _ = self.rendered_slots.set(slots.into_boxed_slice());
+ *self.shared_items.lock().unwrap() = skim_items.clone();
+
+ for skim_item in &skim_items {
+ let _ = self.tx.send(Arc::clone(skim_item));
+ }
+
+ self.spawn_precompute(&list_items);
+ }
+
+ fn on_update(&self, idx: usize, rendered: String) {
+ if let Some(slots) = self.rendered_slots.get()
+ && let Some(slot) = slots.get(idx)
+ {
+ *slot.lock().unwrap() = strip_osc8_hyperlinks(&rendered);
+ }
+ }
+
+ fn on_reveal(&self, rendered: Vec<Option<String>>) {
+ let Some(slots) = self.rendered_slots.get() else {
+ return;
+ };
+ for (slot, line) in slots.iter().zip(rendered) {
+ if let Some(line) = line {
+ *slot.lock().unwrap() = strip_osc8_hyperlinks(&line);
+ }
+ }
+ }
+}
+
+impl PickerHandler {
+ /// Kick off preview + summary pre-compute in the dedicated rayon pool.
+ ///
+ /// Spawn order mirrors the old synchronous path: the first item's modes
+ /// win the first slots (the user lands there and may tab-cycle), then
+ /// mode-major across the rest. Summaries queue last because each LLM
+ /// call can take seconds.
+ fn spawn_precompute(&self, list_items: &[Arc<ListItem>]) {
+ let modes = [
+ PreviewMode::WorkingTree,
+ PreviewMode::Log,
+ PreviewMode::BranchDiff,
+ PreviewMode::UpstreamDiff,
+ ];
+
+ if let Some(first) = list_items.first() {
+ for mode in modes {
+ self.orchestrator
+ .spawn_preview(Arc::clone(first), mode, self.preview_dims);
+ }
+ }
+ for mode in modes {
+ for item in list_items.iter().skip(1) {
+ self.orchestrator
+ .spawn_preview(Arc::clone(item), mode, self.preview_dims);
+ }
+ }
+
+ if let Some(llm) = self.llm_command.as_ref() {
+ if let Some(first) = list_items.first() {
+ self.orchestrator
+ .spawn_summary(Arc::clone(first), llm.clone(), self.repo.clone());
+ }
+ for item in list_items.iter().skip(1) {
+ self.orchestrator
+ .spawn_summary(Arc::clone(item), llm.clone(), self.repo.clone());
+ }
+ } else if let Some(hint) = self.summary_hint.as_ref() {
+ for item in list_items {
+ let branch = item.branch_name().to_string();
+ self.preview_cache
+ .insert((branch, PreviewMode::Summary), hint.clone());
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::commands::list::model::ListItem;
+ use worktrunk::testing::TestRepo;
+
+ fn make_handler() -> (
+ PickerHandler,
+ TestRepo,
+ crossbeam_channel::Receiver<Arc<dyn SkimItem>>,
+ ) {
+ let test = TestRepo::with_initial_commit();
+ let (tx, rx) = crossbeam_channel::unbounded::<Arc<dyn SkimItem>>();
+ let shared_items = Arc::new(Mutex::new(Vec::new()));
+ let orchestrator = Arc::new(PreviewOrchestrator::new());
+ let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
+ let repo = test.repo.clone();
+ let handler = PickerHandler {
+ tx,
+ shared_items,
+ rendered_slots: OnceLock::new(),
+ preview_cache,
+ orchestrator,
+ preview_dims: (80, 24),
+ llm_command: None,
+ repo,
+ summary_hint: Some("disabled".to_string()),
+ };
+ (handler, test, rx)
+ }
+
+ fn header(text: &str) -> StyledLine {
+ let mut line = StyledLine::new();
+ line.push_raw(text);
+ line
+ }
+
+ /// Skeleton → update → reveal: verifies that each event writes through
+ /// to the shared `rendered` string the `WorktreeSkimItem` holds. Skim
+ /// reads these strings on its heartbeat; the matcher-stable search
+ /// text (branch + path) never changes.
+ #[test]
+ fn handler_updates_render_strings_in_place() {
+ let (handler, _test, rx) = make_handler();
+ let items = vec![
+ ListItem::new_branch("aaa".into(), "one".into()),
+ ListItem::new_branch("bbb".into(), "two".into()),
+ ];
+ let rendered = vec!["skel-one".to_string(), "skel-two".to_string()];
+
+ handler.on_skeleton(items, rendered, header("hdr"));
+
+ // Header + 2 items sent to skim.
+ let received: Vec<Arc<dyn SkimItem>> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
+ assert_eq!(received.len(), 3, "expected header + 2 items");
+
+ let slots = handler.rendered_slots.get().unwrap();
+ assert_eq!(slots.len(), 2);
+ assert_eq!(*slots[0].lock().unwrap(), "skel-one");
+ assert_eq!(*slots[1].lock().unwrap(), "skel-two");
+
+ // on_update rewrites a single slot (the second item here).
+ handler.on_update(1, "updated-two".into());
+ assert_eq!(*slots[0].lock().unwrap(), "skel-one", "row 0 untouched");
+ assert_eq!(*slots[1].lock().unwrap(), "updated-two");
+
+ // on_reveal: Some entries rewrite the slot, None entries leave it.
+ handler.on_reveal(vec![Some("rev-one".into()), None]);
+ assert_eq!(*slots[0].lock().unwrap(), "rev-one");
+ assert_eq!(
+ *slots[1].lock().unwrap(),
+ "updated-two",
+ "row 1 had data — reveal must not clobber it"
+ );
+ }
+
+ /// Header + items get published in order. `output()` of the
+ /// WorktreeSkimItem is the branch name so skim returns the correct
+ /// identifier when the user hits Enter.
+ #[test]
+ fn skeleton_publishes_header_then_items() {
+ let (handler, _test, rx) = make_handler();
+ let items = vec![
+ ListItem::new_branch("aaa".into(), "feat-a".into()),
+ ListItem::new_branch("bbb".into(), "feat-b".into()),
+ ];
+
+ handler.on_skeleton(
+ items,
+ vec!["skel-a".into(), "skel-b".into()],
+ header("Branch Status"),
+ );
+
+ let received: Vec<Arc<dyn SkimItem>> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
+ assert_eq!(received.len(), 3);
+ // Header emits empty output (not selectable).
+ assert_eq!(received[0].output().as_ref(), "");
+ // Branch items emit the branch name.
+ assert_eq!(received[1].output().as_ref(), "feat-a");
+ assert_eq!(received[2].output().as_ref(), "feat-b");
+
+ // Shared state matches what was sent.
+ let shared = handler.shared_items.lock().unwrap();
+ assert_eq!(shared.len(), 3);
+ assert_eq!(shared[1].output().as_ref(), "feat-a");
+ assert_eq!(shared[2].output().as_ref(), "feat-b");
+ }
+}
diff --git a/src/config/user/resolved.rs b/src/config/user/resolved.rs
index 2abf8687e..72ff1b633 100644
--- a/src/config/user/resolved.rs
+++ b/src/config/user/resolved.rs
@@ -22,7 +22,7 @@ use super::sections::{
/// let squash = resolved.merge.squash(); // bool, default applied
/// let stage = resolved.commit.stage(); // StageMode, default applied
/// let pager = resolved.switch_picker.pager(); // Option<&str>
-/// let timeout = resolved.switch_picker.timeout(); // Option<Duration>
+/// let timeout = resolved.switch_picker.timeout(); // Option<Duration>, parsed but unused
/// let cd = resolved.switch.cd(); // bool, default applied
/// ```
#[derive(Debug, Clone, PartialEq)]
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 48990bbf6..9882c445c 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -332,14 +332,12 @@ pub struct SwitchPickerConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub pager: Option<String>,
- /// Wall-clock budget for picker data collection in milliseconds.
+ /// Accepted for backward compatibility; currently ignored.
///
- /// Controls how long the picker waits for git data before displaying.
- /// Tasks still running when the budget expires are abandoned.
- ///
- /// - Unset: 500ms default
- /// - `0`: No budget (wait for all results)
- /// - Positive value: Custom budget in milliseconds
+ /// Previously bounded how long the picker blocked before rendering.
+ /// The picker now renders its skeleton immediately and fills rows in
+ /// place as results arrive, so there's no UI-freeze budget to tune.
+ /// Left in the schema so existing configs keep parsing without error.
#[serde(rename = "timeout-ms", skip_serializing_if = "Option::is_none")]
pub timeout_ms: Option<u64>,
}
@@ -350,8 +348,9 @@ impl SwitchPickerConfig {
self.pager.as_deref()
}
- /// Wall-clock budget for picker data collection (default: 500ms).
- /// Returns `None` when disabled (timeout_ms = 0).
+ /// Parses the legacy `timeout-ms` field. Kept for schema round-tripping;
+ /// the picker no longer consults it (progressive rendering made the
+ /// UI-freeze budget obsolete).
pub fn timeout(&self) -> Option<std::time::Duration> {
match self.timeout_ms {
Some(0) => None,
diff --git a/src/styling/hyperlink.rs b/src/styling/hyperlink.rs
index a4bc34e06..2147decf2 100644
--- a/src/styling/hyperlink.rs
+++ b/src/styling/hyperlink.rs
@@ -33,6 +33,11 @@ pub fn hyperlink_stdout(url: &str, text: &str) -> String {
///
/// Uses the `osc8` crate's parser to find hyperlinks and extract just the visible text.
pub fn strip_osc8_hyperlinks(s: &str) -> String {
+ // Fast path — callers routinely pass strings with no hyperlinks (skeleton
+ // rows, plain log output). Skip the parse-and-rebuild work entirely.
+ if !s.contains("\x1b]8;") {
+ return s.to_string();
+ }
let mut result = s.to_string();
// Keep parsing and removing hyperlinks until none remain
while let Ok(Some((_, range))) = Hyperlink::parse(&result) {
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 0e74e490e..27ac69a55 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -175,7 +175,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  #
  # [switch.picker]
  # pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-  # timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+  # timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
  #
  # ### Step
  #
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index dc13d9aa5..28db8695a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -221,7 +221,7 @@ Most flags are on by default. Set to false to change default behavior.
 
  [switch.picker]
  pager = "delta --paging=never" # Example: override git's core.pager for diff preview
-  timeout-ms = 500 # Wall-clock budget (ms) for picker data collection; 0 disables
+  timeout-ms = 0 # Deprecated. Accepted for backward compatibility, currently ignored.
Step