Skip to content

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

Add Chrome Trace Format export with timestamp and thread tracking (#559)

Maximilian Roos6a7225899502
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 0a0196c2b..b81c237f4 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -17,16 +17,17 @@
//! - **Batching** — timestamp fetch passes all SHAs to one `git show` command
//! - **Parallelization** — independent commands run concurrently via `join!` macro
//!
-//! **Steady-state (4-6 commands):**
+//! **Steady-state (5-7 commands):**
//!
-//! | Command | Purpose |
-//! |---------|---------|
-//! | `git worktree list --porcelain` | Enumerate worktrees |
-//! | `git config worktrunk.default-branch` | Cached default branch |
-//! | `git show -s --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps for sorting |
-//! | `git config --bool core.bare` | Bare repo check for expected-path logic |
-//! | `git for-each-ref refs/heads` | Only with `--branches` flag |
-//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag |
+//! | Command | Purpose | Parallel |
+//! |---------|---------|----------|
+//! | `git worktree list --porcelain` | Enumerate worktrees | Sequential (required first) |
+//! | `git config worktrunk.default-branch` | Cached default branch | ✓ |
+//! | `git config --bool core.bare` | Bare repo check for expected-path logic | ✓ |
+//! | `git rev-parse --show-toplevel` | Worktree root for project config | ✓ |
+//! | `git for-each-ref refs/heads` | Only with `--branches` flag | ✓ |
+//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag | ✓ |
+//! | `git show -s --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |
//!
//! **Non-git operations (negligible latency):**
//! - Path canonicalization — detect current worktree
@@ -44,11 +45,30 @@
//!
//! ### Post-Skeleton Operations
//!
-//! Everything else runs **after** the skeleton appears:
-//! - `get_switch_previous()` — previous branch detection (updates gutter symbol)
-//! - `effective_integration_target()` — upstream vs local target check
-//! - URL template expansion — parallelized in task spawning
-//! - All computed fields (ahead/behind, diffs, CI status, etc.)
+//! After the skeleton renders, remaining setup runs before spawning the worker thread.
+//! These operations are parallelized using `rayon::scope` with single-level parallelism:
+//!
+//! ```text
+//! Skeleton render
+//! ├─ is_builtin_fsmonitor_enabled() (5ms, sequential - gate)
+//! ├─ rayon::scope(
+//! │ ├─ get_switch_previous() (5ms)
+//! │ ├─ integration_target() (10ms)
+//! │ ├─ start_fsmonitor_daemon × N worktrees (6ms each, all parallel)
+//! │ ) // ~10ms total (max of all spawns)
+//! Worker thread spawns
+//! ```
+//!
+//! **Why fsmonitor check is sequential:** It gates whether daemon starts are needed.
+//! The check is fast (~5ms) and must complete before we know which spawns to add.
+//!
+//! **Why fsmonitor starts are in the parallel scope:** The `git fsmonitor--daemon start`
+//! command returns quickly after signaling the daemon. By the time the worker thread
+//! starts executing `git status` commands, daemons have had time to initialize.
+//!
+//! **Invalid default branch warning:** Uses cached value from `default_branch()` which
+//! ran during pre-skeleton. The `invalid_default_branch_config()` call is a pure cache
+//! read with no git commands.
//!
//! When adding new features, ask: "Can this be computed after skeleton?" If yes, defer it.
//! The skeleton shows `·` placeholder for gutter symbols, filled in when data loads.
@@ -75,8 +95,8 @@ use anyhow::Context;
use color_print::cformat;
use crossbeam_channel as chan;
use dunce::canonicalize;
+use once_cell::sync::OnceCell;
use rayon::prelude::*;
-use rayon_join_macro::join;
use worktrunk::git::{LineDiff, Repository, WorktreeInfo};
use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};
@@ -636,28 +656,6 @@ fn drain_results(
DrainOutcome::Complete
}
-/// Get branches that don't have worktrees.
-///
-/// Returns (branch_name, commit_sha) pairs for all branches without associated worktrees.
-fn get_branches_without_worktrees(
- repo: &Repository,
- worktrees: &[WorktreeInfo],
-) -> anyhow::Result<Vec<(String, String)>> {
- // Get all local branches
- let all_branches = repo.list_local_branches()?;
-
- // Build a set of branch names that have worktrees
- let worktree_branches = worktree_branch_set(worktrees);
-
- // Filter to branches without worktrees
- let branches_without_worktrees: Vec<_> = all_branches
- .into_iter()
- .filter(|(branch_name, _)| !worktree_branches.contains(branch_name.as_str()))
- .collect();
-
- Ok(branches_without_worktrees)
-}
-
fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> std::collections::HashSet<&str> {
worktrees
.iter()
@@ -696,11 +694,78 @@ pub fn collect(
use super::progressive_table::ProgressiveTable;
worktrunk::shell_exec::trace_instant("List collect started");
- // Phase 1: Get worktree list (required for everything else)
- let worktrees = repo.list_worktrees().context("Failed to list worktrees")?;
+ // Phase 1: Parallel fetch of ALL independent git data
+ //
+ // Key insight: most operations don't depend on each other. By running them all
+ // in parallel via rayon::scope, we minimize wall-clock time. Dependencies:
+ //
+ // - worktree list: independent (needed for filtering and SHAs)
+ // - default_branch: independent (git config + verify)
+ // - is_bare: independent (git config, cached for later use)
+ // - url_template: independent (loads project config via show-toplevel)
+ // - local_branches: independent (for-each-ref, but filtering needs worktrees)
+ // - remote_branches: independent (for-each-ref)
+ //
+ // After this scope completes, we have all raw data and can do CPU-only work.
+ let worktrees_cell: OnceCell<anyhow::Result<Vec<WorktreeInfo>>> = OnceCell::new();
+ let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();
+ let url_template_cell: OnceCell<Option<String>> = OnceCell::new();
+ let local_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();
+ let remote_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();
+
+ rayon::scope(|s| {
+ s.spawn(|_| {
+ let _ = worktrees_cell.set(repo.list_worktrees());
+ });
+ s.spawn(|_| {
+ let _ = default_branch_cell.set(repo.default_branch());
+ });
+ s.spawn(|_| {
+ // Populate is_bare cache (value used later via worktree_base)
+ let _ = repo.is_bare();
+ });
+ s.spawn(|_| {
+ let _ = url_template_cell.set(repo.url_template());
+ });
+ s.spawn(|_| {
+ if show_branches {
+ let _ = local_branches_cell.set(repo.list_local_branches());
+ }
+ });
+ s.spawn(|_| {
+ if show_remotes {
+ let _ = remote_branches_cell.set(repo.list_untracked_remote_branches());
+ }
+ });
+ });
+
+ // Extract results
+ let worktrees = worktrees_cell
+ .into_inner()
+ .unwrap()
+ .context("Failed to list worktrees")?;
if worktrees.is_empty() {
return Ok(None);
}
+ let default_branch = default_branch_cell.into_inner().unwrap();
+ let url_template = url_template_cell.into_inner().unwrap();
+
+ // Filter local branches to those without worktrees (CPU-only, no git commands)
+ let branches_without_worktrees = if show_branches {
+ let all_local = local_branches_cell.into_inner().unwrap()?;
+ let worktree_branches = worktree_branch_set(&worktrees);
+ all_local
+ .into_iter()
+ .filter(|(name, _)| !worktree_branches.contains(name.as_str()))
+ .collect()
+ } else {
+ Vec::new()
+ };
+ let remote_branches = if show_remotes {
+ remote_branches_cell.into_inner().unwrap()?
+ } else {
+ Vec::new()
+ };
// Detect current worktree by checking if repo path is inside any worktree.
// This avoids a git command - we just compare canonicalized paths.
@@ -712,27 +777,6 @@ pub fn collect(
.filter(|wt_path| repo_path.starts_with(wt_path))
})
});
-
- // Phase 2: Parallel fetch of independent git data
- // These operations don't depend on each other, only on worktree list.
- // Running them in parallel reduces pre-skeleton time (e.g., ~46ms to ~28ms).
- let (default_branch, branches_without_worktrees, remote_branches) = join!(
- || repo.default_branch(),
- || {
- if show_branches {
- get_branches_without_worktrees(repo, &worktrees)
- } else {
- Ok(Vec::new())
- }
- },
- || {
- if show_remotes {
- repo.list_untracked_remote_branches()
- } else {
- Ok(Vec::new())
- }
- }
- );
// Show warning if user configured a default branch that doesn't exist locally
if let Some(configured) = repo.invalid_default_branch_config() {
let msg =
@@ -742,9 +786,6 @@ pub fn collect(
crate::output::print(worktrunk::styling::hint_message(hint))?;
}
- let branches_without_worktrees = branches_without_worktrees?;
- let remote_branches = remote_branches?;
-
// Main worktree is the worktree on the default branch (if exists), else first non-prunable worktree.
// find_home returns None if all worktrees are prunable or the list is empty.
// TODO: show ellipsis or indicator when default_branch is None and columns are empty
@@ -789,9 +830,7 @@ pub fn collect(
// (paths from git worktree list may differ based on symlinks or working directory)
let main_worktree_canonical = canonicalize(&main_worktree.path).ok();
- // Check if URL template is configured (for layout column allocation).
- // Template expansion is deferred to post-skeleton to minimize time-to-skeleton.
- let url_template = repo.url_template();
+ // URL template already fetched in parallel join (layout needs to know if column is needed)
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
@@ -936,10 +975,56 @@ pub fn collect(
}
// === Post-skeleton computations (deferred to minimize time-to-skeleton) ===
+ //
+ // These operations run in parallel using rayon::scope with single-level parallelism.
+ // See module docs for the timing diagram.
worktrunk::shell_exec::trace_instant("Post-skeleton started");
- // Compute previous_branch and update is_previous on items
- let previous_branch = repo.get_switch_previous();
+ // Collect worktree paths for fsmonitor starts (macOS only, fast, no git commands).
+ // Git's builtin fsmonitor has race conditions under parallel load - pre-starting
+ // daemons before parallel operations avoids hangs.
+ #[cfg(target_os = "macos")]
+ let fsmonitor_worktrees: Vec<_> = if repo.is_builtin_fsmonitor_enabled() {
+ sorted_worktrees
+ .iter()
+ .filter(|wt| !wt.is_prunable())
+ .collect()
+ } else {
+ vec![]
+ };
+ #[cfg(not(target_os = "macos"))]
+ let fsmonitor_worktrees: Vec<&WorktreeInfo> = vec![];
+
+ // Single-level parallelism: all spawns in one rayon::scope.
+ // See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's fsmonitor workaround)
+ // See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same fsmonitor issue)
+ let previous_branch_cell: OnceCell<Option<String>> = OnceCell::new();
+ let integration_target_cell: OnceCell<Option<String>> = OnceCell::new();
+
+ rayon::scope(|s| {
+ // Previous branch lookup (for gutter symbol)
+ s.spawn(|_| {
+ let _ = previous_branch_cell.set(repo.get_switch_previous());
+ });
+
+ // Integration target (upstream if ahead of local, else local)
+ s.spawn(|_| {
+ let _ = integration_target_cell.set(repo.integration_target());
+ });
+
+ // Fsmonitor daemon starts (one spawn per worktree)
+ for wt in &fsmonitor_worktrees {
+ s.spawn(|_| {
+ repo.start_fsmonitor_daemon_at(&wt.path);
+ });
+ }
+ });
+
+ // Extract results from cells
+ let previous_branch = previous_branch_cell.into_inner().flatten();
+ let integration_target = integration_target_cell.into_inner().flatten();
+
+ // Update is_previous on items
if let Some(prev) = previous_branch.as_deref() {
for item in &mut all_items {
if item.branch.as_deref() == Some(prev)
@@ -950,12 +1035,6 @@ pub fn collect(
}
}
- // Effective target for integration checks: upstream if ahead of local, else local.
- // This handles the case where a branch was merged remotely but user hasn't pulled yet.
- // Deferred until after skeleton to avoid blocking initial render.
- // Uses cached integration_target() which returns None if default_branch unknown.
- let integration_target = repo.integration_target();
-
// Batch-fetch ahead/behind counts to identify branches that are far behind.
// This allows skipping expensive merge-base operations for diverged branches, dramatically
// improving performance on repos with many stale branches (e.g., wt select).
@@ -985,28 +1064,6 @@ pub fn collect(
// Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive
// and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.
- // Pre-start fsmonitor daemons on macOS to avoid auto-start races.
- //
- // Git's builtin fsmonitor on macOS has race conditions under parallel load that can
- // cause git commands to hang. When multiple git status commands try to auto-start
- // the daemon simultaneously, they can wedge. Pre-starting the daemons before parallel
- // operations avoids this race.
- //
- // See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's workaround)
- // See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same issue)
- #[cfg(target_os = "macos")]
- {
- if repo.is_builtin_fsmonitor_enabled() {
- // Parallelize daemon starts - explicit `start` is safe to call concurrently
- // (each returns quickly if daemon already running for that worktree).
- sorted_worktrees.par_iter().for_each(|wt| {
- if !wt.is_prunable() {
- repo.start_fsmonitor_daemon_at(&wt.path);
- }
- });
- }
- }
-
// Cache last rendered (unclamped) message per row to avoid redundant updates.
let mut last_rendered_lines: Vec<String> = vec![String::new(); all_items.len()];
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 96e43e51e..ae1d50e7f 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -602,22 +602,40 @@ impl Task for BranchDiffTask {
}
/// Task 5 (worktree only): Working tree diff + status flags
+///
+/// Parallelizes `git status` with `rev-parse --verify` + `diff-tree --quiet` since they're
+/// independent. The `diff-tree` compares committed trees (HEAD vs main), not the working tree,
+/// so it can run while status is scanning the working tree.
pub struct WorkingTreeDiffTask;
impl Task for WorkingTreeDiffTask {
const KIND: TaskKind = TaskKind::WorkingTreeDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
+ use worktrunk::git::TreesMatchResult;
+
// This task is only spawned for worktree items, so worktree path is always present.
let wt = ctx
.branch_ref
.working_tree(&ctx.repo)
.expect("WorkingTreeDiffTask requires a worktree");
- // Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's
- // `git stash create` which needs the index lock.
- let status_output = wt
- .run_command(&["--no-optional-locks", "status", "--porcelain"])
- .map_err(|e| ctx.error(Self::KIND, e))?;
+
+ // Use default_branch (local default branch) for informational display
+ let default_branch = ctx.default_branch();
+
+ // Parallelize: status (reads working tree) || trees_match (compares committed trees)
+ // These are independent - diff-tree compares HEAD vs main trees, not the working tree.
+ let (status_result, trees_match_result) = rayon::join(
+ || {
+ // Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's
+ // `git stash create` which needs the index lock.
+ wt.run_command(&["--no-optional-locks", "status", "--porcelain"])
+ },
+ || wt.trees_match_base(default_branch.as_deref()),
+ );
+
+ let status_output = status_result.map_err(|e| ctx.error(Self::KIND, e))?;
+ let trees_match = trees_match_result.map_err(|e| ctx.error(Self::KIND, e))?;
let (working_tree_status, is_dirty, has_conflicts) =
parse_working_tree_status(&status_output);
@@ -629,11 +647,21 @@ impl Task for WorkingTreeDiffTask {
LineDiff::default()
};
- // Use default_branch (local default branch) for informational display
- let default_branch = ctx.default_branch();
- let working_tree_diff_with_main = wt
- .working_tree_diff_with_base(default_branch.as_deref(), is_dirty)
- .map_err(|e| ctx.error(Self::KIND, e))?;
+ // Compute working tree diff vs main based on trees_match result
+ let working_tree_diff_with_main = match trees_match {
+ TreesMatchResult::NoBaseBranch => Some(LineDiff::default()),
+ TreesMatchResult::BranchNotFound | TreesMatchResult::TreesDiffer => None,
+ TreesMatchResult::TreesMatch { branch } => {
+ if is_dirty {
+ Some(
+ wt.working_tree_diff_vs_ref(branch)
+ .map_err(|e| ctx.error(Self::KIND, e))?,
+ )
+ } else {
+ Some(LineDiff::default())
+ }
+ }
+ };
Ok(TaskResult::WorkingTreeDiff {
item_idx: ctx.item_idx,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 59e6010b6..1b3563387 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -41,7 +41,7 @@ pub use error::{
exit_code,
};
pub use parse::{parse_porcelain_z, parse_untracked_files};
-pub use repository::{Repository, ResolvedWorktree, WorkingTree, set_base_path};
+pub use repository::{Repository, ResolvedWorktree, TreesMatchResult, WorkingTree, set_base_path};
pub use url::{GitRemoteUrl, parse_owner_repo, parse_remote_host, parse_remote_owner};
/// Why branch content is considered integrated into the target branch.
///
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 6e664e6dc..46e807496 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -152,9 +152,12 @@ impl Repository {
// If configured, validate it exists locally
if let Some(ref branch) = configured {
if self.local_branch_exists(branch).unwrap_or(false) {
+ // Valid config - no invalid branch to report
+ let _ = self.cache.invalid_default_branch.set(None);
return Some(branch.clone());
}
- // Configured branch doesn't exist - return None (don't fall back)
+ // Configured branch doesn't exist - cache for warning, return None
+ let _ = self.cache.invalid_default_branch.set(Some(branch.clone()));
log::debug!(
"Configured default branch '{}' doesn't exist locally",
branch
@@ -162,6 +165,9 @@ impl Repository {
return None;
}
+ // Not configured - no invalid branch to report
+ let _ = self.cache.invalid_default_branch.set(None);
+
// Not configured - detect and persist to git config
if let Ok(branch) = self.detect_default_branch() {
let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
@@ -181,18 +187,16 @@ impl Repository {
/// - Configured branch exists locally
///
/// Used to show warnings when the configured branch is invalid.
+ ///
+ /// **Performance:** Calls `default_branch()` internally to ensure the cache is
+ /// populated, but that call is itself cached so subsequent calls are free.
pub fn invalid_default_branch_config(&self) -> Option<String> {
- let configured = self
- .run_command(&["config", "--get", "worktrunk.default-branch"])
- .ok()
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())?;
-
- if self.local_branch_exists(&configured).unwrap_or(false) {
- None
- } else {
- Some(configured)
- }
+ // Ensure default_branch() has populated the cache (no-op if already called)
+ let _ = self.default_branch();
+ self.cache
+ .invalid_default_branch
+ .get()
+ .and_then(|opt| opt.clone())
}
/// Detect the default branch without using worktrunk's cache.
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index b3c18aca8..3ca722ed1 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -43,8 +43,8 @@ mod working_tree;
mod worktrees;
// Re-export WorkingTree
-pub use working_tree::WorkingTree;
pub(super) use working_tree::path_to_logging_context;
+pub use working_tree::{TreesMatchResult, WorkingTree};
// ============================================================================
// Repository Cache
@@ -65,6 +65,9 @@ pub(super) struct RepoCache {
pub(super) is_bare: OnceCell<bool>,
/// Default branch (main, master, etc.)
pub(super) default_branch: OnceCell<Option<String>>,
+ /// Invalid default branch config (set when user configured a non-existent branch).
+ /// Populated by `default_branch()` as a side effect, read by `invalid_default_branch_config()`.
+ pub(super) invalid_default_branch: OnceCell<Option<String>>,
/// Effective integration target (local default branch or upstream if ahead)
pub(super) integration_target: OnceCell<Option<String>>,
/// Primary remote name (None if no remotes configured)
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 64e581863..00db569a0 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -212,20 +212,16 @@ impl<'a> WorkingTree<'a> {
LineDiff::from_numstat(&stdout)
}
- /// Get working tree diff stats vs a base branch, if trees differ.
+ /// Check if HEAD tree matches a base branch tree.
///
- /// When `base_branch` is `None` (main worktree), returns `Some(LineDiff::default())`.
- /// If the base branch tree matches HEAD and the working tree is dirty, computes
- /// the precise diff; otherwise returns zero to indicate trees match.
- /// When trees differ, returns `None` so callers can skip expensive comparisons.
- pub fn working_tree_diff_with_base(
+ /// This runs `rev-parse --verify` + `diff-tree --quiet` and returns the result.
+ /// Can be called directly for parallel execution with `git status`.
+ pub fn trees_match_base<'b>(
&self,
- base_branch: Option<&str>,
- working_tree_dirty: bool,
- ) -> anyhow::Result<Option<LineDiff>> {
+ base_branch: Option<&'b str>,
+ ) -> anyhow::Result<TreesMatchResult<'b>> {
let Some(branch) = base_branch else {
- // Main worktree has no base to compare against
- return Ok(Some(LineDiff::default()));
+ return Ok(TreesMatchResult::NoBaseBranch);
};
// Check if branch exists
@@ -233,7 +229,7 @@ impl<'a> WorkingTree<'a> {
.run_command(&["rev-parse", "--verify", branch])
.is_err()
{
- return Ok(None);
+ return Ok(TreesMatchResult::BranchNotFound);
}
// Check if trees match
@@ -242,14 +238,22 @@ impl<'a> WorkingTree<'a> {
.is_ok();
if trees_match {
- // Trees identical - if working tree is dirty, compute the diff
- if working_tree_dirty {
- Ok(Some(self.working_tree_diff_vs_ref(branch)?))
- } else {
- Ok(Some(LineDiff::default()))
- }
+ Ok(TreesMatchResult::TreesMatch { branch })
} else {
- Ok(None)
+ Ok(TreesMatchResult::TreesDiffer)
}
}
}
+
+/// Result of checking if HEAD tree matches a base branch tree.
+#[derive(Debug, Clone, Copy)]
+pub enum TreesMatchResult<'a> {
+ /// No base branch specified (main worktree).
+ NoBaseBranch,
+ /// Base branch doesn't exist.
+ BranchNotFound,
+ /// Trees differ between HEAD and base branch.
+ TreesDiffer,
+ /// Trees match - includes branch name for computing diff if needed.
+ TreesMatch { branch: &'a str },
+}