Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: progress counter overflow in `wt list` progressive rendering (#442)
Maximilian Roos26353b3d8b3e
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 211806ed7..cd9b65b99 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -1022,6 +1022,7 @@ pub fn collect(// Track completed results for footer progresslet mut completed_results = 0;+ let mut progress_overflow = false;// Drain task results with conditional progressive renderinglet drain_outcome = drain_results(@@ -1042,6 +1043,16 @@ pub fn collect(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 progresslet footer_msg = format!("{INFO_SYMBOL} {dim}{footer_base} ({completed_results}/{total_results} loaded){dim:#}"@@ -1160,24 +1171,36 @@ pub fn collect(// Status symbols are now computed during data collection (both modes), no fallback needed- // Display collection errors as warnings (after table rendering)- if !errors.is_empty() {- // Sort for deterministic output (tasks complete in arbitrary order)- errors.sort_by_key(|e| (e.item_idx, e.kind));- let error_lines: Vec<String> = errors- .iter()- .map(|error| {- let name = all_items[error.item_idx].branch_name();- let kind_str: &'static str = error.kind.into();- // Take first line only - git errors can be multi-line with usage hints- let msg = error.message.lines().next().unwrap_or(&error.message);- cformat!("<bold>{}</>: {} ({})", name, kind_str, msg)- })- .collect();- let warning = format!(- "Some git operations failed:\n{}",- format_with_gutter(&error_lines.join("\n"), None)- );+ // Display collection errors/warnings (after table rendering)+ if !errors.is_empty() || progress_overflow {+ let mut warning_parts = Vec::new();++ if !errors.is_empty() {+ // Sort for deterministic output (tasks complete in arbitrary order)+ errors.sort_by_key(|e| (e.item_idx, e.kind));+ let error_lines: Vec<String> = errors+ .iter()+ .map(|error| {+ let name = all_items[error.item_idx].branch_name();+ let kind_str: &'static str = error.kind.into();+ // Take first line only - git errors can be multi-line with usage hints+ let msg = error.message.lines().next().unwrap_or(&error.message);+ cformat!("<bold>{}</>: {} ({})", name, kind_str, msg)+ })+ .collect();+ warning_parts.push(format!(+ "Some git operations failed:\n{}",+ format_with_gutter(&error_lines.join("\n"), None)+ ));+ }++ if progress_overflow {+ // Defensive: should never trigger now that immediate URL sends register expectations,+ // but kept to detect future counting bugs+ warning_parts.push("Progress counter overflow (completed > expected)".to_string());+ }++ let warning = warning_parts.join("\n");crate::output::print(warning_message(&warning))?;// Show issue reporting hint (writes diagnostic file if --verbose was used)diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex c5b71fbb2..272de2ecc 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -741,6 +741,7 @@ pub fn collect_worktree_progressive(// Send URL immediately (before health check) so it appears in normal styling right away.// The health check task will later send url_active to dim if inactive.if let Some(ref url) = item_url {+ expected_results.expect(item_idx, TaskKind::UrlStatus);let _ = tx.send(Ok(TaskResult::UrlStatus {item_idx,url: Some(url.clone()),@@ -781,22 +782,8 @@ pub fn collect_branch_progressive(tx: Sender<Result<TaskResult, TaskError>>,expected_results: &Arc<ExpectedResults>,) {- // Expand URL template for this item (deferred from pre-skeleton)- let item_url = options.url_template.as_ref().and_then(|template| {- let mut vars = std::collections::HashMap::new();- vars.insert("branch", branch_name);- worktrunk::config::expand_template(template, &vars, false).ok()- });-- // Send URL immediately (before health check) so it appears in normal styling right away.- // The health check task will later send url_active to dim if inactive.- if let Some(ref url) = item_url {- let _ = tx.send(Ok(TaskResult::UrlStatus {- item_idx,- url: Some(url.clone()),- active: None,- }));- }+ // Branches without worktrees don't have URLs - there's no directory to run a dev server from.+ // URL templates only make sense for worktrees where post-start hooks can start servers.let ctx = TaskContext {repo_path: repo_path.to_path_buf(),@@ -805,7 +792,7 @@ pub fn collect_branch_progressive(default_branch: Some(default_branch.to_string()),target: Some(target.to_string()),item_idx,- item_url,+ item_url: None,};collect_progressive(ctx, false, options, tx, expected_results);diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rsindex 868378b7e..37936041e 100644--- a/tests/integration_tests/list_config.rs+++ b/tests/integration_tests/list_config.rs@@ -267,6 +267,8 @@ fn test_list_json_no_url_without_template(repo: TestRepo, temp_home: TempDir) {}/// Test URL column with --branches flag+///+/// Only worktrees should have URLs - branches without worktrees can't have running dev servers.#[rstest]fn test_list_url_with_branches_flag(repo: TestRepo, temp_home: TempDir) {// Create a branch without a worktree@@ -298,16 +300,30 @@ url = "http://localhost:{{ branch | hash_port }}"let output = cmd.output().unwrap();let stdout = String::from_utf8_lossy(&output.stdout);- // Parse JSON and verify both worktree and branch have URLs+ // Parse JSONlet json: serde_json::Value = serde_json::from_str(&stdout).unwrap();let items = json.as_array().unwrap();assert_eq!(items.len(), 2); // main worktree + feature branch- // Both items should have URLs- for item in items {- let url = item["url"].as_str().unwrap();- assert!(url.starts_with("http://localhost:"));- }+ // Worktree should have URL, branch should not (no dev server running for branches)+ let worktree = items.iter().find(|i| i["kind"] == "worktree").unwrap();+ let branch = items.iter().find(|i| i["kind"] == "branch").unwrap();++ assert!(+ worktree["url"]+ .as_str()+ .unwrap()+ .starts_with("http://localhost:"),+ "Worktree should have URL"+ );+ assert!(+ branch["url"].is_null(),+ "Branch without worktree should not have URL"+ );+ assert!(+ branch["url_active"].is_null(),+ "Branch without worktree should not have url_active"+ );}/// Test URL with {{ branch }} variable (not hash_port)