Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Implement progressive table with crossterm for list command
Maximilian Roos8d9ef88da00d
diff --git a/Cargo.lock b/Cargo.lockindex 5b3324321..04749d22c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -443,7 +443,7 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "980c2afde4af43d6a05c5be738f9eae595cff86dce1f38f88b95058a98c027f3"dependencies = [- "crossterm",+ "crossterm 0.29.0",][[package]]@@ -501,7 +501,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "51360853ebbeb3df20c76c82aecf43d387a62860f1a59ba65ab51f00eea85aad"dependencies = ["crokey-proc_macros",- "crossterm",+ "crossterm 0.29.0","once_cell","serde","strict",@@ -513,7 +513,7 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3bf1a727caeb5ee5e0a0826a97f205a9cf84ee964b0b48239fef5214a00ae439"dependencies = [- "crossterm",+ "crossterm 0.29.0","proc-macro2","quote","strict",@@ -576,6 +576,22 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]+name = "crossterm"+version = "0.28.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"+dependencies = [+ "bitflags 2.10.0",+ "crossterm_winapi",+ "mio",+ "parking_lot",+ "rustix 0.38.44",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]+[[package]]name = "crossterm"version = "0.29.0"@@ -588,7 +604,7 @@ dependencies = ["document-features","mio","parking_lot",- "rustix",+ "rustix 1.1.2","signal-hook","signal-hook-mio","winapi",@@ -1135,19 +1151,6 @@ dependencies = ["serde_core",]-[[package]]-name = "indicatif"-version = "0.18.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88"-dependencies = [- "console 0.16.1",- "portable-atomic",- "unicode-width 0.2.2",- "unit-prefix",- "web-time",-]-[[package]]name = "insta"version = "1.44.1"@@ -1294,6 +1297,12 @@ dependencies = ["libc",]+[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"+[[package]]name = "linux-raw-sys"version = "0.11.0"@@ -1875,6 +1884,19 @@ dependencies = ["semver",]+[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.10.0",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.59.0",+]+[[package]]name = "rustix"version = "1.1.2"@@ -1884,7 +1906,7 @@ dependencies = ["bitflags 2.10.0","errno","libc",- "linux-raw-sys",+ "linux-raw-sys 0.11.0","windows-sys 0.61.2",]@@ -2232,7 +2254,7 @@ dependencies = ["fastrand","getrandom 0.3.4","once_cell",- "rustix",+ "rustix 1.1.2","windows-sys 0.61.2",]@@ -2269,7 +2291,7 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0"dependencies = [- "rustix",+ "rustix 1.1.2","windows-sys 0.60.2",]@@ -2524,12 +2546,6 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"-[[package]]-name = "unit-prefix"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "323402cff2dd658f39ca17c789b502021b3f18707c91cdf22e3838e1b4023817"-[[package]]name = "utf8parse"version = "0.2.2"@@ -2713,16 +2729,6 @@ dependencies = ["wasm-bindgen",]-[[package]]-name = "web-time"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"-dependencies = [- "js-sys",- "wasm-bindgen",-]-[[package]]name = "which"version = "7.0.3"@@ -2731,7 +2737,7 @@ checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"dependencies = ["either","env_home",- "rustix",+ "rustix 1.1.2","winsafe",]@@ -3027,12 +3033,12 @@ dependencies = ["console 0.16.1","criterion","crossbeam-channel",+ "crossterm 0.28.1","directories","env_logger","etcetera","fs2","indexmap",- "indicatif","insta","insta-cmd","log",diff --git a/Cargo.toml b/Cargo.tomlindex b8ebdf178..859b1cf1d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,10 +45,10 @@ clap_complete = { version = "4.5", features = ["unstable-dynamic"] }config = "0.15"console = "0.16"crossbeam-channel = "0.5"+crossterm = "0.28"directories = "6.0"env_logger = "0.11"indexmap = { version = "2.12", features = ["serde"] }-indicatif = "0.18"once_cell = "1.21"etcetera = "0.11"log = "0.4"diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 3b475a17d..e6dd32e3b 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -442,8 +442,7 @@ pub fn collect(show_progress: bool,render_table: bool,) -> anyhow::Result<Option<super::model::ListData>> {- use indicatif::{MultiProgress, ProgressBar, ProgressStyle};- use std::time::Duration;+ use super::progressive_table::ProgressiveTable;let worktrees = repo.list_worktrees()?;if worktrees.worktrees.is_empty() {@@ -518,69 +517,9 @@ pub fn collect(let layout = super::layout::calculate_layout_from_basics(&all_items, show_full, fetch_ci);// Single-line invariant: use safe width to prevent line wrapping- // (which breaks indicatif's line-based cursor math).let max_width = super::layout::get_safe_list_width();- // Clamp helper to keep progress output single-line in narrow terminals.- // truncate_visible already returns early if no truncation needed, avoiding redundant work.- let clamp = |s: &str| -> String { crate::display::truncate_visible(s, max_width, "…") };-- // Create MultiProgress with explicit draw target and cursor mode- // Use stderr for progress bars so they don't interfere with stdout directives- let multi = if show_progress {- let mp = MultiProgress::with_draw_target(indicatif::ProgressDrawTarget::stderr_with_hz(10));- mp.set_move_cursor(true); // Stable since bar count is fixed- mp- } else {- MultiProgress::new()- };-- let message_style = ProgressStyle::with_template("{msg}").unwrap();-- // Create header progress bar (part of transient UI, cleared with finish_and_clear)- let header_pb = if show_progress {- let pb = multi.add(ProgressBar::hidden());- pb.set_style(message_style.clone());- pb.set_message(clamp(&layout.format_header_line()));- Some(pb)- } else {- None- };-- // Create progress bars for all items (worktrees + branches)- let progress_bars: Vec<_> = all_items- .iter()- .map(|item| {- let pb = multi.add(ProgressBar::new_spinner());- if show_progress {- pb.set_style(message_style.clone());-- // Render skeleton immediately with clamping- let skeleton = if item.worktree_data().is_some() {- // Worktree skeleton - show known data (branch, path, commit)- let is_current = item- .worktree_path()- .and_then(|p| current_worktree_path.as_ref().map(|cp| p == cp))- .unwrap_or(false);- layout.format_skeleton_row(item, is_current)- } else {- // Branch skeleton - use full item rendering- layout.format_list_item_line(item, current_worktree_path.as_ref())- };- pb.set_message(clamp(&skeleton));- pb.enable_steady_tick(Duration::from_millis(100));- }- pb- })- .collect();-- // Cache last rendered (unclamped) message per row to avoid redundant updates.- // TODO(list-progressive): if we change clamping/detection strategy, keep a test case- // for off-screen CI column updates to ensure we still refresh rows.- let mut last_rendered_lines: Vec<String> = vec![String::new(); all_items.len()];-- // Footer progress bar with loading status- // Uses determinate bar (no spinner) with {wide_msg} to prevent clearing artifacts+ // Build initial footer messagelet total_cells = all_items.len() * layout.columns.len();let num_worktrees = all_items.iter()@@ -597,35 +536,43 @@ pub fn collect(format!("Showing {} worktree{}", num_worktrees, plural)};- // Spacer: single-line blank between the table rows and the footer (no multiline messages)- let spacer_style = ProgressStyle::with_template("{wide_msg}").unwrap();- let spacer_pb = if show_progress {- let gap = multi.add(ProgressBar::new(1));- gap.set_style(spacer_style.clone());- gap.set_message(" "); // padded blank line- Some(gap)- } else {- None- };-- // Footer is single-line; no '\n'. Will be replaced with final summary on finish.- let footer_style = ProgressStyle::with_template("{wide_msg}").unwrap();-- let footer_pb = if show_progress {+ // Create progressive table if showing progress+ let mut progressive_table = if show_progress {use anstyle::Style;let dim = Style::new().dimmed();- // Footer with determinate bar (no spinner/tick)- let footer = multi.add(ProgressBar::new(total_cells as u64));- footer.set_style(footer_style);- footer.set_message(format!(- "{INFO_EMOJI} {dim}{footer_base} (0/{total_cells} cells loaded){dim:#}"- ));- Some(footer)+ // Build skeleton rows+ let skeletons: Vec<String> = all_items+ .iter()+ .map(|item| {+ if item.worktree_data().is_some() {+ let is_current = item+ .worktree_path()+ .and_then(|p| current_worktree_path.as_ref().map(|cp| p == cp))+ .unwrap_or(false);+ layout.format_skeleton_row(item, is_current)+ } else {+ layout.format_list_item_line(item, current_worktree_path.as_ref())+ }+ })+ .collect();++ let initial_footer =+ format!("{INFO_EMOJI} {dim}{footer_base} (0/{total_cells} cells loaded){dim:#}");++ Some(ProgressiveTable::new(+ layout.format_header_line(),+ skeletons,+ initial_footer,+ max_width,+ )?)} else {None};+ // 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 cell updateslet (tx, rx) = chan::unbounded();@@ -714,122 +661,74 @@ pub fn collect();// Progressive mode only: update UI- if show_progress {+ if let Some(ref mut table) = progressive_table {use anstyle::Style;let dim = Style::new().dimmed();completed_cells += 1;// Update footer progress- if let Some(pb) = footer_pb.as_ref() {- pb.set_position(completed_cells as u64);- pb.set_message(format!(+ let footer_msg = format!("{INFO_EMOJI} {dim}{footer_base} ({completed_cells}/{total_cells} cells loaded){dim:#}"- ));+ );+ if let Err(e) = table.update_footer(footer_msg) {+ log::debug!("Progressive footer update failed: {}", e);}- // Re-render the row with caching and clamping (now includes status if computed)- if let Some(pb) = progress_bars.get(item_idx) {- let rendered =- layout.format_list_item_line(item, current_worktree_path.as_ref());- let clamped = clamp(&rendered);+ // Re-render the row with caching (now includes status if computed)+ let rendered = layout.format_list_item_line(item, current_worktree_path.as_ref());- // 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;- pb.set_message(clamped);+ // 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();+ if let Err(e) = table.update_row(item_idx, rendered) {+ log::debug!("Progressive row update failed: {}", e);}}}},);- // Finalize progress bars: no clearing race; footer morphs into summary on TTY- if show_progress {- use std::io::IsTerminal;- let is_tty = std::io::stderr().is_terminal(); // Check stderr, not stdout ✅-- // Build final summary string once using helper function+ // Finalize progressive table or render buffered output+ if let Some(mut table) = progressive_table {+ // Build final summary stringlet final_msg =super::format_summary_message(&all_items, show_branches, layout.hidden_nonempty_count);- if is_tty {- // Interactive: morph footer → summary, keep rows in place- // Do a final render pass to ensure all data is displayed- // (progressive updates may have been clamped or timing-delayed)- for (item_idx, pb) in progress_bars.iter().enumerate() {- let rendered = layout- .format_list_item_line(&all_items[item_idx], current_worktree_path.as_ref());- let clamped = clamp(&rendered);- pb.set_message(clamped);- }-- if let Some(pb) = spacer_pb.as_ref() {- pb.finish(); // leave the blank line- }- if let Some(pb) = footer_pb.as_ref() {- pb.finish_with_message(final_msg.clone());- }- if let Some(pb) = header_pb {- pb.finish();- }- for pb in progress_bars {- pb.finish();+ if table.is_tty() {+ // Interactive: do final render pass and update footer to summary+ for (item_idx, item) in all_items.iter().enumerate() {+ let rendered = layout.format_list_item_line(item, current_worktree_path.as_ref());+ if let Err(e) = table.update_row(item_idx, rendered) {+ log::debug!("Final row update failed: {}", e);+ }}+ table.finalize_tty(final_msg)?;} else {- // Non-TTY: clear progress bars and print final table to stderr- if let Some(pb) = spacer_pb {- pb.finish_and_clear();- }- if let Some(pb) = footer_pb {- pb.finish_and_clear();- }- if let Some(pb) = header_pb {- pb.finish_and_clear();- }- for pb in progress_bars {- pb.finish_and_clear();+ // Non-TTY: print final static table+ let mut final_lines = Vec::new();+ final_lines.push(layout.format_header_line());+ for item in &all_items {+ final_lines+ .push(layout.format_list_item_line(item, current_worktree_path.as_ref()));}- // Ensure atomicity w.r.t. indicatif's draw thread- multi.suspend(|| {- // Redraw static table- crate::output::raw_terminal(layout.format_header_line())?;- for item in &all_items {- crate::output::raw_terminal(- layout.format_list_item_line(item, current_worktree_path.as_ref()),- )?;- }- // Blank line + summary (rendered here in non-tty mode)- crate::output::raw_terminal("")?;- crate::output::raw_terminal(final_msg.clone())- })?;+ final_lines.push(String::new()); // Spacer+ final_lines.push(final_msg);+ table.finalize_non_tty(final_lines)?;}- } else {- // Buffered mode (no progress bars shown)- for pb in progress_bars {- pb.finish();- }-- // Render final table if requested (table format), otherwise just return data (JSON format)- if render_table {- // Build final summary string- let final_msg = super::format_summary_message(- &all_items,- show_branches,- layout.hidden_nonempty_count,- );+ } else if render_table {+ // Buffered mode: render final table+ let final_msg =+ super::format_summary_message(&all_items, show_branches, layout.hidden_nonempty_count);- // Render complete table- crate::output::raw_terminal(layout.format_header_line())?;- for item in &all_items {- crate::output::raw_terminal(- layout.format_list_item_line(item, current_worktree_path.as_ref()),- )?;- }- // Blank line + summary- crate::output::raw_terminal("")?;- crate::output::raw_terminal(final_msg)?;+ crate::output::raw_terminal(layout.format_header_line())?;+ for item in &all_items {+ crate::output::raw_terminal(+ layout.format_list_item_line(item, current_worktree_path.as_ref()),+ )?;}+ crate::output::raw_terminal("")?;+ crate::output::raw_terminal(final_msg)?;}// Status symbols are now computed during data collection (both modes), no fallback neededdiff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex c3524df75..83914f0fe 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -81,6 +81,7 @@ mod columns;mod layout;pub mod model;pub mod progressive;+mod progressive_table;mod render;#[cfg(test)]diff --git a/src/commands/list/progressive_table.rs b/src/commands/list/progressive_table.rsnew file mode 100644index 000000000..6a0533c30--- /dev/null+++ b/src/commands/list/progressive_table.rs@@ -0,0 +1,208 @@+//! Progressive table renderer using crossterm for direct terminal control.+//!+//! This module provides a progressive table renderer that updates rows in-place+//! as data arrives, using crossterm for cursor control. Unlike indicatif's+//! MultiProgress, this renderer:+//!+//! - Uses our own escape-aware width calculations (StyledLine, truncate_visible)+//! - Supports OSC-8 hyperlinks correctly+//! - Has predictable cursor behavior based on our rendering logic++use crossterm::{+ ExecutableCommand,+ cursor::{MoveToColumn, MoveUp},+ terminal::{Clear, ClearType},+};+use std::io::{IsTerminal, Write, stderr};++use crate::display::truncate_visible;++/// Progressive table that updates rows in-place using crossterm cursor control.+///+/// The table structure is:+/// - Header row (column labels)+/// - N data rows (one per worktree/branch)+/// - Spacer (blank line)+/// - Footer (loading status / summary)+pub struct ProgressiveTable {+ /// Previously rendered content for each line (header + rows + spacer + footer)+ lines: Vec<String>,+ /// Maximum width for content (terminal width - safety margin)+ max_width: usize,+ /// Number of data rows (not counting header, spacer, footer)+ row_count: usize,+ /// Whether output is going to a TTY+ is_tty: bool,+}++impl ProgressiveTable {+ /// Create a new progressive table with the given structure.+ ///+ /// # Arguments+ /// * `header` - The header line content+ /// * `skeletons` - Initial content for each data row (skeleton with known data)+ /// * `initial_footer` - Initial footer message+ /// * `max_width` - Maximum content width (for truncation)+ pub fn new(+ header: String,+ skeletons: Vec<String>,+ initial_footer: String,+ max_width: usize,+ ) -> std::io::Result<Self> {+ let is_tty = stderr().is_terminal();+ let row_count = skeletons.len();++ // Build initial lines: header + rows + spacer + footer+ let mut lines = Vec::with_capacity(row_count + 3);+ lines.push(truncate_visible(&header, max_width, "…"));++ for skeleton in skeletons {+ lines.push(truncate_visible(&skeleton, max_width, "…"));+ }++ // Spacer (blank line)+ lines.push(String::new());++ // Footer+ lines.push(truncate_visible(&initial_footer, max_width, "…"));++ let table = Self {+ lines,+ max_width,+ row_count,+ is_tty,+ };++ // Print initial table+ if is_tty {+ table.print_all()?;+ }++ Ok(table)+ }++ /// Print all lines to stderr.+ fn print_all(&self) -> std::io::Result<()> {+ let mut stderr = stderr();+ for line in &self.lines {+ writeln!(stderr, "{}", line)?;+ }+ stderr.flush()+ }++ /// Update a data row at the given index.+ ///+ /// # Arguments+ /// * `row_idx` - Index of the data row (0-based, not counting header)+ /// * `content` - New content for the row+ pub fn update_row(&mut self, row_idx: usize, content: String) -> std::io::Result<()> {+ if row_idx >= self.row_count {+ return Ok(());+ }++ let truncated = truncate_visible(&content, self.max_width, "…");++ // Line index: header (0) + row_idx+ let line_idx = row_idx + 1;++ // Skip if content hasn't changed+ if self.lines[line_idx] == truncated {+ return Ok(());+ }++ self.lines[line_idx] = truncated;++ if self.is_tty {+ self.redraw_line(line_idx)?;+ }++ Ok(())+ }++ /// Update the footer message.+ pub fn update_footer(&mut self, content: String) -> std::io::Result<()> {+ let truncated = truncate_visible(&content, self.max_width, "…");++ // Footer is the last line+ let footer_idx = self.lines.len() - 1;++ // Skip if content hasn't changed+ if self.lines[footer_idx] == truncated {+ return Ok(());+ }++ self.lines[footer_idx] = truncated;++ if self.is_tty {+ self.redraw_line(footer_idx)?;+ }++ Ok(())+ }++ /// Redraw a specific line by moving cursor up, clearing, and printing.+ fn redraw_line(&self, line_idx: usize) -> std::io::Result<()> {+ let mut stderr = stderr();++ // Calculate how many lines up from current position+ // Current position is after the footer (last line)+ let lines_up = self.lines.len() - line_idx;++ // Move cursor up to the target line+ if lines_up > 0 {+ stderr.execute(MoveUp(lines_up as u16))?;+ }++ // Move to column 0 and clear the line+ stderr.execute(MoveToColumn(0))?;+ stderr.execute(Clear(ClearType::CurrentLine))?;++ // Print the new content+ write!(stderr, "{}", self.lines[line_idx])?;++ // Move cursor back to the end (after footer)+ // We need to move down (lines_up) lines, but since we printed one line+ // without newline, we need to print newlines to get back+ for _ in 0..lines_up {+ writeln!(stderr)?;+ }++ stderr.flush()+ }++ /// Finalize for TTY: do final render pass and leave output in place.+ ///+ /// # Arguments+ /// * `final_footer` - Final summary message to replace loading status+ pub fn finalize_tty(&mut self, final_footer: String) -> std::io::Result<()> {+ if !self.is_tty {+ return Ok(());+ }++ // Update footer with final summary+ self.update_footer(final_footer)?;++ Ok(())+ }++ /// Finalize for non-TTY: clear all and print final static table.+ ///+ /// # Arguments+ /// * `final_lines` - Final rendered lines (header + rows + spacer + footer)+ pub fn finalize_non_tty(&self, final_lines: Vec<String>) -> std::io::Result<()> {+ let mut stderr = stderr();++ // For non-TTY, we just print the final table+ // (initial output was suppressed)+ for line in final_lines {+ writeln!(stderr, "{}", line)?;+ }++ stderr.flush()+ }++ /// Check if output is going to a TTY.+ pub fn is_tty(&self) -> bool {+ self.is_tty+ }+}