Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: picker cache, switch ref resolution, and statusline scans (#2842)
Maximilian Roosd9b8eb12e499
diff --git a/benches/time_to_first_output.rs b/benches/time_to_first_output.rsindex daca32c07..16fec8f23 100644--- a/benches/time_to_first_output.rs+++ b/benches/time_to_first_output.rs@@ -80,7 +80,8 @@ fn bench_first_output(c: &mut Criterion) {});});- // list: exits after skeleton data collection, before render+ // list: stdout is piped here, so first output is the first buffered table+ // line after collection/render preparation, not the progressive skeleton.group.bench_function("list", |b| {b.iter(|| {let output = make_cmd(&["list"]).output().unwrap();@@ -89,6 +90,10 @@ fn bench_first_output(c: &mut Criterion) {"Benchmark command failed:\nstderr: {}",String::from_utf8_lossy(&output.stderr));+ assert!(+ !output.stdout.is_empty(),+ "WORKTRUNK_FIRST_OUTPUT should emit the first stdout line"+ );});});diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex c360e2a48..7dea67c93 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -262,16 +262,34 @@ struct TableRenderPlan {}impl TableRenderPlan {- fn render(mut self) -> anyhow::Result<()> {+ fn render(mut self) -> anyhow::Result<bool> {+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ // `progressive_table` is always `None` here: `collect()` early-exits+ // for `WORKTRUNK_FIRST_OUTPUT` whenever progressive rendering is on+ // (`show_progress || progressive_handler.is_some()`), so this render+ // path runs only in buffered mode.+ print_first_buffered_line(&self.header)?;+ return Ok(true);+ }+if let Some(mut table) = self.progressive_table.take() {table.finalize(self.rows, self.summary)?;} else {print_buffered_table(&self.header, &self.rows, &self.summary);}- Ok(())+ Ok(false)}}+fn print_first_buffered_line(header: &str) -> anyhow::Result<()> {+ use std::io::Write as _;++ let mut stdout = std::io::stdout();+ writeln!(stdout, "{header}")?;+ stdout.flush()?;+ Ok(())+}+fn print_buffered_table(header: &str, rows: &[String], summary: &str) {println!("{header}");for row in rows {@@ -316,12 +334,14 @@ pub struct CollectOptions {/// Captured ref state for this list invocation.///- /// Built once during the pre-skeleton phase by- /// [`Repository::capture_refs_with_ahead_behind`] and shared (cheaply,- /// behind `Arc`) into every task. Tasks resolve target ref names to- /// commit SHAs through this snapshot, then call the `_by_sha` variants- /// of cached methods — bypassing the ambient ref→SHA cache entirely.- /// `None` when capture failed (degraded mode).+ /// Built once during the pre-skeleton phase (or during single-item+ /// population) and shared (cheaply, behind `Arc`) into every task.+ /// Tasks resolve target ref names to commit SHAs through this snapshot,+ /// then call the `_by_sha` variants of cached methods — bypassing the+ /// ambient ref→SHA cache entirely. The full list path may include+ /// batched ahead/behind data; single-item callers intentionally use a+ /// plain ref snapshot and let per-row tasks fall back to per-pair+ /// queries. `None` when capture failed (degraded mode).pub snapshot: Option<std::sync::Arc<worktrunk::git::RefSnapshot>>,/// Whether `WorkingTreeDiffTask` should include untracked files in@@ -1091,9 +1111,12 @@ pub fn collect(.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-output+ // Early exit for benchmarking skeleton render time / progressive+ // time-to-first-output. Buffered/piped TTFP continues to the first real+ // table write below, because there is no skeleton output in that mode.if std::env::var_os("WORKTRUNK_SKELETON_ONLY").is_some()- || std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some()+ || (std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some()+ && (show_progress || progressive_handler.is_some())){return Ok(None);}@@ -1575,8 +1598,10 @@ pub fn collect(),});- if let Some(table_render) = table_render {- table_render.render()?;+ if let Some(table_render) = table_render+ && table_render.render()?+ {+ return Ok(None);}// Status symbols are now computed during data collection (both modes), no fallback needed@@ -1805,11 +1830,11 @@ pub fn populate_item(options.default_branch = repo.default_branch();}if options.snapshot.is_none() {- options.snapshot = match options.default_branch.as_deref() {- Some(db) => repo.capture_refs_with_ahead_behind(db).ok(),- None => repo.capture_refs().ok(),- }- .map(std::sync::Arc::new);+ // Statusline needs one row. Avoid the list path's repo-wide+ // `for-each-ref %(ahead-behind:BASE)` prelude here; the+ // AheadBehind/Upstream tasks already have cached per-pair+ // fallbacks that do work only for this item.+ options.snapshot = repo.capture_refs().ok().map(std::sync::Arc::new);}if options.integration_targets.is_none() {options.integration_targets = optionsdiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 73e766776..158aaed93 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -172,6 +172,48 @@ struct PickerCollector {}impl PickerCollector {+ /// Build removal state from a fresh `Repository` so picker reloads after a+ /// background removal do not reuse the startup worktree inventory cache.+ fn prepare_removal(&self, selected_output: &str) -> anyhow::Result<(Repository, RemoveResult)> {+ let repo = Repository::at(self.repo.discovery_path())?;++ // Validate removal before touching the list. prepare_worktree_removal+ // runs a few git commands (~15-20ms) — acceptable on skim's event loop.+ // Only remove the item and spawn background deletion if this succeeds.+ let caller_path = repo.current_worktree().root().ok();++ // Resolve removal target by path when possible (handles both+ // branched and detached worktrees). Branch-only items won't match any+ // worktree path, so they fall through to Branch.+ let worktree_path = repo.list_worktrees().ok().and_then(|wts| {+ // Match by branch first, then fall back to detached (branch: None).+ let by_branch = wts+ .iter()+ .find(|wt| wt.branch.as_deref() == Some(selected_output));+ let matched = by_branch.or_else(|| wts.iter().find(|wt| wt.branch.is_none()));+ matched.map(|wt| wt.path.clone())+ });++ let result = {+ let config = repo.user_config();+ let target = match &worktree_path {+ Some(path) => RemoveTarget::Path(path),+ None => RemoveTarget::Branch(selected_output),+ };+ repo.prepare_worktree_removal(+ target,+ BranchDeletionMode::SafeDelete,+ false,+ config,+ caller_path,+ None,+ None,+ )?+ };++ Ok((repo, result))+ }+/// Execute a queued removal in the background.////// A `RemovedWorktree` result goes through [`handle_remove_output`] in its@@ -252,40 +294,10 @@ impl CommandCollector for PickerCollector {if let Ok(signal) = std::fs::read_to_string(&self.signal_path) {let selected_output = signal.trim().to_string();if !selected_output.is_empty() {- // Validate removal before touching the list. prepare_worktree_removal- // runs a few git commands (~15-20ms) — acceptable on skim's event loop.- // Only remove the item and spawn background deletion if this succeeds.- let caller_path = self.repo.current_worktree().root().ok();- let config = self.repo.user_config();-- // Resolve removal target by path when possible (handles both- // branched and detached worktrees). Branch-only items won't- // match any worktree path, so they fall through to Branch.- let worktree_path = self.repo.list_worktrees().ok().and_then(|wts| {- // Match by branch first, then fall back to detached (branch: None).- let by_branch = wts- .iter()- .find(|wt| wt.branch.as_deref() == Some(selected_output.as_str()));- let matched = by_branch.or_else(|| wts.iter().find(|wt| wt.branch.is_none()));- matched.map(|wt| wt.path.clone())- });- let target = match &worktree_path {- Some(path) => RemoveTarget::Path(path),- None => RemoveTarget::Branch(&selected_output),- };-- let preparation = self.repo.prepare_worktree_removal(- target,- BranchDeletionMode::SafeDelete,- false,- config,- caller_path,- None,- None,- );+ let preparation = self.prepare_removal(&selected_output);match preparation {- Ok(result) => {+ Ok((planning_repo, result)) => {// Removal validated — remove item from the picker list.//// Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails@@ -305,14 +317,17 @@ impl CommandCollector for PickerCollector {changed_directory: true,..}- ) && let Ok(home) = self.repo.home_path()+ ) && let Some(home) = result.destination_path(){- let _ = std::env::set_current_dir(&home);+ let _ = std::env::set_current_dir(home);+ if let Ok(repo) = Repository::at(home) {+ self.repo = repo;+ }}// Defer actual git removal to a background thread so skim's// event loop stays responsive.- let repo = self.repo.clone();+ let repo = planning_repo.clone();let approvals = Arc::clone(&self.approvals);let _ = std::thread::Builder::new().name(format!("picker-remove-{selected_output}"))@@ -929,7 +944,7 @@ pub mod tests {use super::{PickerAction, PickerCollector, drain_stashed_warnings, resolve_identifier};use crate::commands::worktree::RemoveResult;use std::fs;- use std::sync::Mutex;+ use std::sync::{Arc, Mutex};use worktrunk::config::Approvals;use worktrunk::git::BranchDeletionMode;@@ -1150,6 +1165,134 @@ pub mod tests {assert!(!wt_path.exists(), "detached worktree should be removed");}+ #[test]+ fn test_prepare_removal_refreshes_stale_detached_worktree_cache() {+ let test = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();+ let wt_dir = tempfile::tempdir().unwrap();+ let first_path = wt_dir.path().join("detached-one");+ let second_path = wt_dir.path().join("detached-two");++ for (branch, path) in [+ ("to-detach-one", first_path.as_path()),+ ("to-detach-two", second_path.as_path()),+ ] {+ repo.run_command(&["worktree", "add", "-b", branch, path.to_str().unwrap()])+ .unwrap();+ worktrunk::shell_exec::Cmd::new("git")+ .args(["checkout", "--detach", "HEAD"])+ .current_dir(path)+ .run()+ .unwrap();+ }++ let stale_repo = worktrunk::git::Repository::at(test.path()).unwrap();+ let detached_count = stale_repo+ .list_worktrees()+ .unwrap()+ .iter()+ .filter(|wt| wt.branch.is_none())+ .count();+ assert_eq!(detached_count, 2);++ let first_result = RemoveResult::RemovedWorktree {+ main_path: test.path().to_path_buf(),+ worktree_path: first_path.clone(),+ changed_directory: false,+ branch_name: None,+ deletion_mode: BranchDeletionMode::SafeDelete,+ target_branch: Some("main".to_string()),+ integration_reason: None,+ force_worktree: false,+ expected_path: None,+ removed_commit: None,+ };+ PickerCollector::do_removal(&stale_repo, &first_result, &Approvals::default()).unwrap();+ assert!(+ !first_path.exists(),+ "first detached worktree should be removed"+ );+ assert!(+ second_path.exists(),+ "second detached worktree should remain"+ );++ let state_dir = tempfile::tempdir().unwrap();+ let collector = PickerCollector {+ items: Arc::new(Mutex::new(Vec::new())),+ signal_path: state_dir.path().join("remove"),+ repo: stale_repo,+ approvals: Arc::new(Approvals::default()),+ };++ let (_planning_repo, result) = collector.prepare_removal("(detached)").unwrap();+ let canonical_second = dunce::canonicalize(&second_path).unwrap();+ assert!(+ matches!(+ &result,+ RemoveResult::RemovedWorktree { worktree_path, branch_name: None, .. }+ if dunce::canonicalize(worktree_path).unwrap() == canonical_second+ ),+ "detached picker removal should resolve to the surviving detached worktree"+ );+ }++ /// A branch with no worktree resolves to `RemoveTarget::Branch` — it+ /// matches no worktree path, so `prepare_removal` falls through to the+ /// branch-only disposition rather than a worktree removal.+ #[test]+ fn test_prepare_removal_resolves_branch_only_item() {+ let test = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();++ // A branch at the same commit as main, with no worktree. There are no+ // detached worktrees, so the detached fallback can't capture it.+ repo.run_command(&["branch", "branch-only-feature"])+ .unwrap();++ let state_dir = tempfile::tempdir().unwrap();+ let collector = PickerCollector {+ items: Arc::new(Mutex::new(Vec::new())),+ signal_path: state_dir.path().join("remove"),+ repo,+ approvals: Arc::new(Approvals::default()),+ };++ let (_planning_repo, result) = collector.prepare_removal("branch-only-feature").unwrap();+ assert!(+ matches!(&result, RemoveResult::BranchOnly { branch_name, .. } if branch_name == "branch-only-feature"),+ "a branch with no worktree should resolve to BranchOnly"+ );+ }++ /// A selection that names neither a worktree nor a local branch fails the+ /// `prepare_worktree_removal` validation, so `prepare_removal` returns the+ /// error rather than touching the picker list.+ #[test]+ fn test_prepare_removal_errors_on_unknown_target() {+ let test = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();++ let state_dir = tempfile::tempdir().unwrap();+ let collector = PickerCollector {+ items: Arc::new(Mutex::new(Vec::new())),+ signal_path: state_dir.path().join("remove"),+ repo,+ approvals: Arc::new(Approvals::default()),+ };++ // `RemoveResult` isn't `Debug`; drop the Ok payload so `unwrap_err`+ // (which needs `T: Debug`) can report a failure cleanly.+ let err = collector+ .prepare_removal("no-such-branch")+ .map(|_| ())+ .expect_err("unknown removal target should fail validation");+ assert!(+ err.to_string().contains("no-such-branch"),+ "error should name the unresolved target: {err:#}"+ );+ }+/// A `pre-remove` hook the user hasn't approved must not run when the/// picker removes the worktree — the picker can't prompt mid-render, so/// unapproved project commands are skipped. The git removal still happens.@@ -1199,10 +1342,4 @@ pub mod tests {assert!(!wt_path.exists(), "worktree should be removed");assert!(!marker.exists(), "unapproved pre-remove hook must not run");}-- // Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails at- // runtime due to TypeId mismatch between skim's reader thread and the main- // compilation unit (skim 0.20 bug). The invoke() code path uses output()- // matching instead. Full invoke() tests require interactive skim — verified- // via tmux-cli during development.}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex cf0bc7ea5..b557b5d65 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -99,9 +99,7 @@ enum PrProviderChoice {/// wrapped two-provider error.fn choose_pr_provider(repo: &Repository) -> anyhow::Result<PrProviderChoice> {if let Some(platform_raw) = repo- .load_project_config()- .ok()- .flatten()+ .load_project_config()?.and_then(|c| c.forge_platform().map(str::to_string)){let platform = platform_raw.to_ascii_lowercase();@@ -550,8 +548,13 @@ fn resolve_switch_target(.context("Failed to resolve branch name")?;// Handle remote-tracking ref names (e.g., "origin/username/feature-1" from the picker).- // Strip the remote prefix so DWIM can create a local tracking branch.- if !create && let Some(local_name) = repo.strip_remote_prefix(&resolved_branch) {+ // Strip the remote prefix only when there is no exact local branch/worktree,+ // so a local branch literally named `origin/foo` is not retargeted to `foo`.+ if !create+ && repo.worktree_for_branch(&resolved_branch)?.is_none()+ && !repo.branch(&resolved_branch).exists_locally()?+ && let Some(local_name) = repo.strip_remote_prefix(&resolved_branch)+ {resolved_branch = local_name;}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 5fd8e691b..2a48a287a 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2325,6 +2325,31 @@ fn test_list_progressive_with_branches(mut repo: TestRepo) {});}+#[rstest]+fn test_list_first_output_writes_buffered_stdout(mut repo: TestRepo) {+ repo.add_worktree("feature-bench");++ let output = list_snapshots::command(&repo, repo.root_path())+ .env("WORKTRUNK_FIRST_OUTPUT", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "WORKTRUNK_FIRST_OUTPUT should exit 0: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert_eq!(+ stdout.as_bytes().iter().filter(|&&b| b == b'\n').count(),+ 1,+ "WORKTRUNK_FIRST_OUTPUT should emit exactly the first stdout line; stdout:\n{stdout}"+ );+ assert!(!stdout.trim().is_empty());+ assert!(output.stderr.is_empty());+}+// ============================================================================// Task DAG Mode Tests// ============================================================================diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rsindex d3e037f04..97ffa721e 100644--- a/tests/integration_tests/statusline.rs+++ b/tests/integration_tests/statusline.rs@@ -122,6 +122,36 @@ fn test_statusline_commits_ahead(mut repo: TestRepo) {assert_snapshot!(output, @"[0m feature [2m↑[22m [32m↑2[0m ^[32m+2");}+#[rstest]+fn test_statusline_does_not_run_repo_wide_ahead_behind_scan(repo: TestRepo) {+ for i in 0..12 {+ repo.run_git(&["branch", &format!("unused-{i}")]);+ }++ let output = repo+ .wt_command()+ .args(["list", "statusline"])+ .env("RUST_LOG", "debug")+ .output()+ .expect("statusline should run");+ assert!(+ output.status.success(),+ "statusline failed:\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("for-each-ref"),+ "debug trace should include ref scans so this assertion is meaningful:\n{stderr}"+ );+ assert!(+ !stderr.contains("%(ahead-behind:"),+ "single-row statusline must not run repo-wide ahead/behind scans:\n{stderr}"+ );+}+// --- Claude Code Mode Tests ---/// Create snapshot settings that normalize path output for statusline tests.diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 7bfeb0665..985a1c850 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -212,6 +212,52 @@ fn test_switch_remote_prefix_stripped_slash_in_branch(#[from(repo_with_remote)]);}+/// A local branch literally named like a remote-tracking ref must win over the+/// remote-prefix stripping used for picker/DWIM remote-only branches.+#[rstest]+fn test_switch_remote_prefix_preserves_same_named_local_branch(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ // Remote `collision`, with no local `collision` branch.+ repo.run_git(&["branch", "collision"]);+ repo.run_git(&["push", "origin", "collision"]);+ repo.run_git(&["branch", "-D", "collision"]);++ // Local branch literally named `origin/collision`.+ repo.run_git(&["checkout", "-b", "origin/collision"]);+ fs::write(repo.root_path().join("local-collision.txt"), "local").unwrap();+ repo.run_git(&["add", "."]);+ repo.run_git(&["commit", "-m", "Local origin/collision"]);+ repo.run_git(&["checkout", "main"]);++ let output = repo+ .wt_command()+ .args(["switch", "origin/collision"])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "switch should succeed; stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let worktrees = repo.git_output(&["worktree", "list", "--porcelain"]);+ assert!(+ worktrees.contains("branch refs/heads/origin/collision"),+ "should create worktree for local origin/collision, not stripped collision: {worktrees}"+ );++ let stripped_branch = repo+ .git_command()+ .args(["show-ref", "--verify", "refs/heads/collision"])+ .run()+ .unwrap();+ assert!(+ !stripped_branch.status.success(),+ "switch must not create stripped local branch collision"+ );+}+/// When a branch exists on multiple remotes, DWIM should fail with an error/// since git can't determine which remote to track.#[rstest]@@ -4320,6 +4366,65 @@ fn test_switch_pr_forge_platform_invalid_bails(#[from(repo_with_remote)] repo: T});}+/// Malformed project config must fail closed before `pr:` provider fallback.+/// Otherwise an intended `forge.platform` override on an opaque/self-hosted+/// remote can be ignored and route to the wrong CLI.+#[rstest]+fn test_switch_pr_malformed_project_config_bails_before_provider_selection(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://git.internal.example.com/owner/test-repo.git",+ ]);++ let project_config = repo.root_path().join(".config/wt.toml");+ fs::create_dir_all(project_config.parent().unwrap()).unwrap();+ fs::write(&project_config, "[forge]\nplatform = [\"gitea\"\n").unwrap();++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ MockConfig::new("gh")+ .version("gh version 2.0.0 (mock)")+ .command(+ "repo set-default --view",+ MockResponse::output("owner/test-repo\n"),+ )+ .command(+ "api",+ MockResponse::stderr("GH provider fallback was invoked\n").with_exit_code(42),+ )+ .command("_default", MockResponse::exit(42))+ .write(&mock_bin);++ let output = {+ let mut cmd = repo.wt_command();+ cmd.args(["switch", "pr:101"]);+ configure_mock_cli_env(&mut cmd, &mock_bin);+ cmd.output().unwrap()+ };++ assert!(+ !output.status.success(),+ "switch should fail on malformed project config"+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Failed to load project config"),+ "expected project-config load error, got:\n{stderr}"+ );+ assert!(+ stderr.contains("failed to parse"),+ "expected TOML parse diagnostic, got:\n{stderr}"+ );+ assert!(+ !stderr.contains("GH provider fallback was invoked"),+ "provider fallback should not run after malformed project config:\n{stderr}"+ );+}+/// With no parseable remote URL, dispatch defaults to GitHub. Without `gh`/// installed the GitHub provider bails with the install hint — a single,/// readable error rather than a wrapped two-provider message.