Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Defer wt list `·` loading indicator until 200ms (#2199)
Maximilian Roos35ea06276305
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex ae144d682..1c617d148 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -667,8 +667,15 @@ pub fn collect(format!("Showing {} worktree{}", num_worktrees, plural)};- // Create progressive table if showing progress+ // Create progressive table if showing progress.+ //+ // Skeleton renders with `PLACEHOLDER_BLANK` (space) so commands that finish+ // under ~200ms never flash the `·` loading indicator. After+ // `PLACEHOLDER_REVEAL_DELAY` the placeholder is promoted to `·` via the+ // drain tick below.let mut progressive_table = if show_progress {+ layout.placeholder.set(super::render::PLACEHOLDER_BLANK);+let dim = Style::new().dimmed();// Build skeleton rows for both worktrees and branches@@ -694,6 +701,19 @@ pub fn collect(None};+ /// 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)+ /// for interactive testing — useful to inflate the delay high enough to see+ /// the reveal visually (e.g. `WORKTRUNK_PLACEHOLDER_REVEAL_MS=2000 wt list`).+ const PLACEHOLDER_REVEAL_DELAY: std::time::Duration = std::time::Duration::from_millis(200);+ let reveal_delay = std::env::var("WORKTRUNK_PLACEHOLDER_REVEAL_MS")+ .ok()+ .and_then(|s| s.parse::<u64>().ok())+ .map(std::time::Duration::from_millis)+ .unwrap_or(PLACEHOLDER_REVEAL_DELAY);+ let placeholder_reveal_at = std::time::Instant::now() + reveal_delay;+// Early exit for benchmarking skeleton render time / time-to-first-outputif std::env::var_os("WORKTRUNK_SKELETON_ONLY").is_some()|| std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some()@@ -775,9 +795,6 @@ pub fn collect(// Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive// and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.- // Cache last rendered (unclamped) message per row to avoid redundant updates.- let mut last_rendered_lines: Vec<String> = vec![String::new(); all_items.len()];-// Create channel for task resultslet (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();@@ -861,14 +878,60 @@ pub fn collect(// Drop the original sender so drain_results knows when all spawned threads are donedrop(tx);- // Track completed results for footer progress- let mut completed_results = 0;- let mut progress_overflow = false;- let mut first_result_traced = false;+ // Drain task results with conditional progressive rendering.+ //+ // Progressive mutable state (table, row cache, counters) is owned by a+ // `RefCell` so the `on_result` callback and the one-shot 200ms tick can+ // both mutate it. They never run concurrently — the tick fires between+ // channel recvs — so the runtime borrow checks are an invariant formalism,+ // never a source of panics.+ struct ProgressiveState {+ table: ProgressiveTable,+ last_rendered_lines: Vec<String>,+ completed_results: usize,+ progress_overflow: bool,+ first_result_traced: bool,+ }++ let n_items = all_items.len();+ 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,+ })+ });- // Drain task results with conditional progressive renderinglet drain_deadline =collect_deadline.unwrap_or_else(|| std::time::Instant::now() + results::DRAIN_TIMEOUT);++ // Tick closure: at T+200ms, promote placeholder from blank to `·` and+ // re-render every row so still-pending cells pick up the dot. Rows that+ // have already received a result use `format_list_item_line`; untouched+ // rows use `render_skeleton_row` (which avoids surfacing seeded defaults+ // like "55y" for skipped tasks).+ let tick_entry: Option<results::DrainTick<'_>> = progressive_state.as_ref().map(|state_cell| {+ let f: results::DrainTickFn<'_> = Box::new(|items: &mut [ListItem]| {+ layout.placeholder.set(super::render::PLACEHOLDER);+ let mut s = state_cell.borrow_mut();+ 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 _ = s.table.flush();+ });+ (placeholder_reveal_at, f)+ });+let drain_outcome = drain_results(rx,&mut all_items,@@ -877,55 +940,62 @@ pub fn collect(drain_deadline,integration_target.as_deref(),|item_idx, item| {- // Trace first result arrival- if !first_result_traced {- first_result_traced = true;+ let Some(state_cell) = progressive_state.as_ref() else {+ return;+ };+ 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");}- // Progressive mode only: update UI. `status_symbols` is set by- // `drain_results` itself (once all status-feeding tasks for this- // item have arrived successfully); here we only re-render.- if let Some(ref mut table) = progressive_table {- let dim = Style::new().dimmed();-- completed_results += 1;- let total_results = expected_results.count();-- // Catch counting bugs: completed should never exceed expected- debug_assert!(- completed_results <= total_results,- "completed ({completed_results}) > expected ({total_results}): \- task result sent without registering expectation"- );- if completed_results > total_results {- progress_overflow = true;- }-- // Update footer progress- let footer_msg = format!(- "{INFO_SYMBOL} {dim}{footer_base} ({completed_results}/{total_results} loaded){dim:#}"- );- table.update_footer(footer_msg);+ let dim = Style::new().dimmed();+ s.completed_results += 1;+ let total_results = expected_results.count();- // Re-render the row with caching (now includes status if computed)- let rendered = layout.format_list_item_line(item);+ 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;+ }- // Compare using full line so changes beyond the clamp (e.g., CI) still refresh.- if rendered != last_rendered_lines[item_idx] {- last_rendered_lines[item_idx] = rendered.clone();- table.update_row(item_idx, rendered);- }+ 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);- // Flush updates to terminal- if let Err(e) = table.flush() {- log::debug!("Progressive table flush failed: {}", e);- }+ 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);}++ let _ = s.table.flush();},+ tick_entry,);worktrunk::shell_exec::trace_instant("All results drained");+ // Extract progressive state back out. `progressive_table` is re-bound so+ // post-drain code (finalize / error rendering) works unchanged.+ let (progressive_table, progress_overflow) = match progressive_state {+ Some(cell) => {+ let s = cell.into_inner();+ (Some(s.table), s.progress_overflow)+ }+ None => (None, false),+ };+ // Reveal the placeholder synchronously for any path where the drain+ // finished before the tick could fire — keeps subsequent renders+ // (including `finalize`) consistent with the post-reveal placeholder.+ layout.placeholder.set(super::render::PLACEHOLDER);+// Handle timeout if it occurred.// Budget-based deadlines (collect_deadline) are intentional truncation — don't warn.// Only warn for the default DRAIN_TIMEOUT (120s), which indicates a hung command.@@ -1244,6 +1314,7 @@ pub fn populate_item(std::time::Instant::now() + results::DRAIN_TIMEOUT,target.as_deref(),|_item_idx, _item| {},+ None,);// Handle timeout (silent for statusline - just log it)diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rsindex 53fe114ad..4eccbaff2 100644--- a/src/commands/list/collect/results.rs+++ b/src/commands/list/collect/results.rs@@ -24,6 +24,15 @@ use super::super::model::{ItemKind, ListItem};use super::execution::ExpectedResults;use super::types::{DrainOutcome, MissingResult, TaskError, TaskKind, TaskResult};+/// Boxed one-shot tick closure. Factored out so the inferred closure can+/// coerce to `dyn FnMut` at the `Box::new` site.+pub(super) type DrainTickFn<'a> = Box<dyn FnMut(&mut [ListItem]) + 'a>;++/// One-shot tick scheduled against [`drain_results`]. When `Instant` elapses,+/// the boxed closure fires once with the full item slice — used by `wt list`+/// to reveal the `·` loading indicator at T+200ms.+pub(super) type DrainTick<'a> = (Instant, DrainTickFn<'a>);+/// Drain task results from the channel and apply them to items.////// This is the shared logic between progressive and buffered collection modes.@@ -41,6 +50,7 @@ use super::types::{DrainOutcome, MissingResult, TaskError, TaskKind, TaskResult}/// Callers decide how to handle timeout:/// - `collect()`: Shows user-facing diagnostic (interactive command)/// - `populate_item()`: Logs silently (used by statusline)+#[allow(clippy::too_many_arguments)]pub(super) fn drain_results(rx: chan::Receiver<Result<TaskResult, TaskError>>,items: &mut [ListItem],@@ -49,13 +59,29 @@ pub(super) fn drain_results(deadline: Instant,integration_target: Option<&str>,mut on_result: impl FnMut(usize, &mut ListItem),+ mut tick: Option<DrainTick<'_>>,) -> DrainOutcome {// Track which result kinds we've received per item (for timeout diagnostics)let mut received_by_item: Vec<Vec<TaskKind>> = vec![Vec::new(); items.len()];// Process task results as they arrive (with deadline)loop {- let remaining = deadline.saturating_duration_since(Instant::now());+ // Fire the one-shot tick when its deadline has passed. The tick fires+ // between channel recvs, so it never races with `on_result`.+ if let Some((tick_at, _)) = tick.as_ref()+ && Instant::now() >= *tick_at+ {+ let (_, mut tick_fn) = tick.take().unwrap();+ tick_fn(items);+ }++ let now = Instant::now();+ let remaining = deadline.saturating_duration_since(now);+ // Clamp recv timeout so we wake at the tick deadline (earliest of the two).+ let recv_timeout_dur = match tick.as_ref() {+ Some((tick_at, _)) => remaining.min(tick_at.saturating_duration_since(now)),+ None => remaining,+ };if remaining.is_zero() {// Deadline exceeded - build diagnostic info showing MISSING resultslet received_count: usize = received_by_item.iter().map(|v| v.len()).sum();@@ -100,9 +126,9 @@ pub(super) fn drain_results(};}- let outcome = match rx.recv_timeout(remaining) {+ let outcome = match rx.recv_timeout(recv_timeout_dur) {Ok(outcome) => outcome,- Err(chan::RecvTimeoutError::Timeout) => continue, // Check deadline in next iteration+ Err(chan::RecvTimeoutError::Timeout) => continue, // Check tick/deadline next iterationErr(chan::RecvTimeoutError::Disconnected) => break, // All senders dropped - done};@@ -340,6 +366,7 @@ mod tests {Instant::now() + DRAIN_TIMEOUT,None,|_, _| {},+ None,);assert!(matches!(outcome, DrainOutcome::Complete));assert_eq!(items[0].summary, Some(Some("Add feature".into())));@@ -418,6 +445,7 @@ mod tests {Instant::now() + DRAIN_TIMEOUT,Some("main"),|_, _| {},+ None,);assert!(matches!(outcome, DrainOutcome::Complete));@@ -461,6 +489,7 @@ mod tests {Instant::now() + DRAIN_TIMEOUT,Some("main"),|_, _| {},+ None,);assert!(matches!(outcome, DrainOutcome::Complete));@@ -501,6 +530,7 @@ mod tests {Instant::now() + DRAIN_TIMEOUT,Some("main"),|_, _| {},+ None,);assert!(matches!(outcome, DrainOutcome::Complete));@@ -531,6 +561,7 @@ mod tests {Instant::now(),None,|_, _| {},+ None,);let DrainOutcome::TimedOut {@@ -555,4 +586,47 @@ mod tests {.contains(&TaskKind::AheadBehind));}++ #[test]+ fn test_drain_results_tick_fires_when_deadline_passes() {+ // A tick whose deadline has already elapsed should fire exactly once+ // with a mutable view of the items, then stop (no re-fire on subsequent+ // loop iterations). The drain loop wakes at the tick deadline even+ // without any channel traffic, so this also exercises the+ // recv_timeout-clamping path.+ let (tx, rx) = crossbeam_channel::unbounded::<Result<TaskResult, TaskError>>();+ let mut items = vec![ListItem::new_branch("abc123".into(), "feat".into())];+ let mut errors = Vec::new();+ let expected = ExpectedResults::default();++ // Send one result so the drain exits promptly after the tick.+ tx.send(Ok(TaskResult::SummaryGenerate {+ item_idx: 0,+ summary: None,+ }))+ .unwrap();+ drop(tx);++ let mut tick_fires = 0usize;+ let tick_fn: DrainTickFn<'_> = Box::new(|items: &mut [ListItem]| {+ tick_fires += 1;+ // Mutate an item to prove we got a live mutable reference.+ items[0].branch = Some("touched-by-tick".into());+ });++ let outcome = drain_results(+ rx,+ &mut items,+ &mut errors,+ &expected,+ Instant::now() + DRAIN_TIMEOUT,+ None,+ |_, _| {},+ Some((Instant::now(), tick_fn)),+ );++ assert!(matches!(outcome, DrainOutcome::Complete));+ assert_eq!(tick_fires, 1, "tick should fire exactly once");+ assert_eq!(items[0].branch.as_deref(), Some("touched-by-tick"));+ }}diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex 75cd8c35f..4f920a0a4 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -517,6 +517,11 @@ pub struct LayoutConfig {pub max_summary_len: usize,pub hidden_column_count: usize,pub status_position_mask: super::model::PositionMask,+ /// Glyph to use for cells whose data has not yet arrived. Interior+ /// mutability lets the `wt list` progressive path swap the placeholder+ /// at the 200ms reveal threshold without needing `&mut` everywhere.+ /// See `super::render::PLACEHOLDER` / `PLACEHOLDER_BLANK`.+ pub placeholder: std::cell::Cell<&'static str>,}#[derive(Clone, Copy)]@@ -881,6 +886,7 @@ fn allocate_columns_with_priority(max_summary_len,hidden_column_count,status_position_mask: metadata.status_position_mask,+ placeholder: std::cell::Cell::new(super::render::PLACEHOLDER),}}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 75882eeea..28a516917 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -22,6 +22,13 @@ use super::model::{ListItem, PositionMask};/// audit. 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+/// rendering. The skeleton renders with blanks so fast commands (everything+/// resolved under 200ms) never flash the `·` loading indicator. After the+/// 200ms threshold, `LayoutConfig::placeholder` is promoted to [`PLACEHOLDER`]+/// and every still-pending cell is re-rendered with the dot.+pub const PLACEHOLDER_BLANK: &str = " ";+impl DiffColumnConfig {/// Check if a value exceeds the allocated digit widthfn exceeds_width(value: usize, digits: usize) -> bool {@@ -250,7 +257,7 @@ impl LayoutConfig {/// Render list item line as StyledLine (for extracting both plain and styled text)pub fn render_list_item_line(&self, item: &ListItem) -> StyledLine {- self.render_item_with_placeholder(item, PLACEHOLDER)+ self.render_item_with_placeholder(item, self.placeholder.get())}/// Render with stale placeholders for items where data collection was truncated.@@ -260,7 +267,7 @@ impl LayoutConfig {/// (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, PLACEHOLDER)+ self.render_item_with_placeholder(item, self.placeholder.get())}fn render_item_with_placeholder(&self, item: &ListItem, placeholder: &str) -> StyledLine {@@ -289,7 +296,7 @@ impl LayoutConfig {.unwrap_or_default();let dim = Style::new().dimmed();- let spinner = PLACEHOLDER;+ let spinner = self.placeholder.get();self.render_line(|col| {let mut cell = StyledLine::new();@@ -298,12 +305,12 @@ impl LayoutConfig {ColumnKind::Gutter => {// Skeleton shows placeholder gutter - actual symbols (including is_previous)// appear when WorktreeData is populated post-skeleton.- // TODO: is this ever visible? The skeleton renders for ~50ms before data- // arrives. If not, consider removing the middle dot.+ // Uses the current placeholder so the 200ms blank-reveal flow+ // keeps the gutter in lockstep with the data columns.let symbol = if wt_data.is_some() {- "· " // Placeholder for worktrees+ format!("{spinner} ") // Placeholder for worktrees} else {- " " // Branch without worktree (two spaces to match width)+ " ".to_string() // Branch without worktree (two spaces to match width)};cell.push_styled(symbol, dim);}@@ -1338,6 +1345,7 @@ mod tests {max_summary_len: 10,hidden_column_count: 0,status_position_mask: PositionMask::FULL,+ placeholder: std::cell::Cell::new(PLACEHOLDER),};let item = ListItem::new_branch("abc123".into(), "feat".into());