Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(picker): make BranchDiff/UpstreamDiff previews self-contained (#2245)
Maximilian Roos1918c3be1551
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex cb486eba7..dd1aa5fd3 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -48,11 +48,13 @@ impl SkimItem for HeaderSkimItem {}/// Common diff rendering: check stat, show stat + full diff if non-empty.-fn compute_diff_preview(args: &[&str], no_changes_msg: &str, width: usize) -> String {+fn compute_diff_preview(+ repo: &Repository,+ args: &[&str],+ no_changes_msg: &str,+ width: usize,+) -> String {let mut output = String::new();- let Ok(repo) = Repository::current() else {- return format!("{no_changes_msg}\n");- };// Check stat output firstlet mut stat_args = args.to_vec();@@ -101,9 +103,13 @@ pub(super) struct WorktreeSkimItem {/// Branch name — also what `output()` returns when this item is/// selected.pub branch_name: String,- /// Skeleton-snapshot of the underlying ListItem. Used by preview- /// computation, which kicks off at skeleton time and doesn't re-run- /// as slow fields arrive.+ /// Skeleton-snapshot of the underlying ListItem. Preview computation+ /// reads only skeleton-time fields (`branch_name`, `head`,+ /// `worktree_data`) and runs git directly for anything else — see+ /// `compute_*_preview` in this file — so the snapshot staying frozen+ /// while slow fields (`counts`, `upstream`) arrive via the list-row+ /// task pipeline (see `commands::list::collect`) is intentional and+ /// correct.pub item: Arc<ListItem>,/// Shared cache for pre-computed previews (all modes)pub preview_cache: PreviewCache,@@ -232,12 +238,13 @@ impl WorktreeSkimItem {/// that the cache always stores display-ready content (no pager subprocess/// needed at render time).pub(super) fn compute_and_page_preview(+ repo: &Repository,item: &ListItem,mode: PreviewMode,width: usize,height: usize,) -> String {- let content = Self::compute_preview(item, mode, width, height);+ let content = Self::compute_preview(repo, item, mode, width, height);match mode {PreviewMode::WorkingTree | PreviewMode::BranchDiff | PreviewMode::UpstreamDiff => {if let Some(pager_cmd) = diff_pager() {@@ -252,22 +259,23 @@ impl WorktreeSkimItem {/// Compute raw preview for any mode.pub(super) fn compute_preview(+ repo: &Repository,item: &ListItem,mode: PreviewMode,width: usize,height: usize,) -> String {match mode {- PreviewMode::WorkingTree => Self::compute_working_tree_preview(item, width),- PreviewMode::Log => Self::compute_log_preview(item, width, height),- PreviewMode::BranchDiff => Self::compute_branch_diff_preview(item, width),- PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(item, width),+ PreviewMode::WorkingTree => Self::compute_working_tree_preview(repo, item, width),+ PreviewMode::Log => Self::compute_log_preview(repo, item, width, height),+ PreviewMode::BranchDiff => Self::compute_branch_diff_preview(repo, item, width),+ PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(repo, item, width),PreviewMode::Summary => Self::loading_placeholder(PreviewMode::Summary),}}/// Compute Tab 1: Working tree preview (uncommitted changes vs HEAD)- fn compute_working_tree_preview(item: &ListItem, width: usize) -> String {+ fn compute_working_tree_preview(repo: &Repository, item: &ListItem, width: usize) -> String {let branch = item.branch_name();let Some(wt_info) = item.worktree_data() else {let reset = Reset;@@ -280,6 +288,7 @@ impl WorktreeSkimItem {let reset = Reset;compute_diff_preview(+ repo,&["-C", &path, "diff", "HEAD"],&cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no uncommitted changes"),width,@@ -287,27 +296,22 @@ impl WorktreeSkimItem {}/// Compute Tab 3: Branch diff preview (line diffs in commits ahead of default branch)- fn compute_branch_diff_preview(item: &ListItem, width: usize) -> String {+ ///+ /// Independent of `item.counts` — `compute_diff_preview`'s empty-diff+ /// fallback covers the ahead=0 case, so the preview is correct even+ /// before the list-row pipeline has populated counts.+ fn compute_branch_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {let branch = item.branch_name();let reset = Reset;- let Ok(repo) = Repository::current() else {- return cformat!(- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits ahead of main\n"- );- };let Some(default_branch) = repo.default_branch() else {return cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits ahead of main\n");};- if item.counts.is_some_and(|c| c.ahead == 0) {- return cformat!(- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits ahead of <bold>{default_branch}</>{reset}\n"- );- }let merge_base = format!("{}...{}", default_branch, item.head());compute_diff_preview(+ repo,&["diff", &merge_base],&cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no file changes vs <bold>{default_branch}</>{reset}"@@ -317,38 +321,59 @@ impl WorktreeSkimItem {}/// Compute Tab 4: Upstream diff preview (ahead/behind vs tracking branch)- fn compute_upstream_diff_preview(item: &ListItem, width: usize) -> String {+ ///+ /// Independent of `item.upstream` — a single+ /// `git rev-list --left-right --count HEAD...@{u}` probes both+ /// existence (non-zero exit when `@{u}` is unresolvable) and counts,+ /// so the preview is correct even before the list-row pipeline has+ /// populated upstream.+ fn compute_upstream_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {let branch = item.branch_name();let reset = Reset;- let Some(active) = item.upstream.as_ref().and_then(|u| u.active()) else {+ let upstream_ref = format!("{branch}@{{u}}");+ let probe_range = format!("{}...{upstream_ref}", item.head());+ let Ok(counts) = repo.run_command(&["rev-list", "--left-right", "--count", &probe_range])+ else {+ return cformat!(+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no upstream tracking branch\n"+ );+ };+ let mut parts = counts.split_whitespace();+ let parsed = parts+ .next()+ .zip(parts.next())+ .and_then(|(a, b)| Some((a.parse::<usize>().ok()?, b.parse::<usize>().ok()?)));+ let Some((ahead, behind)) = parsed else {+ // Unreachable if `rev-list --left-right --count` succeeded —+ // git guarantees two whitespace-separated integers. Fall+ // through to the safe no-upstream message rather than+ // fabricating zeros if git ever changes output format.return cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no upstream tracking branch\n");};- let upstream_ref = format!("{}@{{u}}", branch);-- if active.ahead == 0 && active.behind == 0 {+ if ahead == 0 && behind == 0 {return cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} is up to date with upstream\n");}- if active.ahead > 0 && active.behind > 0 {+ if ahead > 0 && behind > 0 {let range = format!("{}...{}", upstream_ref, item.head());compute_diff_preview(+ repo,&["diff", &range],&cformat!(- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has diverged (⇡{} ⇣{}) but no unique file changes",- active.ahead,- active.behind+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has diverged (⇡{ahead} ⇣{behind}) but no unique file changes"),width,)- } else if active.ahead > 0 {+ } else if ahead > 0 {let range = format!("{}...{}", upstream_ref, item.head());compute_diff_preview(+ repo,&["diff", &range],&cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no unpushed file changes"@@ -358,10 +383,10 @@ impl WorktreeSkimItem {} else {let range = format!("{}...{}", item.head(), upstream_ref);compute_diff_preview(+ repo,&["diff", &range],&cformat!(- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} is behind upstream (⇣{}) but no file changes",- active.behind+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} is behind upstream (⇣{behind}) but no file changes"),width,)@@ -370,7 +395,12 @@ impl WorktreeSkimItem {/// Compute log preview for a worktree item./// This can be called from background threads for pre-computation.- pub(super) fn compute_log_preview(item: &ListItem, width: usize, height: usize) -> String {+ pub(super) fn compute_log_preview(+ repo: &Repository,+ item: &ListItem,+ width: usize,+ height: usize,+ ) -> String {// Minimum preview width to show timestamps (adds ~7 chars: space + 4-char time + space)// Note: preview is typically 50% of terminal width, so 50 = 100-col terminalconst TIMESTAMP_WIDTH_THRESHOLD: usize = 50;@@ -384,12 +414,6 @@ impl WorktreeSkimItem {let head = item.head();let branch = item.branch_name();let reset = Reset;- let Ok(repo) = Repository::current() else {- output.push_str(&cformat!(- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits\n"- ));- return output;- };let Some(default_branch) = repo.default_branch() else {output.push_str(&cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits\n"@@ -472,7 +496,7 @@ impl WorktreeSkimItem {process_log_with_dimming(&log_output, unique_commits.as_ref());if show_timestamps {// Batch fetch stats for all commits- let stats = batch_fetch_stats(&repo, &hashes);+ let stats = batch_fetch_stats(repo, &hashes);output.push_str(&format_log_output(&processed, &stats));} else {// Strip hash markers (SOH...NUL) since we're not using format_log_output@@ -564,6 +588,148 @@ mod tests {);}+ /// Helper: build a test repo with `main` at the initial commit, then a+ /// second commit so branches can diverge from it.+ fn repo_with_main() -> (worktrunk::testing::TestRepo, Repository) {+ let t = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = Repository::at(t.path()).unwrap();+ // Add a second commit on main so later branches have a merge base+ // with a real parent (otherwise `rev-list main...HEAD` walks back+ // to the initial commit unconditionally).+ std::fs::write(t.path().join("main2.txt"), "main2").unwrap();+ repo.run_command(&["add", "main2.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "main2"]).unwrap();+ (t, repo)+ }++ fn item_at(repo: &Repository, branch: &str) -> ListItem {+ let head = repo+ .run_command(&["rev-parse", branch])+ .unwrap()+ .trim()+ .to_string();+ ListItem::new_branch(head, branch.to_string())+ }++ #[test]+ fn branch_diff_empty_when_no_commits_ahead() {+ // A branch at the same commit as main has no commits ahead — the+ // empty-diff fallback message should fire.+ let (_t, repo) = repo_with_main();+ repo.run_command(&["branch", "parity"]).unwrap();+ let item = item_at(&repo, "parity");+ let output = WorktreeSkimItem::compute_branch_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("has no file changes vs"),+ "expected empty-diff fallback, got: {output:?}"+ );+ }++ #[test]+ fn branch_diff_shows_diff_when_commits_ahead() {+ // A branch with a unique commit should produce a non-empty diff.+ let (t, repo) = repo_with_main();+ repo.run_command(&["checkout", "-b", "feature"]).unwrap();+ std::fs::write(t.path().join("feat.txt"), "feature\n").unwrap();+ repo.run_command(&["add", "feat.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "feat"]).unwrap();+ let item = item_at(&repo, "feature");+ let output = WorktreeSkimItem::compute_branch_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("feat.txt"),+ "expected diff to mention feat.txt, got: {output:?}"+ );+ }++ #[test]+ fn upstream_diff_no_tracking_branch() {+ // Branch with no configured upstream should hit the no-upstream path+ // via non-zero exit from `git rev-list --left-right --count HEAD...@{u}`.+ let (_t, repo) = repo_with_main();+ repo.run_command(&["branch", "orphan"]).unwrap();+ let item = item_at(&repo, "orphan");+ let output = WorktreeSkimItem::compute_upstream_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("has no upstream tracking branch"),+ "expected no-upstream message, got: {output:?}"+ );+ }++ /// Sets up a branch that tracks another local branch, so `@{u}` resolves+ /// without needing a remote. This covers all four ahead/behind shapes.+ fn repo_with_tracked_pair() -> (worktrunk::testing::TestRepo, Repository) {+ let (t, repo) = repo_with_main();+ repo.run_command(&["branch", "upstream-base"]).unwrap();+ repo.run_command(&["checkout", "-b", "feature"]).unwrap();+ repo.run_command(&["branch", "--set-upstream-to=upstream-base"])+ .unwrap();+ (t, repo)+ }++ #[test]+ fn upstream_diff_up_to_date() {+ let (_t, repo) = repo_with_tracked_pair();+ let item = item_at(&repo, "feature");+ let output = WorktreeSkimItem::compute_upstream_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("is up to date with upstream"),+ "expected up-to-date message, got: {output:?}"+ );+ }++ #[test]+ fn upstream_diff_ahead_only() {+ let (t, repo) = repo_with_tracked_pair();+ std::fs::write(t.path().join("ahead.txt"), "ahead\n").unwrap();+ repo.run_command(&["add", "ahead.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "ahead"]).unwrap();+ let item = item_at(&repo, "feature");+ let output = WorktreeSkimItem::compute_upstream_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("ahead.txt"),+ "expected diff to mention ahead.txt, got: {output:?}"+ );+ }++ #[test]+ fn upstream_diff_behind_only() {+ let (t, repo) = repo_with_tracked_pair();+ // Advance the upstream (upstream-base) past feature+ repo.run_command(&["checkout", "upstream-base"]).unwrap();+ std::fs::write(t.path().join("behind.txt"), "behind\n").unwrap();+ repo.run_command(&["add", "behind.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "behind"]).unwrap();+ repo.run_command(&["checkout", "feature"]).unwrap();+ let item = item_at(&repo, "feature");+ let output = WorktreeSkimItem::compute_upstream_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("behind.txt"),+ "expected diff to mention behind.txt, got: {output:?}"+ );+ }++ #[test]+ fn upstream_diff_diverged() {+ let (t, repo) = repo_with_tracked_pair();+ // feature has a unique commit+ std::fs::write(t.path().join("feat.txt"), "feat\n").unwrap();+ repo.run_command(&["add", "feat.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "feat"]).unwrap();+ // upstream-base has a unique commit+ repo.run_command(&["checkout", "upstream-base"]).unwrap();+ std::fs::write(t.path().join("upstream.txt"), "upstream\n").unwrap();+ repo.run_command(&["add", "upstream.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "upstream"]).unwrap();+ repo.run_command(&["checkout", "feature"]).unwrap();+ let item = item_at(&repo, "feature");+ let output = WorktreeSkimItem::compute_upstream_diff_preview(&repo, &item, 80);+ // Diverged path runs the diff; symmetric difference includes both files.+ assert!(+ output.contains("feat.txt") || output.contains("upstream.txt"),+ "expected diverged diff, got: {output:?}"+ );+ }+#[test]fn test_render_preview_tabs_ansi_codes() {// Test that ANSI escape sequences properly reset to prevent style bleedingdiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex f815e78f0..d660f0e60 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -308,7 +308,7 @@ pub fn handle_picker(// first-item preview can run in parallel with `collect::collect` below.// Wrapped in `Arc` because the progressive handler (running on the// collect background thread) also calls `spawn_preview`.- let orchestrator = Arc::new(PreviewOrchestrator::new());+ let orchestrator = Arc::new(PreviewOrchestrator::new(repo.clone()));let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);// Speculative warm-up: the picker sorts the current worktree first, anddiff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex f6b75b1f1..eb6a902d4 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -30,10 +30,15 @@ pub(super) struct PreviewOrchestrator {pub(super) cache: PreviewCache,pool: Arc<rayon::ThreadPool>,pending: Arc<AtomicUsize>,+ /// Repository used by preview compute. Captured once at construction+ /// so background tasks see a stable repo binding, and so unit tests+ /// can inject a `TestRepo`-rooted `Repository` instead of relying on+ /// process CWD.+ repo: Repository,}impl PreviewOrchestrator {- pub(super) fn new() -> Self {+ pub(super) fn new(repo: Repository) -> Self {let cache = Arc::new(DashMap::new());let pool = Arc::new(rayon::ThreadPoolBuilder::new()@@ -46,6 +51,7 @@ impl PreviewOrchestrator {cache,pool,pending: Arc::new(AtomicUsize::new(0)),+ repo,}}@@ -64,12 +70,13 @@ impl PreviewOrchestrator {) {let cache = Arc::clone(&self.cache);let (w, h) = dims;+ let repo = self.repo.clone();self.spawn_task(move || {let cache_key = (item.branch_name().to_string(), mode);if cache.contains_key(&cache_key) {return;}- let value = WorktreeSkimItem::compute_and_page_preview(&item, mode, w, h);+ let value = WorktreeSkimItem::compute_and_page_preview(&repo, &item, mode, w, h);cache.insert(cache_key, value);});}@@ -137,6 +144,10 @@ mod tests {use std::fs;use worktrunk::testing::TestRepo;+ fn orch_for(t: &TestRepo) -> PreviewOrchestrator {+ PreviewOrchestrator::new(Repository::at(t.path()).unwrap())+ }+fn dirty_worktree_item() -> (TestRepo, Arc<ListItem>) {let t = TestRepo::new();fs::write(t.path().join("README.md"), "# Project\n").unwrap();@@ -164,9 +175,9 @@ mod tests {/// spawn pipeline silently fails, this catches it without needing skim.#[test]fn orchestrator_populates_cache_for_real_worktree() {- let (_t, item) = dirty_worktree_item();+ let (t, item) = dirty_worktree_item();- let orch = PreviewOrchestrator::new();+ let orch = orch_for(&t);orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));orch.spawn_preview(Arc::clone(&item), PreviewMode::Log, (80, 24));orch.wait_for_idle();@@ -186,9 +197,9 @@ mod tests {#[test]fn duplicate_spawn_short_circuits() {- let (_t, item) = dirty_worktree_item();+ let (t, item) = dirty_worktree_item();- let orch = PreviewOrchestrator::new();+ let orch = orch_for(&t);orch.spawn_preview(Arc::clone(&item), PreviewMode::WorkingTree, (80, 24));orch.wait_for_idle();let first = orch@@ -218,9 +229,9 @@ mod tests {#[test]fn spawn_summary_populates_cache() {let (t, item) = dirty_worktree_item();- let repo = worktrunk::git::Repository::at(t.path()).unwrap();+ let repo = Repository::at(t.path()).unwrap();- let orch = PreviewOrchestrator::new();+ let orch = orch_for(&t);orch.spawn_summary(Arc::clone(&item), "/bin/cat".to_string(), repo);orch.wait_for_idle();@@ -233,7 +244,8 @@ mod tests {#[test]fn dump_cache_json_format() {- let orch = PreviewOrchestrator::new();+ let t = TestRepo::new();+ let orch = orch_for(&t);orch.cache.insert(("branch-a".to_string(), PreviewMode::WorkingTree),"x".to_string(),diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex c28962bee..7d90ca015 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -186,9 +186,9 @@ mod tests {let test = TestRepo::with_initial_commit();let (tx, rx) = crossbeam_channel::unbounded::<Arc<dyn SkimItem>>();let shared_items = Arc::new(Mutex::new(Vec::new()));- let orchestrator = Arc::new(PreviewOrchestrator::new());- let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);let repo = test.repo.clone();+ let orchestrator = Arc::new(PreviewOrchestrator::new(repo.clone()));+ let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);let handler = PickerHandler {tx,shared_items,