Skip to content

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

feat(testing): Add PTY-based progressive output capture

Maximilian Roos7dbcef13730f
diff --git a/Cargo.lock b/Cargo.lock
index 02738d841..a49043d98 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -376,7 +376,7 @@ dependencies = [
"encode_unicode",
"libc",
"once_cell",
- "unicode-width",
+ "unicode-width 0.2.2",
"windows-sys 0.61.2",
]
@@ -1037,7 +1037,7 @@ checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88"
dependencies = [
"console 0.16.1",
"portable-atomic",
- "unicode-width",
+ "unicode-width 0.2.2",
"unit-prefix",
"web-time",
]
@@ -1910,7 +1910,7 @@ dependencies = [
"skim-tuikit",
"time",
"timer",
- "unicode-width",
+ "unicode-width 0.2.2",
"vte 0.15.0",
"which",
]
@@ -1933,7 +1933,7 @@ dependencies = [
"nix 0.29.0",
"skim-common",
"term",
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -2011,7 +2011,7 @@ dependencies = [
"if_chain",
"nohash-hasher",
"regex",
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -2287,6 +2287,12 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
+[[package]]
+name = "unicode-width"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
+
[[package]]
name = "unicode-width"
version = "0.2.2"
@@ -2349,6 +2355,29 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "vt100"
+version = "0.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84cd863bf0db7e392ba3bd04994be3473491b31e66340672af5d11943c6274de"
+dependencies = [
+ "itoa",
+ "log",
+ "unicode-width 0.1.14",
+ "vte 0.11.1",
+]
+
+[[package]]
+name = "vte"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f5022b5fbf9407086c180e9557be968742d839e68346af7792b8592489732197"
+dependencies = [
+ "arrayvec",
+ "utf8parse",
+ "vte_generate_state_changes",
+]
+
[[package]]
name = "vte"
version = "0.14.1"
@@ -2368,6 +2397,16 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "vte_generate_state_changes"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e369bee1b05d510a7b4ed645f5faa90619e05437111783ea5848f28d97d3c2e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+]
+
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -2792,8 +2831,9 @@ dependencies = [
"tree-sitter",
"tree-sitter-bash",
"tree-sitter-highlight",
- "unicode-width",
+ "unicode-width 0.2.2",
"vergen-gitcl",
+ "vt100",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index b744e0475..f8a9f379a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -86,6 +86,7 @@ toml = "0.9"
criterion = "0.7"
regex = "1.12"
portable-pty = "0.9"
+vt100 = "0.15"
fs2 = "0.4"
[[bench]]
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index c207d0726..cc47e628d 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -26,6 +26,7 @@
#![cfg(unix)]
pub mod list_snapshots;
+pub mod progressive_output;
pub mod shell;
use insta_cmd::get_cargo_bin;
diff --git a/tests/common/progressive_output.rs b/tests/common/progressive_output.rs
new file mode 100644
index 000000000..51dd93618
--- /dev/null
+++ b/tests/common/progressive_output.rs
@@ -0,0 +1,607 @@
+//! Progressive output testing utilities
+//!
+//! Tests commands that use progressive rendering (like `wt list --full`), where the table
+//! structure appears first with placeholder dots (⋯), then data fills in incrementally using
+//! ANSI cursor movements to update rows in-place.
+//!
+//! # The Problem
+//!
+//! Traditional test approaches capture stdout/stderr as linear byte streams. They cannot verify:
+//! - Table structure appearing before data
+//! - Placeholder dots being replaced with actual data over time
+//! - ANSI cursor movements updating rows in-place
+//!
+//! # The Solution
+//!
+//! This module uses:
+//! - **PTY (pseudo-terminal)** - Spawns commands in a real terminal
+//! - **vt100 terminal emulator** - Interprets ANSI escape sequences
+//! - **Progressive snapshots** - Captures screen state at intervals
+//! - **Behavioral verification** - Tests progressive filling without exact snapshot matching
+//!
+//! # Quick Start
+//!
+//! ```rust,ignore
+//! use crate::common::progressive_output::{capture_progressive_output, ProgressiveCaptureOptions};
+//! use crate::common::TestRepo;
+//!
+//! #[test]
+//! fn test_progressive_rendering() {
+//! let mut repo = TestRepo::new();
+//! repo.commit("Initial");
+//! repo.add_worktree("feature", "feature");
+//!
+//! // Capture using byte-based strategy (deterministic for behavioral tests)
+//! let output = capture_progressive_output(
+//! &repo,
+//! "list",
+//! &["--full", "--branches"],
+//! ProgressiveCaptureOptions::with_byte_interval(500),
+//! );
+//!
+//! // Verify progressive filling behavior
+//! assert_eq!(output.exit_code, 0);
+//! assert!(output.stages.len() > 1, "Should capture multiple stages");
+//! output.verify_progressive_filling().expect("Dots should decrease over time");
+//!
+//! // Verify header appears immediately
+//! assert!(output.initial().visible_text().contains("Branch"));
+//!
+//! // Verify all data eventually appears
+//! assert!(output.final_output().contains("feature"));
+//! }
+//! ```
+//!
+//! # Byte-Based vs Time-Based Capture
+//!
+//! **Use `with_byte_interval(N)` for tests** - Captures at fixed byte counts (e.g., every 500 bytes).
+//! This produces deterministic behavioral tests: stage counts and progressive filling verification
+//! work reliably across runs.
+//!
+//! **Why not snapshot testing?** Even with byte-based capture, exact content at each threshold
+//! varies due to PTY buffering timing. Behavioral assertions work; exact snapshots don't.
+//!
+//! # Common Testing Patterns
+//!
+//! **Verify structure appears first:**
+//! ```rust,ignore
+//! let initial = output.initial().visible_text();
+//! assert!(initial.contains("Branch")); // Header appears
+//! assert!(initial.contains("⋯")); // Data incomplete
+//! ```
+//!
+//! **Verify progressive data filling:**
+//! ```rust,ignore
+//! output.verify_progressive_filling().expect("Dots should decrease");
+//! // Or manually:
+//! let dots = output.dots_per_stage();
+//! assert!(dots[0] > dots[dots.len() - 1]);
+//! ```
+//!
+//! **Verify all data eventually appears:**
+//! ```rust,ignore
+//! let final_text = output.final_output();
+//! assert!(final_text.contains("feature-a"));
+//! assert!(!final_text.contains("⋯")); // No placeholders remain
+//! ```
+//!
+//! # Key API Methods
+//!
+//! **ProgressiveOutput:**
+//! - `initial()` - First snapshot (table structure)
+//! - `final_output()` - Final text (complete data)
+//! - `samples(n)` - Get n evenly-spaced snapshots
+//! - `verify_progressive_filling()` - Assert dots decrease over time
+//! - `dots_per_stage()` - Count placeholder dots in each stage
+//!
+//! **ProgressiveCaptureOptions:**
+//! - `with_byte_interval(n)` - Capture every n bytes (deterministic)
+//! - `default()` - Time-based capture every 50ms (less deterministic)
+
+use crate::common::TestRepo;
+use insta_cmd::get_cargo_bin;
+use portable_pty::{CommandBuilder, PtySize, native_pty_system};
+use std::io::Read;
+use std::time::{Duration, Instant};
+
+/// Time to wait for final output to flush after child process exits
+const FINAL_OUTPUT_FLUSH_MS: u64 = 50;
+
+/// Polling interval when waiting for output or child process exit
+const OUTPUT_POLL_INTERVAL_MS: u64 = 10;
+
+/// Strategy for capturing progressive output snapshots
+#[derive(Debug, Clone)]
+pub enum CaptureStrategy {
+ /// Capture snapshots at time intervals (less deterministic, captures real-time behavior)
+ TimeInterval(Duration),
+ /// Capture snapshots at byte count milestones (more deterministic than time-based,
+ /// suitable for behavioral testing but not exact snapshot matching)
+ ByteInterval(usize),
+}
+
+/// Options for capturing progressive output
+#[derive(Debug, Clone)]
+pub struct ProgressiveCaptureOptions {
+ /// Strategy for when to capture snapshots
+ pub strategy: CaptureStrategy,
+ /// Maximum time to wait for output (default: 10s)
+ pub timeout: Duration,
+ /// Terminal size in (rows, cols) (default: 48 rows x 150 cols - matches test suite conventions)
+ pub terminal_size: (u16, u16),
+ /// Minimum change required between snapshots
+ /// - For TimeInterval: minimum time between different snapshots (default: 10ms)
+ /// - For ByteInterval: minimum bytes between snapshots (default: 100 bytes)
+ pub min_change_threshold: usize,
+}
+
+impl Default for ProgressiveCaptureOptions {
+ fn default() -> Self {
+ Self {
+ strategy: CaptureStrategy::TimeInterval(Duration::from_millis(50)),
+ timeout: Duration::from_secs(10),
+ terminal_size: (48, 150),
+ min_change_threshold: 100, // 100 bytes minimum change
+ }
+ }
+}
+
+impl ProgressiveCaptureOptions {
+ /// Create options with byte-based capture (more deterministic than time-based, for behavioral testing)
+ pub fn with_byte_interval(byte_interval: usize) -> Self {
+ Self {
+ strategy: CaptureStrategy::ByteInterval(byte_interval),
+ timeout: Duration::from_secs(10),
+ terminal_size: (48, 150),
+ min_change_threshold: 100,
+ }
+ }
+}
+
+/// A single snapshot of terminal output at a point in time
+#[derive(Debug, Clone)]
+pub struct OutputSnapshot {
+ /// Time elapsed since command started
+ pub timestamp: Duration,
+ /// The visible text on screen (what user would see)
+ visible_text: String,
+}
+
+impl OutputSnapshot {
+ /// Get the visible text (with ANSI codes stripped, formatted for humans)
+ pub fn visible_text(&self) -> &str {
+ &self.visible_text
+ }
+}
+
+/// Collection of progressive output snapshots
+#[derive(Debug)]
+pub struct ProgressiveOutput {
+ /// Individual snapshots captured during execution
+ pub stages: Vec<OutputSnapshot>,
+ /// Exit code of the command
+ pub exit_code: i32,
+ /// Total execution time
+ pub total_duration: Duration,
+}
+
+impl ProgressiveOutput {
+ /// Get the initial snapshot (what appeared first)
+ pub fn initial(&self) -> &OutputSnapshot {
+ self.stages.first().expect("No snapshots captured")
+ }
+
+ /// Get the final snapshot (complete output)
+ pub fn final_snapshot(&self) -> &OutputSnapshot {
+ self.stages.last().expect("No snapshots captured")
+ }
+
+ /// Get the final visible text (convenience for final_snapshot().visible_text())
+ pub fn final_output(&self) -> &str {
+ self.final_snapshot().visible_text()
+ }
+
+ /// Get a snapshot at approximately the given timestamp
+ pub fn snapshot_at(&self, target: Duration) -> &OutputSnapshot {
+ self.stages
+ .iter()
+ .min_by_key(|s| s.timestamp.abs_diff(target))
+ .expect("No snapshots captured")
+ }
+
+ /// Get snapshots at regular intervals (useful for showing progression)
+ pub fn samples(&self, count: usize) -> Vec<&OutputSnapshot> {
+ if self.stages.is_empty() || count == 0 {
+ return vec![];
+ }
+
+ if count >= self.stages.len() {
+ return self.stages.iter().collect();
+ }
+
+ let step = (self.stages.len() - 1) as f64 / (count - 1) as f64;
+ (0..count)
+ .map(|i| {
+ let index = ((i as f64 * step).round() as usize).min(self.stages.len() - 1);
+ &self.stages[index]
+ })
+ .collect()
+ }
+
+ /// Count how many times dots (⋯) appear in each snapshot
+ /// Useful for verifying progressive data filling
+ pub fn dots_per_stage(&self) -> Vec<usize> {
+ self.stages
+ .iter()
+ .map(|s| s.visible_text.matches('⋯').count())
+ .collect()
+ }
+
+ /// Verify that dots decrease over time (data is filling in)
+ ///
+ /// This handles the typical progressive rendering pattern:
+ /// 1. Header appears (0 dots)
+ /// 2. Rows appear with placeholders (dots increase)
+ /// 3. Data fills in (dots decrease)
+ ///
+ /// Verification succeeds if dots eventually decrease from their peak,
+ /// indicating progressive data filling.
+ pub fn verify_progressive_filling(&self) -> Result<(), String> {
+ let dots = self.dots_per_stage();
+ if dots.is_empty() {
+ return Err("No snapshots captured".to_string());
+ }
+
+ if dots.len() < 2 {
+ return Err("Need at least 2 snapshots to verify progressive filling".to_string());
+ }
+
+ // Find the peak (maximum) dots
+ let (peak_index, peak_dots) = dots
+ .iter()
+ .enumerate()
+ .max_by_key(|(_, count)| *count)
+ .unwrap();
+ let peak_dots = *peak_dots;
+
+ // Check if any dots were observed
+ if peak_dots == 0 {
+ return Err(format!(
+ "Progressive filling verification failed: no placeholder dots observed in any snapshot. \
+ This suggests data filled too quickly to observe progressive rendering, or the command \
+ doesn't use progressive rendering. Dots progression: {:?}",
+ dots
+ ));
+ }
+
+ // Verify dots decrease after peak
+ if peak_index == dots.len() - 1 {
+ return Err(format!(
+ "Progressive filling verification failed: peak dots ({}) at final snapshot. \
+ Expected dots to decrease after peak. Dots progression: {:?}",
+ peak_dots, dots
+ ));
+ }
+
+ // Check that final dots are less than peak
+ let final_dots = dots[dots.len() - 1];
+ if final_dots >= peak_dots {
+ return Err(format!(
+ "Progressive filling verification failed: final dots ({}) >= peak dots ({}). \
+ Expected decrease after peak. Dots progression: {:?}",
+ final_dots, peak_dots, dots
+ ));
+ }
+
+ Ok(())
+ }
+}
+
+/// Capture progressive output from a wt command
+///
+/// Executes the command in a PTY and captures multiple snapshots of the terminal
+/// screen as output is rendered. Uses `vt100` terminal emulator to properly
+/// handle ANSI escape sequences (cursor movements, clear line, colors, etc.).
+///
+/// # Arguments
+///
+/// * `repo` - Test repository
+/// * `subcommand` - wt subcommand (e.g., "list")
+/// * `args` - Arguments to the subcommand
+/// * `options` - Capture options (interval, timeout, terminal size)
+///
+/// # Returns
+///
+/// `ProgressiveOutput` containing all captured snapshots and exit code
+pub fn capture_progressive_output(
+ repo: &TestRepo,
+ subcommand: &str,
+ args: &[&str],
+ options: ProgressiveCaptureOptions,
+) -> ProgressiveOutput {
+ let start_time = Instant::now();
+
+ // Create PTY
+ let pty_system = native_pty_system();
+ let pair = pty_system
+ .openpty(PtySize {
+ rows: options.terminal_size.0,
+ cols: options.terminal_size.1,
+ pixel_width: 0,
+ pixel_height: 0,
+ })
+ .unwrap_or_else(|_| {
+ panic!(
+ "Failed to open PTY with size {}x{}",
+ options.terminal_size.0, options.terminal_size.1
+ )
+ });
+
+ // Build command
+ let mut cmd = CommandBuilder::new(get_cargo_bin("wt"));
+ cmd.arg(subcommand);
+ for arg in args {
+ cmd.arg(arg);
+ }
+ cmd.cwd(repo.root_path());
+
+ // Set test environment
+ configure_pty_environment(&mut cmd, repo);
+
+ // Spawn command in PTY
+ let mut child = pair.slave.spawn_command(cmd).unwrap_or_else(|_| {
+ panic!(
+ "Failed to spawn 'wt {}' in PTY at {}",
+ subcommand,
+ repo.root_path().display()
+ )
+ });
+ drop(pair.slave);
+
+ // Create terminal emulator
+ let mut parser = vt100::Parser::new(
+ options.terminal_size.0,
+ options.terminal_size.1,
+ 0, // No scrollback
+ );
+
+ // Read output and capture snapshots
+ let mut reader = pair
+ .master
+ .try_clone_reader()
+ .expect("Failed to clone PTY reader (master pseudo-terminal)");
+
+ let mut snapshots = Vec::new();
+ let mut last_snapshot_time = Instant::now();
+ let mut last_snapshot_bytes = 0;
+ let mut last_snapshot_text = String::new();
+ let mut total_bytes = 0;
+
+ loop {
+ let mut temp_buf = [0u8; 4096];
+
+ match reader.read(&mut temp_buf) {
+ Ok(0) => break, // EOF
+ Ok(n) => {
+ total_bytes += n;
+
+ // Feed bytes to terminal emulator
+ parser.process(&temp_buf[..n]);
+
+ // Check if we should take a snapshot based on strategy
+ let should_snapshot = match options.strategy {
+ CaptureStrategy::TimeInterval(interval) => {
+ last_snapshot_time.elapsed() >= interval
+ }
+ CaptureStrategy::ByteInterval(byte_interval) => {
+ total_bytes >= last_snapshot_bytes + byte_interval
+ }
+ };
+
+ if should_snapshot {
+ let screen = parser.screen();
+ let current_text = screen.contents();
+
+ // Only snapshot if output changed and meets minimum threshold
+ let meets_threshold = match options.strategy {
+ CaptureStrategy::TimeInterval(_) => {
+ last_snapshot_time.elapsed().as_millis()
+ >= options.min_change_threshold as u128
+ }
+ CaptureStrategy::ByteInterval(_) => {
+ total_bytes >= last_snapshot_bytes + options.min_change_threshold
+ }
+ };
+
+ if current_text != last_snapshot_text && meets_threshold {
+ snapshots.push(OutputSnapshot {
+ timestamp: start_time.elapsed(),
+ visible_text: current_text.clone(),
+ });
+
+ last_snapshot_text = current_text;
+ last_snapshot_time = Instant::now();
+ last_snapshot_bytes = total_bytes;
+ }
+ }
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+ // Check if child exited
+ if let Ok(Some(_)) = child.try_wait() {
+ // Give it a moment to flush final output
+ std::thread::sleep(Duration::from_millis(FINAL_OUTPUT_FLUSH_MS));
+
+ // Read any remaining data
+ loop {
+ match reader.read(&mut temp_buf) {
+ Ok(0) => break,
+ Ok(n) => {
+ total_bytes += n;
+ parser.process(&temp_buf[..n]);
+ }
+ Err(_) => break,
+ }
+ }
+
+ // Capture final snapshot
+ let screen = parser.screen();
+ let final_text = screen.contents();
+ if final_text != last_snapshot_text {
+ snapshots.push(OutputSnapshot {
+ timestamp: start_time.elapsed(),
+ visible_text: final_text,
+ });
+ }
+
+ break;
+ }
+
+ if start_time.elapsed() > options.timeout {
+ panic!(
+ "Timeout waiting for command to complete after {:?}. \
+ Captured {} snapshots, last at {:?}, {} total bytes",
+ options.timeout,
+ snapshots.len(),
+ snapshots.last().map(|s| s.timestamp),
+ total_bytes
+ );
+ }
+
+ std::thread::sleep(Duration::from_millis(OUTPUT_POLL_INTERVAL_MS));
+ }
+ Err(e) => panic!("Failed to read PTY output: {}", e),
+ }
+ }
+
+ // Wait for exit code
+ let exit_status = child
+ .wait()
+ .unwrap_or_else(|_| panic!("Failed to wait for 'wt {}' to exit", subcommand));
+ let exit_code = exit_status.exit_code() as i32;
+ let total_duration = start_time.elapsed();
+
+ ProgressiveOutput {
+ stages: snapshots,
+ exit_code,
+ total_duration,
+ }
+}
+
+/// Configure PTY command with test environment variables
+fn configure_pty_environment(cmd: &mut CommandBuilder, repo: &TestRepo) {
+ // Clear environment
+ cmd.env_clear();
+
+ // Basic environment
+ cmd.env(
+ "HOME",
+ std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()),
+ );
+ cmd.env(
+ "PATH",
+ std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),
+ );
+
+ // Test environment (from TestRepo::test_env_vars)
+ for (key, value) in repo.test_env_vars() {
+ cmd.env(key, value);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_progressive_capture_options_default() {
+ let opts = ProgressiveCaptureOptions::default();
+ assert!(matches!(opts.strategy, CaptureStrategy::TimeInterval(_)));
+ assert_eq!(opts.timeout, Duration::from_secs(10));
+ assert_eq!(opts.terminal_size, (48, 150));
+ assert_eq!(opts.min_change_threshold, 100);
+ }
+
+ #[test]
+ fn test_progressive_capture_options_byte_interval() {
+ let opts = ProgressiveCaptureOptions::with_byte_interval(500);
+ assert!(matches!(opts.strategy, CaptureStrategy::ByteInterval(500)));
+ assert_eq!(opts.timeout, Duration::from_secs(10));
+ assert_eq!(opts.terminal_size, (48, 150));
+ assert_eq!(opts.min_change_threshold, 100);
+ }
+
+ #[test]
+ fn test_progressive_output_samples() {
+ let stages = vec![
+ OutputSnapshot {
+ timestamp: Duration::from_millis(0),
+ visible_text: "stage 0".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(50),
+ visible_text: "stage 1".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(100),
+ visible_text: "stage 2".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(150),
+ visible_text: "stage 3".to_string(),
+ },
+ ];
+
+ let output = ProgressiveOutput {
+ stages,
+ exit_code: 0,
+ total_duration: Duration::from_millis(150),
+ };
+
+ // Test samples
+ let samples = output.samples(2);
+ assert_eq!(samples.len(), 2);
+ assert_eq!(samples[0].visible_text, "stage 0");
+ assert_eq!(samples[1].visible_text, "stage 3");
+
+ let samples = output.samples(3);
+ assert_eq!(samples.len(), 3);
+ assert_eq!(samples[0].visible_text, "stage 0");
+ assert_eq!(samples[1].visible_text, "stage 2");
+ assert_eq!(samples[2].visible_text, "stage 3");
+ }
+
+ #[test]
+ fn test_dots_decrease_verification() {
+ let stages = vec![
+ OutputSnapshot {
+ timestamp: Duration::from_millis(0),
+ visible_text: "⋯ ⋯ ⋯ ⋯ ⋯".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(50),
+ visible_text: "data ⋯ ⋯ ⋯".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(100),
+ visible_text: "data data ⋯".to_string(),
+ },
+ OutputSnapshot {
+ timestamp: Duration::from_millis(150),
+ visible_text: "data data data".to_string(),
+ },
+ ];
+
+ let output = ProgressiveOutput {
+ stages,
+ exit_code: 0,
+ total_duration: Duration::from_millis(150),
+ };
+
+ // Should verify successfully
+ assert!(output.verify_progressive_filling().is_ok());
+
+ // Check dots count
+ let dots = output.dots_per_stage();
+ assert_eq!(dots, vec![5, 3, 1, 0]);
+ }
+}
diff --git a/tests/integration_tests/list_progressive.rs b/tests/integration_tests/list_progressive.rs
new file mode 100644
index 000000000..27ab6985b
--- /dev/null
+++ b/tests/integration_tests/list_progressive.rs
@@ -0,0 +1,271 @@
+//! Tests for progressive rendering in `wt list`
+//!
+//! These tests capture multiple snapshots of the output as it renders,
+//! verifying that the table structure appears first and data fills in progressively.
+
+use crate::common::TestRepo;
+use crate::common::progressive_output::{ProgressiveCaptureOptions, capture_progressive_output};
+
+#[test]
+fn test_list_progressive_rendering_basic() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create a few worktrees to have data to render
+ repo.add_worktree("feature-a", "feature-a");
+ repo.add_worktree("feature-b", "feature-b");
+ repo.add_worktree("bugfix", "bugfix");
+
+ // Capture progressive output using byte-based strategy (deterministic)
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &["--full", "--branches"],
+ ProgressiveCaptureOptions::with_byte_interval(500),
+ );
+
+ // Basic assertions
+ assert_eq!(output.exit_code, 0, "Command should succeed");
+ assert!(
+ output.stages.len() > 1,
+ "Should capture multiple stages, got {}",
+ output.stages.len()
+ );
+
+ // Verify progressive filling: dots should decrease over time
+ output
+ .verify_progressive_filling()
+ .expect("Progressive filling verification failed");
+
+ // Verify table header appears in initial output
+ assert!(
+ output.initial().visible_text().contains("Branch"),
+ "Table header should appear immediately"
+ );
+ assert!(
+ output.initial().visible_text().contains("Status"),
+ "Status column header should appear immediately"
+ );
+
+ // Verify final output has all worktrees
+ let final_text = output.final_output();
+ assert!(final_text.contains("feature-a"), "Should contain feature-a");
+ assert!(final_text.contains("feature-b"), "Should contain feature-b");
+ assert!(final_text.contains("bugfix"), "Should contain bugfix");
+
+ // Final output should have fewer dots than initial (verified by verify_progressive_filling)
+ // No need for additional assertions - verify_progressive_filling already confirms progressive behavior
+}
+
+#[test]
+fn test_list_progressive_rendering_stages() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create several worktrees
+ for i in 1..=5 {
+ repo.add_worktree(&format!("branch-{}", i), &format!("branch-{}", i));
+ }
+
+ // Use byte-based capture for deterministic snapshots
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &["--full"],
+ ProgressiveCaptureOptions::with_byte_interval(400),
+ );
+
+ // Sample 3 stages: beginning, middle, end
+ let samples = output.samples(3);
+ assert_eq!(samples.len(), 3, "Should get 3 sample stages");
+
+ // Verify progression: dots should decrease across stages
+ let dots_counts: Vec<usize> = samples
+ .iter()
+ .map(|s| s.visible_text().matches('⋯').count())
+ .collect();
+
+ // Find peak and verify decrease after it
+ let max_dots = dots_counts.iter().max().copied().unwrap_or(0);
+ let max_index = dots_counts.iter().position(|&d| d == max_dots).unwrap_or(0);
+
+ if max_index < dots_counts.len() - 1 {
+ assert!(
+ dots_counts[dots_counts.len() - 1] < max_dots,
+ "Dots should decrease from peak {} at index {} to final {}. Progression: {:?}",
+ max_dots,
+ max_index,
+ dots_counts[dots_counts.len() - 1],
+ dots_counts
+ );
+ }
+
+ // Verify all branches appear in final sample
+ let final_sample = samples.last().unwrap();
+ for i in 1..=5 {
+ assert!(
+ final_sample
+ .visible_text()
+ .contains(&format!("branch-{}", i)),
+ "Final sample should contain branch-{}",
+ i
+ );
+ }
+}
+
+#[test]
+fn test_list_progressive_dots_decrease() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create multiple worktrees to ensure progressive rendering is observable
+ for i in 1..=5 {
+ repo.add_worktree(&format!("branch-{}", i), &format!("branch-{}", i));
+ }
+
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &["--full"],
+ ProgressiveCaptureOptions::with_byte_interval(600),
+ );
+
+ // Use canonical verification method
+ output
+ .verify_progressive_filling()
+ .expect("Progressive filling verification failed");
+}
+
+#[test]
+fn test_list_progressive_timing() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.add_worktree("feature", "feature");
+
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &[],
+ ProgressiveCaptureOptions::with_byte_interval(600),
+ );
+
+ // Verify timestamps are monotonically increasing
+ for i in 1..output.stages.len() {
+ assert!(
+ output.stages[i].timestamp >= output.stages[i - 1].timestamp,
+ "Timestamps should increase monotonically"
+ );
+ }
+
+ // Verify we captured output quickly (within reasonable time)
+ assert!(
+ output.total_duration.as_secs() < 5,
+ "Command should complete in under 5 seconds, took {:?}",
+ output.total_duration
+ );
+}
+
+#[test]
+fn test_list_progressive_snapshot_at() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.add_worktree("feature", "feature");
+
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &[],
+ ProgressiveCaptureOptions::with_byte_interval(600),
+ );
+
+ // Get snapshot at approximately 100ms
+ let snapshot = output.snapshot_at(std::time::Duration::from_millis(100));
+
+ // Should have some content
+ assert!(
+ !snapshot.visible_text().is_empty(),
+ "Snapshot should have content"
+ );
+
+ // Should be somewhere in the middle of rendering
+ assert!(
+ snapshot.timestamp < output.total_duration,
+ "Snapshot should be before end"
+ );
+}
+
+/// Test with a larger dataset to ensure progressive rendering is visible
+#[test]
+fn test_list_progressive_many_worktrees() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create many worktrees to ensure rendering takes time
+ for i in 1..=10 {
+ repo.add_worktree(&format!("worktree-{:02}", i), &format!("branch-{:02}", i));
+ }
+
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &["--full", "--branches"],
+ ProgressiveCaptureOptions::with_byte_interval(600),
+ );
+
+ // With many worktrees, we should see clear progression
+ assert!(
+ output.stages.len() >= 3,
+ "Should capture at least 3 stages with many worktrees, got {}",
+ output.stages.len()
+ );
+
+ // Verify the initial stage has table structure but incomplete data
+ let initial = output.initial().visible_text();
+ assert!(
+ initial.contains("Branch"),
+ "Initial output should have table header"
+ );
+
+ // Verify final output has all worktrees
+ let final_output = output.final_output();
+ for i in 1..=10 {
+ assert!(
+ final_output.contains(&format!("branch-{:02}", i)),
+ "Final output should contain branch-{:02}",
+ i
+ );
+ }
+
+ // Verify progressive filling happened
+ output
+ .verify_progressive_filling()
+ .expect("Should show progressive data filling");
+}
+
+/// Test that we can capture output even for fast commands
+#[test]
+fn test_list_progressive_fast_command() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Run list without any worktrees (fast)
+ let output = capture_progressive_output(
+ &repo,
+ "list",
+ &[],
+ ProgressiveCaptureOptions::with_byte_interval(600),
+ );
+
+ assert_eq!(output.exit_code, 0, "Command should succeed");
+
+ // Even fast commands should capture at least the final state
+ assert!(
+ !output.stages.is_empty(),
+ "Should capture at least one snapshot"
+ );
+
+ assert!(
+ output.final_output().contains("Branch"),
+ "Should have table header"
+ );
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index ccc55dca0..3f916557d 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -23,6 +23,7 @@ pub mod init;
pub mod internal_flag;
pub mod list;
pub mod list_column_alignment;
+pub mod list_progressive;
pub mod list_pty;
pub mod merge;
pub mod post_start_commands;
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap b/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap
index e8da87fc2..47bb976c8 100644
--- a/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap
@@ -1,5 +1,6 @@
---
source: tests/integration_tests/list.rs
+assertion_line: 81
info:
program: wt
args:
@@ -17,7 +18,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp32fLDs/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpXHXwF0/test-config.toml
---
success: true
exit_code: 0